// Főalkalmazás — bejelentkezés, szerep-váltás, navigáció

const { useState, useEffect, useReducer } = React;

const Login = ({ onLogin }) => {
  const [pickedUser, setPickedUser] = useState(null);
  const [pwd, setPwd] = useState('');
  const [pwdErr, setPwdErr] = useState('');
  const [busy, setBusy] = useState(false);
  const [query, setQuery] = useState('');
  const pwdRef = React.useRef(null);
  const searchRef = React.useRef(null);

  React.useEffect(() => {
    if (pickedUser && pwdRef.current) pwdRef.current.focus();
    else if (!pickedUser && searchRef.current) searchRef.current.focus();
  }, [pickedUser]);

  const users = React.useMemo(() => {
    const all = (window.USERS || []).slice().sort((a, b) =>
      a.name.localeCompare(b.name, 'hu', { sensitivity: 'base' })
    );
    const q = query.trim().toLowerCase();
    if (!q) return all;
    return all.filter(u =>
      u.name.toLowerCase().includes(q) ||
      (u.email || '').toLowerCase().includes(q)
    );
  }, [query]);

  const tryLogin = async () => {
    if (pwd.length < 1) { setPwdErr('Add meg a jelszót'); return; }
    setBusy(true);
    setPwdErr('');
    try {
      await window.api.login(pickedUser.id, pwd);
      await window.refreshData();
      onLogin(window.CURRENT_USER || pickedUser);
    } catch (err) {
      if (err && err.status === 401) {
        setPwdErr('Hibás jelszó');
      } else {
        setPwdErr(window.apiErrorMessage(err));
      }
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="login-bg">
      <div className="login-card fade-in">
        <div className="login-brand">
          <img src="assets/H1_logo.png" alt="H1" className="login-logo"/>
          <div className="login-title">H1</div>
          <div className="login-subtitle">Újáépítés</div>
        </div>

        {!pickedUser ? (
          <>
            <div className="login-search">
              <Icon name="search" size={16}/>
              <input
                ref={searchRef}
                type="text"
                className="input"
                value={query}
                onChange={e => setQuery(e.target.value)}
                placeholder="Keresés név vagy e-mail alapján…"
                autoComplete="off"
                spellCheck={false}
              />
              {query && (
                <button className="login-search-clear" onClick={() => setQuery('')} aria-label="Törlés">
                  <Icon name="x" size={14}/>
                </button>
              )}
            </div>
            <div className="login-user-list">
              {users.length === 0 ? (
                <div className="muted" style={{ fontSize: 13, textAlign: 'center', padding: '24px 0' }}>
                  Nincs találat
                </div>
              ) : users.map(u => (
                <button key={u.id} className="login-user-row tap" onClick={() => setPickedUser(u)}>
                  <Avatar user={u} size="md"/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="login-user-name">{u.name}</div>
                  </div>
                  <Icon name="chevron-r" size={16}/>
                </button>
              ))}
            </div>
          </>
        ) : (
          <>
            <button className="btn ghost sm" onClick={() => { setPickedUser(null); setPwd(''); setPwdErr(''); }} style={{ marginBottom: 14, paddingLeft: 0, whiteSpace: 'nowrap' }}>
              <Icon name="arrow-l" size={14}/> Vissza
            </button>
            <div className="login-selected">
              <Avatar user={pickedUser} size="lg"/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 600 }}>{pickedUser.name}</div>
              </div>
            </div>
            <div className="field">
              <label className="label">Jelszó</label>
              <input ref={pwdRef} type="password" className="input" value={pwd}
                onChange={e => { setPwd(e.target.value); setPwdErr(''); }}
                onKeyDown={e => e.key === 'Enter' && tryLogin()}
                placeholder="••••••••"
                autoComplete="current-password"
                style={pwdErr ? { borderColor: 'var(--danger)' } : {}}/>
              {pwdErr && <div style={{ color: 'var(--danger)', fontSize: 12, marginTop: 6 }}>{pwdErr}</div>}
            </div>
            <button className="btn primary full lg" onClick={tryLogin} disabled={busy} style={{ marginTop: 10, opacity: busy ? 0.6 : 1 }}>
              <Icon name="lock" size={16}/> {busy ? 'Belépés…' : 'Belépés'}
            </button>
          </>
        )}
      </div>
      <div className="muted" style={{ fontSize: 11, marginTop: 14, fontFamily: 'Inter', letterSpacing: '0.04em' }}>
        v1.0
      </div>
    </div>
  );
};

