// admin-mobile.jsx — Full mobile layout for DebtLift Operations Console

const { useState: useM, useEffect: useE, useCallback: useCB } = React;

function initialsOf(name) {
  return (name || '?').split(/\s+/).map(s => s[0]).slice(0, 2).join('').toUpperCase();
}

function AdminMobileApp() {
  const theme = useTheme('brand', 'sage');
  const auth  = useAuth();
  if (!auth.authed) return <AdminLogin theme={theme} onSignedIn={() => window.location.reload()}/>;
  const role = auth.user?.role;
  if (role !== 'admin' && role !== 'referral') {
    return (
      <div style={{ padding: 40, textAlign: 'center', background: '#F1F5FC', minHeight: '100dvh' }}>
        <Icon name="shield" size={32} color="#7A88A6"/>
        <div style={{ marginTop: 16, fontSize: 15, fontWeight: 600, color: '#0C2557' }}>Access denied</div>
        <button onClick={auth.signOut} style={{ marginTop: 20, padding: '12px 22px', borderRadius: 10, background: '#1E64D6', color: '#fff', fontWeight: 600, fontSize: 14 }}>Sign out</button>
      </div>
    );
  }
  return <MobileConsole theme={theme} auth={auth} role={role}/>;
}

function MobileConsole({ theme, auth, role }) {
  const [view, setView] = useM('clients');
  const [selectedId, setSelectedId] = useM(null);
  const [sheet, setSheet] = useM(null);
  const [detailRev, setDetailRev] = useM(0);
  const [rosterRev, setRosterRev] = useM(0);
  const [loadingRoster, setLoadingRoster] = useM(true);
  const [rosterErr, setRosterErr] = useM(null);

  useE(() => {
    if (!auth.authed) return;
    let mounted = true;
    (async () => {
      try {
        await loadRoster();
        if (role === 'admin') await Promise.all([loadReps(), loadReferrals()]);
        if (!mounted) return;
        if (ADMIN_CLIENTS.length > 0 && !selectedId) setSelectedId(ADMIN_CLIENTS[0].id);
      } catch (e) { if (mounted) setRosterErr(e); }
      finally { if (mounted) setLoadingRoster(false); }
    })();
    return () => { mounted = false; };
  }, [role, auth.authed]);

  useE(() => {
    if (!selectedId) return;
    loadClientDetail(selectedId).then(() => setDetailRev(r => r + 1)).catch(console.error);
  }, [selectedId]);

  const refreshClient = useCB(async () => {
    if (!selectedId) return;
    await loadClientDetail(selectedId);
    setDetailRev(r => r + 1);
  }, [selectedId]);

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

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

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

  if (selectedId && client && view === 'clients') {
    return (
      <div style={{ minHeight: '100dvh', background: theme.canvas, display: 'flex', flexDirection: 'column', fontFamily: 'Inter, sans-serif' }}>
        <MobileDetailView theme={theme} auth={auth} role={role} client={client} rev={detailRev} onBack={() => setSelectedId(null)} onSheet={setSheet} onRefresh={refreshClient}/>
        {sheet === 'event'        && <AddEventSheet      theme={theme} client={client} onClose={closeSheet}/>}
        {sheet === 'doc'          && <UploadDocSheet     theme={theme} client={client} onClose={closeSheet}/>}
        {sheet === 'offer'        && <LogOfferSheet      theme={theme} client={client} onClose={closeSheet}/>}
        {sheet === 'payment'      && <UpdatePaymentSheet theme={theme} client={client} onClose={closeSheet}/>}
        {sheet === 'rep'          && <AssignRepSheet     theme={theme} client={client} onClose={closeSheet}/>}
        {sheet === 'editClient'   && <EditClientSheet    theme={theme} client={client} onClose={closeSheet}/>}
        {sheet === 'deleteClient' && <DeleteClientSheet  theme={theme} client={client} onClose={closeSheet} onDeleted={() => { setSheet(null); setSelectedId(null); refreshRoster(); }}/>}
        {sheet === 'addLender'    && <AddLenderSheet     theme={theme} client={client} onClose={closeSheet}/>}
      </div>
    );
  }

  return (
    <div style={{ minHeight: '100dvh', background: theme.canvas, display: 'flex', flexDirection: 'column', fontFamily: 'Inter, sans-serif' }}>
      <div style={{ background: theme.surface, color: theme.onSurface, padding: 'max(env(safe-area-inset-top), 14px) 16px 12px', position: 'sticky', top: 0, zIndex: 50 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8 }}>
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 2.5, marginBottom: 3 }}>
              <span style={{ width: 3.5, height: 10, background: 'rgba(255,255,255,0.5)', borderRadius: 1.5 }}/>
              <span style={{ width: 3.5, height: 15, background: 'rgba(255,255,255,0.78)', borderRadius: 1.5 }}/>
              <span style={{ width: 3.5, height: 21, background: '#fff', borderRadius: 1.5 }}/>
            </div>
            <span className="serif" style={{ fontSize: 20, fontWeight: 500, color: theme.onSurface, letterSpacing: -0.4, lineHeight: 1 }}>debtlift</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ width: 32, height: 32, borderRadius: 99, background: 'rgba(255,255,255,0.95)', color: theme.surface, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700 }}>{initialsOf(auth.user?.name)}</div>
            <button onClick={auth.signOut} style={{ fontSize: 12, color: 'rgba(255,255,255,0.7)', fontWeight: 500 }}>Sign out</button>
          </div>
        </div>
        {role === 'admin' && (
          <div style={{ display: 'flex', gap: 6, marginTop: 10 }}>
            {[{ id: 'clients', label: 'Clients' }, { id: 'team', label: 'Team' }].map(t => (
              <button key={t.id} onClick={() => setView(t.id)} style={{ padding: '6px 16px', borderRadius: 99, fontSize: 12.5, fontWeight: 600, background: view === t.id ? 'rgba(255,255,255,0.95)' : 'rgba(255,255,255,0.12)', color: view === t.id ? theme.surface : 'rgba(255,255,255,0.85)' }}>{t.label}</button>
            ))}
          </div>
        )}
      </div>
      {view === 'clients' && <MobileClientList theme={theme} role={role} loading={loadingRoster} error={rosterErr} rev={rosterRev} onSelect={setSelectedId} onNew={() => setSheet('new')}/>}
      {view === 'team' && role === 'admin' && <TeamPage theme={theme}/>}
      {sheet === 'new' && <NewClientSheet theme={theme} onClose={(id) => { closeSheet(true); if (id) setSelectedId(id); }}/>}
    </div>
  );
}

