// admin-app.jsx — Operations Console (PRODUCTION)

const { useState: useStateAdmin } = React;

function AdminApp() {
  const theme = useTheme('brand', 'sage');
  const auth = useAuth();

  // If not signed in: show login. AdminLogin calls api.login() + api.verifyOtp()
  // and then notifies us via onSignedIn(user).
  if (!auth.authed) {
    return <AdminLogin theme={theme} onSignedIn={() => window.location.reload()}/>;
  }

  // Only admins and referrals may access this console.
  const role = auth.user?.role;
  if (role !== 'admin' && role !== 'referral') {
    return <AdminAccessDenied theme={theme} user={auth.user} onSignOut={auth.signOut}/>;
  }

  return <AdminConsole theme={theme} auth={auth} role={role}/>;
}

// ─── Main console (mounted once auth confirms admin/referral) ────
function AdminConsole({ theme, auth, role }) {
  const [view, setView]   = useStateAdmin('clients');   // 'clients' | 'team'
  const [selectedId, setSelectedId] = useStateAdmin(null);
  const [sheet, setSheet] = useStateAdmin(null);   // 'event' | 'doc' | 'offer' | 'payment' | 'rep' | 'new'
  const [cmdK, setCmdK]   = useStateAdmin(false);
  const [rosterRev, setRosterRev] = useStateAdmin(0); // bump to force re-render after roster update
  const [detailRev, setDetailRev] = useStateAdmin(0); // bump after detail refresh
  const [loadingRoster, setLoadingRoster] = useStateAdmin(true);
  const [rosterErr, setRosterErr] = useStateAdmin(null);

  const client = selectedId ? clientById(selectedId) : null;

  // ─── On mount: load roster + (admin-only) reps + referrals ──
  React.useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        await loadRoster();
        if (role === 'admin') {
          await Promise.all([loadReps(), loadReferrals()]);
        }
        if (!mounted) return;
        // Auto-select first client if any
        if (!selectedId && ADMIN_CLIENTS.length > 0) {
          setSelectedId(ADMIN_CLIENTS[0].id);
        }
      } catch (e) {
        if (mounted) setRosterErr(e);
      } finally {
        if (mounted) setLoadingRoster(false);
      }
    })();
    return () => { mounted = false; };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [role]);

  // ─── When client selection changes: load detail ─────────────
  React.useEffect(() => {
    if (!selectedId) return;
    loadClientDetail(selectedId).then(() => setDetailRev(r => r + 1)).catch(e => {
      console.error('client detail load failed:', e);
    });
  }, [selectedId]);

  // ─── Refresh helpers passed down to sheets so they can refetch after write ──
  const refreshClient = React.useCallback(async () => {
    if (!selectedId) return;
    await loadClientDetail(selectedId);
    setDetailRev(r => r + 1);
  }, [selectedId]);

  const refreshRoster = React.useCallback(async () => {
    await loadRoster();
    setRosterRev(r => r + 1);
  }, []);

  const closeSheet = (didChange) => {
    setSheet(null);
    if (didChange) {
      refreshClient();
      refreshRoster();
    }
  };

  // ⌘K binding
  React.useEffect(() => {
    const onKey = e => {
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') { e.preventDefault(); setCmdK(true); }
      if (e.key === 'Escape') { setSheet(null); setCmdK(false); }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  return (
    <div style={{
      width: '100vw', height: '100vh', overflow: 'hidden',
      background: theme.canvas, color: theme.ink,
      display: 'flex', flexDirection: 'column',
      fontFamily: 'Inter, sans-serif',
    }}>
      {/* Referral role banner */}
      {role === 'referral' && (
        <div style={{
          background: '#FAF6EC', borderBottom: '1px solid #E2C77B',
          padding: '7px 18px',
          fontSize: 11.5, color: '#7A5A1B', fontWeight: 600, letterSpacing: 0.3,
          display: 'flex', alignItems: 'center', gap: 8,
        }}>
          <Icon name="eye" size={13} color="#7A5A1B"/>
          Read-only view · You're signed in as a referral partner. Internal notes and write actions are hidden.
        </div>
      )}

      <AdminTopBar
        theme={theme} role={role} user={auth.user}
        view={view} onChangeView={setView}
        onCmdK={() => setCmdK(true)}
        onSignOut={auth.signOut}
      />

      {view === 'clients' && (
        <div style={{ flex: 1, display: 'flex', minHeight: 0 }}>
          <AdminLeftRail
            theme={theme} role={role}
            selectedId={selectedId} onSelect={setSelectedId}
            onNewClient={() => setSheet('new')}
            loading={loadingRoster} error={rosterErr} rev={rosterRev}
          />
          <AdminClientFile
            theme={theme} role={role} client={client} rev={detailRev}
            onAddEvent={()       => setSheet('event')}
            onLogOffer={()       => setSheet('offer')}
            onUploadDoc={()      => setSheet('doc')}
            onUpdatePayment={()  => setSheet('payment')}
            onAssignRep={()      => setSheet('rep')}
          />
          <AdminRightRail
            theme={theme} role={role} client={client}
            onAddEvent={()       => setSheet('event')}
            onAssignRep={()      => setSheet('rep')}
            onLogOffer={()       => setSheet('offer')}
            onUploadDoc={()      => setSheet('doc')}
            onUpdatePayment={()  => setSheet('payment')}
          />
        </div>
      )}

      {view === 'team' && role === 'admin' && (
        <div style={{ flex: 1, display: 'flex', minHeight: 0 }}>
          <TeamPage theme={theme}/>
        </div>
      )}

      {/* Sheets */}
      {sheet === 'event'   && client && <AddEventSheet      theme={theme} client={client} onClose={closeSheet}/>}
      {sheet === 'doc'     && client && <UploadDocSheet     theme={theme} client={client} onClose={closeSheet}/>}
      {sheet === 'offer'   && client && <LogOfferSheet      theme={theme} client={client} onClose={closeSheet}/>}
      {sheet === 'payment' && client && <UpdatePaymentSheet theme={theme} client={client} onClose={closeSheet}/>}
      {sheet === 'rep'     && client && <AssignRepSheet     theme={theme} client={client} onClose={closeSheet}/>}
      {sheet === 'new'                && <NewClientSheet    theme={theme}                  onClose={(picked) => { closeSheet(true); if (picked) setSelectedId(picked); }}/>}

      {cmdK && <CmdK theme={theme} onClose={() => setCmdK(false)} onPickClient={(id) => { setSelectedId(id); setCmdK(false); }} role={role}/>}
    </div>
  );
}

// ─── Command palette (unchanged from demo, reads from live store) ────
function CmdK({ theme, onClose, onPickClient, role }) {
  const [q, setQ] = React.useState('');
  const inputRef = React.useRef(null);
  React.useEffect(() => { inputRef.current?.focus(); }, []);

  let clients = ADMIN_CLIENTS;
  if (q) {
    const lq = q.toLowerCase();
    clients = clients.filter(c =>
      c.name?.toLowerCase().includes(lq) ||
      c.biz?.toLowerCase().includes(lq) ||
      c.code?.toLowerCase().includes(lq)
    );
  }

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(8,18,40,0.55)',
      zIndex: 300, display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
      paddingTop: '12vh',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 'min(640px, 92vw)',
        background: theme.raised, border: `1px solid ${theme.rule}`,
        borderRadius: 14, overflow: 'hidden',
        boxShadow: '0 30px 80px rgba(0,0,0,0.4)',
      }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12,
          padding: '14px 18px', borderBottom: `1px solid ${theme.rule}`,
        }}>
          <Icon name="search" size={16} color={theme.inkMute}/>
          <input
            ref={inputRef} value={q} onChange={e => setQ(e.target.value)}
            placeholder="Search clients, lenders, payments…"
            style={{ flex: 1, border: 0, outline: 0, fontSize: 16, color: theme.ink, fontFamily: 'inherit', background: 'transparent' }}
          />
          <span style={{ fontSize: 10, color: theme.inkMute, padding: '3px 6px', border: `1px solid ${theme.rule}`, borderRadius: 4, fontFamily: 'JetBrains Mono', fontWeight: 600 }}>ESC</span>
        </div>
        <div className="scroll" style={{ maxHeight: '50vh', overflowY: 'auto' }}>
          {clients.slice(0, 8).map(c => (
            <button key={c.id} onClick={() => onPickClient(c.id)} style={{
              width: '100%', display: 'flex', alignItems: 'center', gap: 12,
              padding: '11px 18px', borderBottom: `1px solid ${theme.rule}`, textAlign: 'left',
            }}>
              <div style={{
                width: 30, height: 30, borderRadius: 99,
                background: theme.canvas2, color: theme.ink,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 10, fontWeight: 700, letterSpacing: 0.5,
              }}>{c.initials}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600, color: theme.ink }}>{c.name}</div>
                <div style={{ fontSize: 11.5, color: theme.inkMute, marginTop: 2 }}>{c.biz} · {c.code}</div>
              </div>
              <span className="tnum" style={{ fontSize: 12, color: theme.inkDim }}>${((c.enrolled || 0) / 1000).toFixed(0)}k</span>
            </button>
          ))}
          {clients.length === 0 && <div style={{ padding: 24, textAlign: 'center', color: theme.inkMute, fontSize: 13 }}>No matches.</div>}
        </div>
        <div style={{
          padding: '10px 18px', borderTop: `1px solid ${theme.rule}`,
          background: theme.canvas, fontSize: 11, color: theme.inkMute,
          display: 'flex', justifyContent: 'space-between',
        }}>
          <span>Search clients by name, business, or ID.</span>
          <span style={{ fontFamily: 'JetBrains Mono' }}>↑↓ navigate · ↵ select</span>
        </div>
      </div>
    </div>
  );
}

// ─── Access denied (e.g. client-role user landing here) ────────
function AdminAccessDenied({ theme, user, onSignOut }) {
  return (
    <div style={{
      width: '100vw', height: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: theme.canvas, color: theme.ink, padding: 40,
    }}>
      <div style={{ textAlign: 'center', maxWidth: 460 }}>
        <Icon name="shield" size={36} color={theme.inkMute}/>
        <h1 className="serif" style={{ fontSize: 28, fontWeight: 500, marginTop: 20, letterSpacing: -0.4 }}>
          This area is for staff and partners.
        </h1>
        <div style={{ fontSize: 14, color: theme.inkDim, marginTop: 12, lineHeight: 1.5 }}>
          You're signed in as {user?.email}, which is a client account. Visit the member portal instead.
        </div>
        <button onClick={onSignOut} style={{
          marginTop: 28, padding: '12px 22px', borderRadius: 10,
          background: theme.surface, color: theme.onSurface, fontWeight: 600, fontSize: 14,
        }}>Sign out</button>
      </div>
    </div>
  );
}

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