// === Fő app ===
const App = () => {
  const [user, setUser] = useState(window.CURRENT_USER || null);
  const [view, setView] = useState('home');
  const [logger, setLogger] = useState(false);
  const [approvalLog, setApprovalLog] = useState(null);
  const [payoutContractor, setPayoutContractor] = useState(null);
  const [showInvoice, setShowInvoice] = useState(false);
  const [showChat, setShowChat] = useState(false);
  const [toast, setToast] = useState(null);
  const [, force] = useReducer(x => x + 1, 0);

  // Subscribe to global data refreshes — every successful mutation fires
  // window.dispatchEvent(new CustomEvent('h1:data')), which re-renders the
  // whole tree from the freshly bootstrapped window.X arrays.
  useEffect(() => {
    const onData = () => {
      // Keep the local user reference in sync with the latest USERS list.
      if (user) {
        const fresh = window.USERS.find(u => u.id === user.id);
        if (fresh) setUser(fresh);
      }
      force();
    };
    window.addEventListener('h1:data', onData);
    return () => window.removeEventListener('h1:data', onData);
  }, [user]);

  // On mount, ask the server who is logged in (BOOT may have been emitted
  // for an empty session if the SSR include failed). The response also
  // refills window.X globals, so we just take currentUser.
  useEffect(() => {
    if (user) return; // already populated from BOOT
    (async () => {
      try {
        await window.api.bootstrap();
        if (window.CURRENT_USER) setUser(window.CURRENT_USER);
        force();
      } catch (e) {
        // Stay on Login.
      }
    })();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const showToast = (msg) => {
    setToast(msg);
    setTimeout(() => setToast(null), 2500);
  };

  if (!user) {
    return <Login onLogin={u => { setUser(u); setView('home'); }}/>;
  }

  const handleSubmitLog = async (data) => {
    try {
      const fd = new FormData();
      fd.append('phase_id', String(data.phaseId));
      fd.append('parent_task_id', String(data.parentTaskId));
      fd.append('log_date', data.date);
      fd.append('hourly_rate', String(data.hourlyRate || 0));
      fd.append('material_cost', String(data.materialCost || 0));
      fd.append('description', data.description || '');
      fd.append('entry_type', data.entryType === 'labor' ? 'work' : data.entryType);
      fd.append('tiers', JSON.stringify(data.tiers || []));
      (data.photoFiles || []).forEach(f => fd.append('photos[]', f));
      await window.api.workLogs.create(fd);
      await window.refreshData();
      setLogger(false);
      showToast('✓ Beküldve jóváhagyásra');
    } catch (err) {
      showToast('Hiba: ' + window.apiErrorMessage(err));
    }
  };

  const handleApprove = async (decision, amount, note) => {
    if (!approvalLog) return;
    try {
      await window.api.workLogs.decision({
        work_log_id: approvalLog.id,
        decision,
        note: note || '',
        approved_amount: decision === 'approved' ? (amount || 0) : 0,
      });
      await window.refreshData();
      setApprovalLog(null);
      showToast(decision === 'approved' ? '✓ Jóváhagyva' : '✓ Elutasítva');
    } catch (err) {
      showToast('Hiba: ' + window.apiErrorMessage(err));
    }
  };

  const handlePayout = async (data) => {
    try {
      const fd = new FormData();
      fd.append('contractor_id', String(data.contractorId));
      fd.append('amount', String(data.originalAmount));
      fd.append('currency', data.currency);
      fd.append('fx_rate', String(data.fxRate));
      fd.append('paid_at', new Date().toISOString().slice(0, 10));
      fd.append('note', data.note || '');
      if (data.invoicePhoto) fd.append('invoice_photo', data.invoicePhoto);
      await window.api.payments.create(fd);
      await window.refreshData();
      setPayoutContractor(null);
      showToast('✓ Kifizetés rögzítve');
    } catch (err) {
      showToast('Hiba: ' + window.apiErrorMessage(err));
    }
  };

  // Nav config szerep szerint
  const navByRole = {
    contractor: [
      { v: 'home',     l: 'Áttekintés', icon: 'meter' },
      { v: 'history',  l: 'Munkáim',  icon: 'list' },
      { v: 'dash',     l: 'Költségvetés',  icon: 'coins' },
      { v: 'timeline', l: 'Ütemterv', icon: 'gantt' },
      { v: 'docs',     l: 'Doksik',   icon: 'docs' },
    ],
    approver: [
      { v: 'home',     l: 'Áttekintés', icon: 'meter' },
      { v: 'inbox',    l: 'Jóváhagyás', icon: 'thumbs-up' },
      { v: 'payouts',  l: 'Kifizetés', icon: 'wallet' },
      { v: 'dash',     l: 'Költségvetés',  icon: 'coins' },
      { v: 'timeline', l: 'Ütemterv', icon: 'gantt' },
      { v: 'docs',     l: 'Doksik',   icon: 'docs' },
    ],
    admin: [
      { v: 'home',     l: 'Áttekintés', icon: 'meter' },
      { v: 'inbox',    l: 'Jóváhagyás', icon: 'thumbs-up' },
      { v: 'dash',     l: 'Költségvetés',  icon: 'coins' },
      { v: 'timeline', l: 'Ütemterv', icon: 'gantt' },
      { v: 'docs',     l: 'Doksik',   icon: 'docs' },
      { v: 'users',    l: 'Beállítások',   icon: 'settings' },
    ],
  };
  const nav = navByRole[user.role];

  // Render content
  const renderView = () => {
    if (user.role === 'contractor') {
      switch (view) {
        case 'home':     return <ContractorHome user={user} setView={setView} openLogger={() => setLogger(true)}/>;
        case 'history':  return <ContractorHistory user={user}/>;
        case 'dash':     return <Dashboard user={user}/>;
        case 'timeline': return <Timeline user={user}/>;
        case 'docs':     return <Documents user={user}/>;
      }
    }
    if (user.role === 'approver') {
      switch (view) {
        case 'home':    return <ApproverHome user={user} setView={setView} openApproval={l => setApprovalLog(l)} openPayout={c => setPayoutContractor(c)}/>;
        case 'inbox':   return <ApproverInbox openApproval={l => setApprovalLog(l)}/>;
        case 'payouts': return <Payouts openPayout={c => setPayoutContractor(c)} openInvoiceScan={() => setShowInvoice(true)}/>;
        case 'dash':    return <Dashboard user={user}/>;
        case 'timeline': return <Timeline user={user}/>;
        case 'docs':    return <Documents user={user}/>;
      }
    }
    if (user.role === 'admin') {
      switch (view) {
        case 'home':        return <AdminHome user={user} setView={setView}/>;
        case 'inbox':       return <ApproverInbox openApproval={l => setApprovalLog(l)}/>;
        case 'dash':        return <Dashboard user={user}/>;
        case 'timeline':    return <Timeline user={user}/>;
        case 'docs':        return <Documents user={user}/>;
        case 'users':       return <AdminUsers/>;
        case 'budget':      return <AdminBudget/>;
        case 'timing':      return <AdminTiming/>;
        case 'permissions': return <AdminPermissions/>;
      }
    }
    return null;
  };

  const roleLabels = { contractor: 'Vállalkozó', approver: 'Jóváhagyó', admin: 'Admin' };

  return (
    <div className="app app-mobile" data-screen-label={view}>
      {/* Top bar */}
      <div className="topbar">
        <Avatar user={user}/>
        <div>
          <h1 style={{ fontSize: 15 }}>H1</h1>
          <div className="sub">{user.name} · <span style={{ color: 'var(--accent-d)' }}>{roleLabels[user.role]}</span></div>
        </div>
        <div className="right">
          <button className="btn ghost sm badge-btn topbar-chat-btn" onClick={() => setShowChat(true)} title="Csapat chat">
            <Icon name="chat" size={22} stroke={2.1}/>
            {(() => {
              const lastRead = window.CHAT_LAST_READ || '1970-01-01';
              const unread = window.MESSAGES.filter(m => m.createdAt > lastRead && m.authorId !== user.id).length;
              return unread > 0 ? <span className="badge">{unread}</span> : null;
            })()}
          </button>

          <button className="btn ghost sm" style={{ padding: 8 }} onClick={async () => {
            try { await window.api.logout(); } catch (e) { /* ignore */ }
            try { await window.refreshData(); } catch (e) { /* ignore */ }
            setUser(null);
            setView('home');
          }} title="Kijelentkezés">
            <Icon name="logout" size={18}/>
          </button>
          <img src="assets/H1_logo.png" alt="H1" className="brand-logo"/>
        </div>
      </div>

      {/* Tartalom */}
      {renderView()}

      {/* FAB — csak vállalkozónak */}
      {user.role === 'contractor' && !logger && (
        <button className="fab" onClick={() => setLogger(true)} aria-label="Új teljesítés">
          <Icon name="plus" size={28} stroke={2.4}/>
        </button>
      )}

      {/* Bottom nav */}
      <div className="bottomnav">
        {nav.map(n => (
          <button key={n.v} className={view === n.v ? 'active' : ''} onClick={() => setView(n.v)}>
            <span className="ico"><Icon name={n.icon} size={20}/></span>
            <span className="label">{n.l}</span>
          </button>
        ))}
      </div>

      {/* Modálok */}
      {logger && <Logger user={user} onClose={() => setLogger(false)} onSubmit={handleSubmitLog}/>}
      {approvalLog && <ApprovalDetail log={approvalLog} onClose={() => setApprovalLog(null)} onDecide={handleApprove}/>}
      {payoutContractor && <PayoutSheet contractor={payoutContractor} onClose={() => setPayoutContractor(null)} onSubmit={handlePayout}/>}
      {showInvoice && <InvoiceScan onClose={() => setShowInvoice(false)} onSave={() => showToast('✓ Számla rögzítve')}/>}

      {showChat && <Chat user={user} onClose={() => setShowChat(false)} onToast={showToast}/>}

      {toast && (
        <div style={{ position: 'fixed', bottom: 90, left: '50%', transform: 'translateX(-50%)', background: 'var(--ink)', color: 'var(--bg)', padding: '10px 16px', borderRadius: 999, fontSize: 13, zIndex: 200, boxShadow: 'var(--shadow-3)', animation: 'slideUp 0.2s' }}>
          {toast}
        </div>
      )}
    </div>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