function MobileClientList({ theme, role, loading, error, rev, onSelect, onNew }) {
  const [filter, setFilter] = useM('all');
  const [q, setQ] = useM('');
  const pool = ADMIN_CLIENTS;
  const filters = [
    { id: 'all',     label: 'All',     count: pool.length },
    { id: 'Active',  label: 'Active',  count: pool.filter(c => c.status === 'Active').length },
    { id: 'Intake',  label: 'Intake',  count: pool.filter(c => c.status === 'Intake').length },
    { id: 'Settled', label: 'Settled', count: pool.filter(c => c.status === 'Settled').length },
  ];
  let visible = filter === 'all' ? pool : pool.filter(c => c.status === filter);
  if (q) { const lq = q.toLowerCase(); visible = visible.filter(c => c.name?.toLowerCase().includes(lq) || c.biz?.toLowerCase().includes(lq) || c.code?.toLowerCase().includes(lq)); }
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '12px 16px 0', display: 'flex', gap: 10, alignItems: 'center' }}>
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 8, padding: '9px 12px', borderRadius: 10, background: theme.raised, border: '1px solid ' + theme.rule }}>
          <Icon name="search" size={14} color={theme.inkMute}/>
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search clients..." style={{ flex: 1, border: 0, outline: 0, background: 'transparent', fontSize: 14, color: theme.ink, fontFamily: 'inherit' }}/>
        </div>
        {role === 'admin' && (
          <button onClick={onNew} style={{ width: 40, height: 40, borderRadius: 10, background: theme.surface, color: theme.onSurface, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <Icon name="plus" size={18} color={theme.onSurface} strokeWidth={2}/>
          </button>
        )}
      </div>
      <div className="scroll" style={{ display: 'flex', gap: 6, overflowX: 'auto', padding: '10px 16px' }}>
        {filters.map(f => (
          <button key={f.id} onClick={() => setFilter(f.id)} style={{ padding: '6px 12px', borderRadius: 99, whiteSpace: 'nowrap', fontSize: 12, fontWeight: 600, background: filter === f.id ? theme.surface : 'transparent', color: filter === f.id ? theme.onSurface : theme.inkDim, border: '1px solid ' + (filter === f.id ? theme.surface : theme.rule), display: 'flex', alignItems: 'center', gap: 5 }}>
            {f.label}
            <span style={{ fontSize: 10, opacity: 0.7, padding: '1px 5px', borderRadius: 99, background: filter === f.id ? 'rgba(255,255,255,0.18)' : theme.canvas2 }}>{f.count}</span>
          </button>
        ))}
      </div>
      <div className="scroll" style={{ flex: 1, overflowY: 'auto' }}>
        {loading && <div style={{ padding: 40, textAlign: 'center', color: theme.inkMute, fontSize: 13 }}>Loading clients...</div>}
        {!loading && error && <div style={{ padding: 24, textAlign: 'center', color: '#7A2E11', fontSize: 13 }}>Couldn't load roster.</div>}
        {!loading && !error && visible.map(c => (
          <button key={c.id} onClick={() => onSelect(c.id)} style={{ width: '100%', textAlign: 'left', padding: '14px 16px', borderBottom: '1px solid ' + theme.rule, background: 'transparent', display: 'flex', gap: 12, alignItems: 'center' }}>
            <div style={{ width: 40, height: 40, borderRadius: 99, flexShrink: 0, background: theme.canvas2, color: theme.ink, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700 }}>{c.initials}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
                <div style={{ fontSize: 15, fontWeight: 600, color: theme.ink, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.name}</div>
                <span className="tnum" style={{ fontSize: 12, color: theme.inkDim, flexShrink: 0 }}>${((c.enrolled || 0) / 1000).toFixed(0)}k</span>
              </div>
              <div style={{ fontSize: 12.5, color: theme.inkMute, marginTop: 2 }}>{c.biz}</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 5 }}>
                <span style={{ fontSize: 11, fontWeight: 600, color: c.status === 'Active' ? theme.accent.solid : c.status === 'Settled' ? '#2F6A4F' : '#9B6B2F', display: 'flex', alignItems: 'center', gap: 4 }}>
                  <span style={{ width: 5, height: 5, borderRadius: 99, background: c.status === 'Active' ? theme.accent.solid : c.status === 'Settled' ? '#2F6A4F' : '#9B6B2F' }}/>{c.status}
                </span>
                {c.flagsAtRisk && <span style={{ fontSize: 9.5, fontWeight: 700, color: '#B5481D' }}>AT RISK</span>}
              </div>
            </div>
            <Icon name="chevR" size={16} color={theme.inkMute}/>
          </button>
        ))}
        {!loading && !error && visible.length === 0 && <div style={{ padding: 40, textAlign: 'center', color: theme.inkMute, fontSize: 13 }}>{pool.length === 0 ? 'No clients yet.' : 'No clients match.'}</div>}
      </div>
    </div>
  );
}

function MobileDetailView({ theme, auth, role, client, rev, onBack, onSheet, onRefresh }) {
  const [tab, setTab] = useM('overview');
  const [actionsOpen, setActionsOpen] = useM(false);
  const tabs = [
    { id: 'overview', label: 'Overview' },
    { id: 'lenders',  label: 'Lenders' },
    { id: 'activity', label: 'Activity' },
    { id: 'payments', label: 'Payments' },
    { id: 'vault',    label: 'Vault' },
    { id: 'plan',     label: 'Plan' },
  ];
  return (
    <>
      <div style={{ background: theme.surface, color: theme.onSurface, position: 'sticky', top: 0, zIndex: 50 }}>
        <div style={{ padding: 'max(env(safe-area-inset-top), 14px) 16px 10px', display: 'flex', alignItems: 'center', gap: 12 }}>
          <button onClick={onBack} style={{ display: 'flex', alignItems: 'center', gap: 4, color: 'rgba(255,255,255,0.8)', fontSize: 13, fontWeight: 500, flexShrink: 0 }}>
            <Icon name="chevL" size={16} color="rgba(255,255,255,0.8)"/>Clients
          </button>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 16, fontWeight: 600, color: theme.onSurface, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{client.name}</div>
            <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.65)', marginTop: 1 }}>{client.code} · {client.status}</div>
          </div>
          {role === 'admin' && (
            <button onClick={() => setActionsOpen(true)} style={{ width: 34, height: 34, borderRadius: 8, background: 'rgba(255,255,255,0.12)', border: '1px solid rgba(255,255,255,0.2)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <Icon name="moreH" size={16} color={theme.onSurface}/>
            </button>
          )}
        </div>
        {role === 'admin' && (
          <div className="scroll" style={{ display: 'flex', gap: 8, padding: '0 16px 10px', overflowX: 'auto' }}>
            {[
              { label: 'Add event', icon: 'plus',   sheet: 'event' },
              { label: 'Log offer', icon: 'spark',  sheet: 'offer' },
              { label: 'Upload',    icon: 'upload', sheet: 'doc' },
              { label: 'Payment',   icon: 'pay',    sheet: 'payment' },
              { label: 'Assign',    icon: 'user',   sheet: 'rep' },
            ].map(a => (
              <button key={a.label} onClick={() => onSheet(a.sheet)} style={{ padding: '7px 12px', borderRadius: 8, whiteSpace: 'nowrap', background: 'rgba(255,255,255,0.12)', border: '1px solid rgba(255,255,255,0.2)', color: theme.onSurface, fontSize: 12, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0 }}>
                <Icon name={a.icon} size={12} color={theme.onSurface} strokeWidth={2}/>{a.label}
              </button>
            ))}
          </div>
        )}
        <div className="scroll" style={{ display: 'flex', overflowX: 'auto', borderTop: '1px solid rgba(255,255,255,0.15)' }}>
          {tabs.map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{ padding: '10px 14px', fontSize: 12.5, fontWeight: 600, whiteSpace: 'nowrap', flexShrink: 0, color: tab === t.id ? '#fff' : 'rgba(255,255,255,0.6)', borderBottom: '2px solid ' + (tab === t.id ? '#fff' : 'transparent') }}>{t.label}</button>
          ))}
        </div>
      </div>

      <div className="scroll" style={{ flex: 1, overflowY: 'auto', padding: '16px 16px 40px' }}>
        {tab === 'overview'  && <MobileOverviewTab  client={client} theme={theme} role={role}/>}
        {tab === 'lenders'   && <MobileLendersTab   client={client} theme={theme} role={role} onSheet={onSheet}/>}
        {tab === 'activity'  && <MobileActivityTab  client={client} theme={theme} role={role} onSheet={onSheet}/>}
        {tab === 'payments'  && <MobilePaymentsTab  client={client} theme={theme} role={role} onSheet={onSheet}/>}
        {tab === 'vault'     && <MobileVaultTab     client={client} theme={theme} role={role} onSheet={onSheet}/>}
        {tab === 'plan'      && <MobilePlanTab      client={client} theme={theme} role={role} onSheet={onSheet}/>}
      </div>

      {actionsOpen && role === 'admin' && (
        <>
          <div onClick={() => setActionsOpen(false)} style={{ position: 'fixed', inset: 0, background: 'rgba(8,18,40,0.45)', zIndex: 200 }}/>
          <div style={{ position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 201, background: theme.canvas, borderTopLeftRadius: 20, borderTopRightRadius: 20, padding: '16px 0 max(env(safe-area-inset-bottom), 24px)', boxShadow: '0 -20px 60px rgba(0,0,0,0.2)' }}>
            <div style={{ width: 36, height: 4, borderRadius: 99, background: theme.rule, margin: '0 auto 16px' }}/>
            {[
              { label: 'Edit client details', icon: 'gear',   sheet: 'editClient' },
              { label: 'Disable client',      icon: 'x',      sheet: 'deleteClient', danger: true },
            ].map((a, i) => (
              <button key={i} onClick={() => { setActionsOpen(false); onSheet(a.sheet); }} style={{ width: '100%', padding: '16px 20px', display: 'flex', alignItems: 'center', gap: 14, borderBottom: i === 0 ? '1px solid ' + theme.rule : 'none', textAlign: 'left' }}>
                <Icon name={a.icon} size={18} color={a.danger ? '#DC2626' : theme.ink}/>
                <span style={{ fontSize: 15, fontWeight: 500, color: a.danger ? '#DC2626' : theme.ink }}>{a.label}</span>
              </button>
            ))}
          </div>
        </>
      )}
    </>
  );
}

function MobileOverviewTab({ client, theme, role }) {
  const lenders  = lendersForClient(client.id);
  const activity = activityForClient(client.id, role);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ background: theme.raised, border: '1px solid ' + theme.rule, borderRadius: 14, padding: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: theme.inkMute, letterSpacing: 1.4, textTransform: 'uppercase' }}>Plan progress</div>
          <div style={{ fontSize: 12, color: theme.inkDim }}>Month {client.planMonthsDone || 0} of {client.planMonths || 0}</div>
        </div>
        <div className="serif tnum" style={{ fontSize: 40, fontWeight: 500, color: theme.ink, lineHeight: 1, marginBottom: 10 }}>{client.planProgress || 0}%</div>
        <ProgressBar value={client.planProgress || 0} theme={theme} color={theme.accent.solid} height={8}/>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0, marginTop: 14, paddingTop: 12, borderTop: '1px solid ' + theme.rule }}>
          {[
            { label: 'Enrolled', v: client.enrolled || 0, color: theme.ink },
            { label: 'Settled',  v: client.settled  || 0, color: theme.ink },
            { label: 'Saved',    v: client.saved    || 0, color: theme.accent.solid },
          ].map((s, i) => (
            <div key={s.label} style={{ padding: '0 10px', borderLeft: i > 0 ? '1px solid ' + theme.rule : 'none' }}>
              <div style={{ fontSize: 9.5, color: theme.inkMute, fontWeight: 600, letterSpacing: 1, textTransform: 'uppercase' }}>{s.label}</div>
              <div className="serif tnum" style={{ fontSize: 16, fontWeight: 500, color: s.color, marginTop: 3, lineHeight: 1 }}>${((s.v || 0) / 1000).toFixed(0)}k</div>
            </div>
          ))}
        </div>
      </div>
      <div style={{ background: theme.raised, border: '1px solid ' + theme.rule, borderRadius: 14, padding: 16 }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: theme.inkMute, letterSpacing: 1.4, textTransform: 'uppercase', marginBottom: 10 }}>Key facts</div>
        {[
          { k: 'Plan',         v: client.plan || '—' },
          { k: 'Bank',         v: (client.bankBrand || '—') + (client.bankLast4 ? ' ..' + client.bankLast4 : '') },
          { k: 'Next payment', v: client.nextPayment > 0 ? '$' + client.nextPayment.toLocaleString() + ' on ' + client.nextDate : '—' },
          { k: 'Documents',    v: (client.docsCount || 0) + ' files' },
        ].map((r, i, arr) => (
          <div key={r.k} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 0', borderBottom: i < arr.length - 1 ? '1px solid ' + theme.rule : 'none' }}>
            <span style={{ fontSize: 13, color: theme.inkMute }}>{r.k}</span>
            <span className="tnum" style={{ fontSize: 13, fontWeight: 500, color: theme.ink, textAlign: 'right', maxWidth: '55%' }}>{r.v}</span>
          </div>
        ))}
      </div>
      <div>
        <div style={{ fontSize: 11, fontWeight: 600, color: theme.inkMute, letterSpacing: 1.4, textTransform: 'uppercase', marginBottom: 8 }}>Lender ledger ({lenders.length})</div>
        <div style={{ background: theme.raised, border: '1px solid ' + theme.rule, borderRadius: 14, overflow: 'hidden' }}>
          {lenders.slice(0, 4).map((l, i, arr) => (
            <div key={l.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', borderBottom: i < arr.length - 1 ? '1px solid ' + theme.rule : 'none' }}>
              <div style={{ width: 32, height: 32, borderRadius: 8, background: theme.canvas2, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 700, color: theme.ink, flexShrink: 0 }}>{l.short}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: theme.ink }}>{l.name}</div>
                <div className="tnum" style={{ fontSize: 11, color: theme.inkMute, marginTop: 2 }}>Balance ${(l.balance || 0).toLocaleString()}</div>
              </div>
              <StatusPill status={l.status} theme={theme}/>
            </div>
          ))}
          {lenders.length === 0 && <div style={{ padding: 20, textAlign: 'center', color: theme.inkMute, fontSize: 12 }}>No lenders on file.</div>}
        </div>
      </div>
      <div>
        <div style={{ fontSize: 11, fontWeight: 600, color: theme.inkMute, letterSpacing: 1.4, textTransform: 'uppercase', marginBottom: 8 }}>Recent activity</div>
        <div style={{ background: theme.raised, border: '1px solid ' + theme.rule, borderRadius: 14, overflow: 'hidden' }}>
          {activity.slice(0, 3).map((e, i, arr) => <MobileActivityRow key={e.id} e={e} theme={theme} role={role} last={i === arr.length - 1}/>)}
          {activity.length === 0 && <div style={{ padding: 20, textAlign: 'center', color: theme.inkMute, fontSize: 12 }}>No events.</div>}
        </div>
      </div>
    </div>
  );
}

function MobileLendersTab({ client, theme, role, onSheet }) {
  const lenders = lendersForClient(client.id);
  return (
    <div>
      {role === 'admin' && (
        <div style={{ display: 'flex', gap: 8, marginBottom: 14 }}>
          <button onClick={() => onSheet('addLender')} style={{ flex: 1, padding: '10px', borderRadius: 10, background: theme.surface, color: theme.onSurface, fontSize: 13, fontWeight: 600, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
            <Icon name="plus" size={13} color={theme.onSurface} strokeWidth={2}/>Add lender
          </button>
          <button onClick={() => onSheet('offer')} style={{ flex: 1, padding: '10px', borderRadius: 10, background: theme.raised, color: theme.ink, border: '1px solid ' + theme.rule, fontSize: 13, fontWeight: 600, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
            <Icon name="spark" size={13} color={theme.ink}/>Log offer
          </button>
        </div>
      )}
      {lenders.length === 0 ? (
        <div style={{ padding: '40px 20px', textAlign: 'center', color: theme.inkMute }}>
          <Icon name="bank" size={28} color={theme.inkMute}/>
          <div style={{ marginTop: 10, fontSize: 14, fontWeight: 500, color: theme.ink }}>No lenders on file</div>
          <div style={{ marginTop: 6, fontSize: 12 }}>Add lenders to start tracking negotiations.</div>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {lenders.map(l => (
            <div key={l.id} style={{ background: theme.raised, border: '1px solid ' + theme.rule, borderRadius: 12, padding: 14 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
                <div style={{ width: 36, height: 36, borderRadius: 9, background: theme.canvas2, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700, color: theme.ink, flexShrink: 0 }}>{l.short}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: theme.ink }}>{l.name}</div>
                  {l.contactPerson && <div style={{ fontSize: 11.5, color: theme.inkMute, marginTop: 1 }}>{l.contactPerson}</div>}
                </div>
                <StatusPill status={l.status} theme={theme}/>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
                {[
                  { label: 'Balance',    v: '$' + (l.balance || 0).toLocaleString() },
                  { label: 'Settlement', v: l.settlement ? '$' + l.settlement.toLocaleString() : '—' },
                  { label: 'Discount',   v: l.settlement && l.balance ? '-' + Math.round(100 - (l.settlement / l.balance) * 100) + '%' : '—', color: l.settlement ? theme.accent.solid : theme.inkMute },
                ].map(s => (
                  <div key={s.label}>
                    <div style={{ fontSize: 10, color: theme.inkMute, fontWeight: 600, letterSpacing: 1, textTransform: 'uppercase' }}>{s.label}</div>
                    <div className="tnum" style={{ fontSize: 14, fontWeight: 600, color: s.color || theme.ink, marginTop: 2 }}>{s.v}</div>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function MobileActivityTab({ client, theme, role, onSheet }) {
  const [showInternal, setShowInternal] = useM(role === 'admin');
  const raw = activityForClient(client.id, 'admin');
  const events = (role === 'referral' || !showInternal) ? raw.filter(e => e.visibility === 'public') : raw;
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
        {role === 'admin' && (
          <label style={{ display: 'flex', alignItems: 'center', gap: 7, cursor: 'pointer' }}>
            <input type="checkbox" checked={showInternal} onChange={e => setShowInternal(e.target.checked)} style={{ accentColor: theme.surface, width: 15, height: 15 }}/>
            <span style={{ fontSize: 12.5, color: theme.ink, fontWeight: 500 }}>Show internal notes</span>
          </label>
        )}
        {role === 'admin' && (
          <button onClick={() => onSheet('event')} style={{ padding: '8px 12px', borderRadius: 8, background: theme.surface, color: theme.onSurface, fontSize: 12, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="plus" size={12} color={theme.onSurface} strokeWidth={2}/>Add
          </button>
        )}
      </div>
      <div style={{ background: theme.raised, border: '1px solid ' + theme.rule, borderRadius: 14, overflow: 'hidden' }}>
        {events.map((e, i, arr) => <MobileActivityRow key={e.id} e={e} theme={theme} role={role} last={i === arr.length - 1}/>)}
        {events.length === 0 && <div style={{ padding: 40, textAlign: 'center', color: theme.inkMute, fontSize: 13 }}>No events to display.</div>}
      </div>
    </div>
  );
}

function MobileActivityRow({ e, theme, role, last }) {
  const isInternal = e.visibility === 'internal';
  const typeMeta = {
    settled:     { icon: 'check', color: '#2F6A4F', bg: '#DBE7DC' },
    offer:       { icon: 'spark', color: '#1F4A8B', bg: '#D9E5F4' },
    payment:     { icon: 'pay',   color: theme.ink,  bg: theme.canvas2 },
    message:     { icon: 'msg',   color: '#9B6B2F', bg: '#EFDFC5' },
    negotiation: { icon: 'pulse', color: '#7A2E11', bg: '#F5DFC9' },
    document:    { icon: 'doc',   color: theme.ink,  bg: theme.canvas2 },
    internal:    { icon: 'lock',  color: theme.inkDim, bg: theme.canvas2 },
  };
  const m = typeMeta[e.type] || typeMeta.message;
  return (
    <div style={{ display: 'flex', gap: 10, padding: '12px 14px', borderBottom: last ? 'none' : '1px solid ' + theme.rule, background: isInternal && role === 'admin' ? '#FAF6EC' : 'transparent', position: 'relative' }}>
      {isInternal && <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 3, background: '#D9B262' }}/>}
      <div style={{ width: 28, height: 28, borderRadius: 8, flexShrink: 0, background: m.bg, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Icon name={m.icon} size={13} color={m.color}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: theme.ink, lineHeight: 1.3 }}>{e.title}</div>
          {e.amount && <span className="serif tnum" style={{ fontSize: 12, fontWeight: 600, color: theme.ink, whiteSpace: 'nowrap' }}>${e.amount.toLocaleString()}</span>}
        </div>
        {e.body && <div style={{ fontSize: 12, color: theme.inkDim, marginTop: 3, lineHeight: 1.4 }}>{e.body}</div>}
        <div style={{ fontSize: 11, color: theme.inkMute, marginTop: 4 }}>{e.when} · {e.time}</div>
      </div>
    </div>
  );
}

function MobilePaymentsTab({ client, theme, role, onSheet }) {
  const payments = paymentsForClient(client.id);
  const next = payments.find(p => p.status === 'Scheduled');
  const posted = payments.filter(p => p.status === 'Posted');
  const totalPosted = posted.reduce((s, p) => s + p.amount, 0);
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 16 }}>
        {[
          { label: 'Next payment', v: next ? '$' + next.amount.toLocaleString() : '—', sub: next?.date || '' },
          { label: 'Total posted', v: '$' + totalPosted.toLocaleString(), sub: posted.length + ' payments' },
        ].map(s => (
          <div key={s.label} style={{ background: theme.raised, border: '1px solid ' + theme.rule, borderRadius: 12, padding: 12 }}>
            <div style={{ fontSize: 10, color: theme.inkMute, fontWeight: 600, letterSpacing: 1.2, textTransform: 'uppercase' }}>{s.label}</div>
            <div className="serif tnum" style={{ fontSize: 20, fontWeight: 500, color: theme.ink, marginTop: 4, lineHeight: 1 }}>{s.v}</div>
            {s.sub && <div style={{ fontSize: 11, color: theme.inkMute, marginTop: 4 }}>{s.sub}</div>}
          </div>
        ))}
      </div>
      {role === 'admin' && (
        <button onClick={() => onSheet('payment')} style={{ width: '100%', padding: '10px', borderRadius: 10, background: theme.surface, color: theme.onSurface, fontSize: 13, fontWeight: 600, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, marginBottom: 14 }}>
          <Icon name="pay" size={13} color={theme.onSurface}/>Add payment
        </button>
      )}
      {payments.length === 0 ? (
        <div style={{ padding: '40px 20px', textAlign: 'center', color: theme.inkMute }}>
          <Icon name="pay" size={28} color={theme.inkMute}/>
          <div style={{ marginTop: 10, fontSize: 14, fontWeight: 500, color: theme.ink }}>No payments recorded</div>
        </div>
      ) : (
        <div style={{ background: theme.raised, border: '1px solid ' + theme.rule, borderRadius: 14, overflow: 'hidden' }}>
          {payments.map((p, i, arr) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 14px', borderBottom: i < arr.length - 1 ? '1px solid ' + theme.rule : 'none' }}>
              <div>
                <div style={{ fontSize: 13, fontWeight: 500, color: theme.ink }}>{p.date}</div>
                <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: 0.5, padding: '2px 7px', borderRadius: 99, background: p.status === 'Posted' ? '#DBE7DC' : p.status === 'Failed' ? '#F5DFC9' : '#D9E5F4', color: p.status === 'Posted' ? '#173C2C' : p.status === 'Failed' ? '#7A2E11' : '#1F4A8B', marginTop: 4, display: 'inline-block' }}>{p.status}</span>
              </div>
              <span className="serif tnum" style={{ fontSize: 16, fontWeight: 500, color: theme.ink }}>${p.amount.toLocaleString()}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function MobileVaultTab({ client, theme, role, onSheet }) {
  const docs = docsForClient(client.id, role);
  const downloadDoc = async (doc) => {
    try {
      const blob = await api.admin.downloadDocument(doc.id);
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a'); a.href = url; a.download = doc.name; a.click();
      URL.revokeObjectURL(url);
    } catch (e) { alert('Download failed: ' + (e.message || 'Unknown error')); }
  };
  return (
    <div>
      {role === 'admin' && (
        <button onClick={() => onSheet('doc')} style={{ width: '100%', padding: '10px', borderRadius: 10, background: theme.surface, color: theme.onSurface, fontSize: 13, fontWeight: 600, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, marginBottom: 14 }}>
          <Icon name="upload" size={13} color={theme.onSurface}/>Upload document
        </button>
      )}
      {docs.length === 0 ? (
        <div style={{ padding: '40px 20px', textAlign: 'center', color: theme.inkMute }}>
          <Icon name="doc" size={28} color={theme.inkMute}/>
          <div style={{ marginTop: 10, fontSize: 14, fontWeight: 500, color: theme.ink }}>No documents</div>
        </div>
      ) : (
        <div style={{ background: theme.raised, border: '1px solid ' + theme.rule, borderRadius: 14, overflow: 'hidden' }}>
          {docs.map((d, i, arr) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', borderBottom: i < arr.length - 1 ? '1px solid ' + theme.rule : 'none' }}>
              <div style={{ width: 36, height: 44, borderRadius: 6, background: theme.canvas2, border: '1px solid ' + theme.rule, display: 'flex', alignItems: 'flex-end', justifyContent: 'center', paddingBottom: 5, flexShrink: 0 }}>
                <span className="mono" style={{ fontSize: 8, fontWeight: 700, color: theme.accent.solid, letterSpacing: 0.5 }}>PDF</span>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 500, color: theme.ink, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{d.name}</div>
                <div style={{ fontSize: 11, color: theme.inkMute, marginTop: 2 }}>{d.folder} · {d.date} · {d.size}</div>
              </div>
              <button onClick={() => downloadDoc(d)} style={{ padding: 8 }}><Icon name="download" size={16} color={theme.inkDim}/></button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function MobilePlanTab({ client, theme, role, onSheet }) {
  const rep = repById(client.rep);
  const referrer = refById(client.referrer);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{ background: theme.raised, border: '1px solid ' + theme.rule, borderRadius: 14, padding: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: theme.inkMute, letterSpacing: 1.4, textTransform: 'uppercase' }}>Assigned specialist</div>
          {role === 'admin' && <button onClick={() => onSheet('rep')} style={{ fontSize: 12, fontWeight: 600, color: theme.surface }}>Reassign</button>}
        </div>
        {rep ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 46, height: 46, borderRadius: 99, background: 'linear-gradient(135deg, ' + theme.accent.solid + ', ' + theme.accent.ink + ')', color: '#fff', fontSize: 14, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'Newsreader, serif', flexShrink: 0 }}>{rep.initials}</div>
            <div>
              <div className="serif" style={{ fontSize: 18, fontWeight: 500, color: theme.ink }}>{rep.name}</div>
              <div style={{ fontSize: 12, color: theme.inkMute, marginTop: 2 }}>{rep.role}</div>
              <div className="tnum" style={{ fontSize: 11, color: theme.inkMute, marginTop: 2 }}>Caseload {rep.caseload}/{rep.capacity}</div>
            </div>
          </div>
        ) : <div style={{ fontSize: 13, color: theme.inkMute }}>No specialist assigned.</div>}
      </div>
      <div style={{ background: theme.raised, border: '1px solid ' + theme.rule, borderRadius: 14, padding: 16 }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: theme.inkMute, letterSpacing: 1.4, textTransform: 'uppercase', marginBottom: 10 }}>Plan terms</div>
        {[
          { k: 'Program',          v: client.plan || '—' },
          { k: 'Duration',         v: (client.planMonths || 0) + ' months' },
          { k: 'Months completed', v: String(client.planMonthsDone || 0) },
          { k: 'Member since',     v: client.member || '—' },
        ].map((r, i, arr) => (
          <div key={r.k} style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 0', borderBottom: i < arr.length - 1 ? '1px solid ' + theme.rule : 'none' }}>
            <span style={{ fontSize: 13, color: theme.inkMute }}>{r.k}</span>
            <span style={{ fontSize: 13, fontWeight: 500, color: theme.ink }}>{r.v}</span>
          </div>
        ))}
      </div>
      {referrer && (
        <div style={{ background: theme.raised, border: '1px solid ' + theme.rule, borderRadius: 14, padding: 16 }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: theme.inkMute, letterSpacing: 1.4, textTransform: 'uppercase', marginBottom: 10 }}>Referral source</div>
          <div style={{ fontSize: 14, fontWeight: 600, color: theme.ink }}>{referrer.name}</div>
          <div style={{ fontSize: 12, color: theme.inkMute, marginTop: 4 }}>{referrer.contact} · {referrer.email}</div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { AdminMobileApp });
if (window.innerWidth < 768) {
  ReactDOM.createRoot(document.getElementById('root')).render(<AdminMobileApp/>);
}
