// admin-tabs.jsx — Client file: header + tab nav + tab content
// Tabs: Overview, Lenders, Activity, Payments, Vault, Specialist

function AdminClientFile({ theme, role, client, onAddEvent, onLogOffer, onUploadDoc, onUpdatePayment, onAssignRep }) {
  const [tab, setTab] = React.useState('overview');

  if (!client) {
    return (
      <div style={{
        flex: 1, background: theme.canvas,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: theme.inkMute, fontSize: 13,
      }}>Select a client from the left.</div>
    );
  }

  const tabs = [
    { id: 'overview',   label: 'Overview' },
    { id: 'lenders',    label: 'Lenders' },
    { id: 'activity',   label: 'Activity' },
    { id: 'payments',   label: 'Payments' },
    { id: 'vault',      label: 'Vault' },
    { id: 'specialist', label: 'Plan' },
  ];

  return (
    <div style={{
      flex: 1, background: theme.canvas,
      display: 'flex', flexDirection: 'column',
      overflow: 'hidden', minWidth: 0,
    }}>
      {/* Client header */}
      <ClientHeader theme={theme} role={role} client={client} onAddEvent={onAddEvent} onLogOffer={onLogOffer}/>

      {/* Tab nav */}
      <div style={{
        flexShrink: 0, padding: '0 24px',
        borderBottom: `1px solid ${theme.rule}`,
        background: theme.raised,
        display: 'flex', gap: 4,
      }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            padding: '12px 14px',
            fontSize: 13, fontWeight: 600, letterSpacing: 0.1,
            color: tab === t.id ? theme.surface : theme.inkDim,
            borderBottom: `2px solid ${tab === t.id ? theme.surface : 'transparent'}`,
            marginBottom: -1,
          }}>{t.label}</button>
        ))}
      </div>

      {/* Tab body */}
      <div className="scroll" style={{ flex: 1, overflowY: 'auto', padding: '20px 24px 40px' }}>
        {tab === 'overview'   && <OverviewTab   client={client} theme={theme} role={role}/>}
        {tab === 'lenders'    && <LendersTab    client={client} theme={theme} role={role} onLogOffer={onLogOffer}/>}
        {tab === 'activity'   && <ActivityTab   client={client} theme={theme} role={role} onAddEvent={onAddEvent}/>}
        {tab === 'payments'   && <PaymentsTab   client={client} theme={theme} role={role} onUpdatePayment={onUpdatePayment}/>}
        {tab === 'vault'      && <VaultTab      client={client} theme={theme} role={role} onUploadDoc={onUploadDoc}/>}
        {tab === 'specialist' && <SpecialistTab client={client} theme={theme} role={role} onAssignRep={onAssignRep}/>}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Client header
// ─────────────────────────────────────────────────────────────
function ClientHeader({ theme, role, client, onAddEvent, onLogOffer }) {
  const rep = repById(client.rep);
  const statusColor = ({
    Active: theme.accent.solid,
    Intake: '#9B6B2F',
    Settled: '#2F6A4F',
  })[client.status] || theme.inkMute;

  return (
    <div style={{
      flexShrink: 0, padding: '20px 24px 16px',
      background: theme.raised,
      borderBottom: `1px solid ${theme.rule}`,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 24 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ fontSize: 10.5, color: theme.inkMute, fontWeight: 600, letterSpacing: 1.6, textTransform: 'uppercase' }}>
              Casefile · {client.code}
            </div>
            <span style={{
              fontSize: 10, fontWeight: 700, letterSpacing: 0.6,
              padding: '2px 7px', borderRadius: 99,
              background: theme.canvas2, color: statusColor,
              display: 'flex', alignItems: 'center', gap: 4,
            }}>
              <span style={{ width: 5, height: 5, borderRadius: 99, background: statusColor }}/>
              {client.status.toUpperCase()}
            </span>
            {client.flagsAtRisk && (
              <span style={{
                fontSize: 10, fontWeight: 700, letterSpacing: 0.6,
                padding: '2px 7px', borderRadius: 99,
                background: '#FFE4D1', color: '#7A2E11',
              }}>⚐ AT RISK</span>
            )}
          </div>
          <h1 className="serif" style={{
            fontSize: 28, fontWeight: 500, color: theme.ink,
            margin: '6px 0 0', letterSpacing: -0.4, lineHeight: 1.05,
          }}>{client.name}</h1>
          <div style={{ fontSize: 13, color: theme.inkDim, marginTop: 5 }}>
            {client.biz} · {client.bizType}
          </div>
          <div style={{
            fontSize: 11.5, color: theme.inkMute, marginTop: 7,
            display: 'flex', gap: 14, flexWrap: 'wrap',
          }}>
            <span>📍 {client.address}</span>
            <span>· {client.phone}</span>
            <span>· {client.email}</span>
            <span>· Member since {client.member}</span>
          </div>
        </div>

        {/* Metric block + actions */}
        <div style={{ textAlign: 'right', flexShrink: 0 }}>
          <div style={{ fontSize: 10, color: theme.inkMute, fontWeight: 600, letterSpacing: 1.6, textTransform: 'uppercase' }}>
            Enrolled debt
          </div>
          <div className="serif tnum" style={{
            fontSize: 32, fontWeight: 500, color: theme.ink, marginTop: 4,
            lineHeight: 1, letterSpacing: -0.5,
          }}>
            <span style={{ opacity: 0.55, fontWeight: 400, marginRight: 1 }}>$</span>
            {client.enrolled.toLocaleString()}
          </div>
          <div style={{
            display: 'flex', gap: 14, marginTop: 8, justifyContent: 'flex-end',
            fontSize: 11.5, color: theme.inkDim,
          }}>
            <span>Settled <span className="tnum" style={{ fontWeight: 600, color: theme.ink }}>${(client.settled / 1000).toFixed(1)}k</span></span>
            <span>Saved <span className="tnum" style={{ fontWeight: 600, color: theme.accent.solid }}>${(client.saved / 1000).toFixed(1)}k</span></span>
            <span>Progress <span className="tnum" style={{ fontWeight: 600, color: theme.ink }}>{client.planProgress}%</span></span>
          </div>

          {role === 'admin' && (
            <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end', marginTop: 14 }}>
              <button onClick={onAddEvent} 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 event
              </button>
              <button onClick={onLogOffer} style={{
                padding: '8px 12px', borderRadius: 8,
                background: theme.raised, color: theme.ink,
                border: `1px solid ${theme.rule}`,
                fontSize: 12, fontWeight: 600,
                display: 'flex', alignItems: 'center', gap: 6,
              }}>
                <Icon name="spark" size={12} color={theme.ink}/>
                Log offer
              </button>
              <button style={{
                width: 30, height: 30, borderRadius: 8,
                background: theme.raised, border: `1px solid ${theme.rule}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}><Icon name="moreH" size={14} color={theme.ink}/></button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// OVERVIEW TAB
// ─────────────────────────────────────────────────────────────
function OverviewTab({ client, theme, role }) {
  const lenders = lendersForClient(client.id);
  const activity = activityForClient(client.id, role);

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18 }}>
      {/* LEFT — plan visualization + lenders summary */}
      <div>
        {/* Plan progress card */}
        <Card theme={theme} pad={18}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <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 <strong className="tnum">{client.planMonthsDone}</strong> of <strong className="tnum">{client.planMonths}</strong>
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 16, marginTop: 12 }}>
            <div className="serif tnum" style={{ fontSize: 42, fontWeight: 500, color: theme.ink, lineHeight: 1 }}>
              {client.planProgress}%
            </div>
            <div style={{ flex: 1, paddingBottom: 4 }}>
              <ProgressBar value={client.planProgress} theme={theme} color={theme.accent.solid} height={8}/>
            </div>
          </div>
          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0,
            marginTop: 16, paddingTop: 14, borderTop: `1px solid ${theme.rule}`,
          }}>
            <OverviewStat theme={theme} label="Enrolled"      v={client.enrolled} accent={theme.ink}/>
            <OverviewStat theme={theme} label="Settled"       v={client.settled}  accent={theme.ink} border/>
            <OverviewStat theme={theme} label="Client saved"  v={client.saved}    accent={theme.accent.solid} border/>
          </div>
        </Card>

        {/* Lenders summary */}
        <div style={{ marginTop: 18 }}>
          <SectionHeader theme={theme} action={`${lenders.length} lenders`}>Lender ledger</SectionHeader>
          <Card theme={theme} pad={0}>
            {lenders.slice(0, 5).map((l, i, arr) => (
              <div key={l.id} style={{
                display: 'grid', gridTemplateColumns: '40px 1fr 90px 110px',
                gap: 12, alignItems: 'center',
                padding: '11px 14px',
                borderBottom: i < arr.length - 1 ? `1px solid ${theme.rule}` : 'none',
              }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 8,
                  background: theme.canvas2, border: `1px solid ${theme.rule}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: 'Newsreader, serif', fontSize: 10, fontWeight: 700, color: theme.ink, letterSpacing: 0.4,
                }}>{l.short}</div>
                <div style={{ 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.toLocaleString()}
                    {l.settlement && ` · Settled $${l.settlement.toLocaleString()}`}
                  </div>
                </div>
                <div className="tnum" style={{ fontSize: 12, fontWeight: 600, color: l.settlement ? theme.accent.solid : theme.inkMute, textAlign: 'right' }}>
                  {l.settlement ? `−${Math.round(100 - (l.settlement / l.balance) * 100)}%` : '—'}
                </div>
                <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                  <StatusPill status={l.status} theme={theme}/>
                </div>
              </div>
            ))}
          </Card>
        </div>
      </div>

      {/* RIGHT — recent activity + key facts */}
      <div>
        <Card theme={theme} pad={16}>
          <div style={{ fontSize: 11, fontWeight: 600, color: theme.inkMute, letterSpacing: 1.4, textTransform: 'uppercase' }}>Key facts</div>
          <KVRow theme={theme} k="Plan"          v={client.plan}/>
          <KVRow theme={theme} k="Funding bank"  v={`${client.bankBrand} ${client.bankLast4 ? '··' + client.bankLast4 : ''}`}/>
          <KVRow theme={theme} k="Next payment"  v={client.nextPayment > 0 ? `$${client.nextPayment.toLocaleString()} on ${client.nextDate}` : '—'}/>
          <KVRow theme={theme} k="Documents"     v={`${client.docsCount} files`}/>
          <KVRow theme={theme} k="Last update"   v={client.lastUpdate} last/>
        </Card>

        <div style={{ marginTop: 18 }}>
          <SectionHeader theme={theme}>Recent activity</SectionHeader>
          <Card theme={theme} pad={0}>
            {activity.slice(0, 4).map((e, i, arr) => (
              <AdminActivityRow key={e.id} e={e} theme={theme} last={i === arr.length - 1} role={role} compact/>
            ))}
            {activity.length === 0 && <div style={{ padding: 24, textAlign: 'center', color: theme.inkMute, fontSize: 12 }}>No events.</div>}
          </Card>
        </div>
      </div>
    </div>
  );
}

function OverviewStat({ theme, label, v, accent, border }) {
  return (
    <div style={{ padding: '0 14px', borderLeft: border ? `1px solid ${theme.rule}` : 'none' }}>
      <div style={{ fontSize: 10, color: theme.inkMute, fontWeight: 600, letterSpacing: 1.2, textTransform: 'uppercase' }}>{label}</div>
      <div className="serif tnum" style={{ fontSize: 19, fontWeight: 500, color: accent, marginTop: 4, lineHeight: 1, letterSpacing: -0.3 }}>
        <span style={{ opacity: 0.55, marginRight: 1, fontWeight: 400 }}>$</span>{v.toLocaleString()}
      </div>
    </div>
  );
}

function KVRow({ k, v, theme, last }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      padding: '11px 0',
      borderBottom: last ? 'none' : `1px solid ${theme.rule}`,
    }}>
      <span style={{ fontSize: 12, color: theme.inkMute }}>{k}</span>
      <span className="tnum" style={{ fontSize: 13, fontWeight: 500, color: theme.ink, textAlign: 'right' }}>{v}</span>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// LENDERS TAB — table of all lenders for client
// ─────────────────────────────────────────────────────────────
function LendersTab({ client, theme, role, onLogOffer }) {
  const lenders = lendersForClient(client.id);
  if (lenders.length === 0) {
    return <EmptyTab theme={theme} icon="bank" title="No lenders on file" body="This client's intake is in progress."/>;
  }
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
        <SectionHeader theme={theme}>All lenders ({lenders.length})</SectionHeader>
        {role === 'admin' && (
          <button onClick={onLogOffer} style={{
            padding: '7px 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}/>
            Log offer / update
          </button>
        )}
      </div>
      <Card theme={theme} pad={0}>
        {/* table header */}
        <div style={{
          display: 'grid', gridTemplateColumns: '44px 1.4fr 1fr 1fr 1fr 130px 40px',
          gap: 10, alignItems: 'center',
          padding: '11px 14px',
          borderBottom: `1px solid ${theme.rule}`,
          fontSize: 10, fontWeight: 600, letterSpacing: 1.4, textTransform: 'uppercase', color: theme.inkMute,
        }}>
          <span/>
          <span>Lender · Contact</span>
          <span style={{ textAlign: 'right' }}>Original</span>
          <span style={{ textAlign: 'right' }}>Settlement</span>
          <span style={{ textAlign: 'right' }}>Discount</span>
          <span>Status</span>
          <span/>
        </div>
        {lenders.map((l, i, arr) => (
          <div key={l.id} style={{
            display: 'grid', gridTemplateColumns: '44px 1.4fr 1fr 1fr 1fr 130px 40px',
            gap: 10, alignItems: 'center',
            padding: '12px 14px',
            borderBottom: i < arr.length - 1 ? `1px solid ${theme.rule}` : 'none',
          }}>
            <div style={{
              width: 34, height: 34, borderRadius: 8,
              background: theme.canvas2, border: `1px solid ${theme.rule}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'Newsreader, serif', fontSize: 11, fontWeight: 700, color: theme.ink, letterSpacing: 0.4,
            }}>{l.short}</div>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: theme.ink }}>{l.name}</div>
              {l.contactPerson && <div style={{ fontSize: 11, color: theme.inkMute, marginTop: 2 }}>{l.contactPerson}</div>}
            </div>
            <div className="tnum serif" style={{ fontSize: 14, color: theme.ink, textAlign: 'right' }}>${l.balance.toLocaleString()}</div>
            <div className="tnum serif" style={{ fontSize: 14, color: l.settlement ? theme.ink : theme.inkMute, textAlign: 'right' }}>
              {l.settlement ? `$${l.settlement.toLocaleString()}` : '—'}
            </div>
            <div className="tnum" style={{ fontSize: 13, fontWeight: 600, color: l.settlement ? theme.accent.solid : theme.inkMute, textAlign: 'right' }}>
              {l.settlement ? `−${Math.round(100 - (l.settlement / l.balance) * 100)}%` : '—'}
            </div>
            <div><StatusPill status={l.status} theme={theme}/></div>
            <button style={{ color: theme.inkMute, display: 'flex', justifyContent: 'flex-end' }}>
              <Icon name="moreH" size={14} color={theme.inkMute}/>
            </button>
          </div>
        ))}
      </Card>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// ACTIVITY TAB — with visibility toggle
// ─────────────────────────────────────────────────────────────
function ActivityTab({ client, theme, role, onAddEvent }) {
  const [showInternal, setShowInternal] = React.useState(role === 'admin');
  const raw = activityForClient(client.id, 'admin');
  const events = (role === 'referral' || !showInternal)
    ? raw.filter(e => e.visibility === 'public')
    : raw;

  const internalCount = raw.filter(e => e.visibility === 'internal').length;

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12, gap: 10, flexWrap: 'wrap' }}>
        <SectionHeader theme={theme}>Casefile · {events.length} events</SectionHeader>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          {role === 'admin' && (
            <label style={{ display: 'flex', alignItems: 'center', gap: 7, cursor: 'pointer' }}>
              <input
                type="checkbox" checked={showInternal} onChange={e => setShowInternal(e.target.checked)}
                style={{ width: 14, height: 14, accentColor: theme.surface }}
              />
              <span style={{ fontSize: 12, color: theme.ink, fontWeight: 500 }}>
                Show internal notes
                <span className="tnum" style={{ color: theme.inkMute, marginLeft: 4 }}>({internalCount})</span>
              </span>
            </label>
          )}
          {role === 'admin' && (
            <button onClick={onAddEvent} style={{
              padding: '7px 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 event
            </button>
          )}
        </div>
      </div>

      <Card theme={theme} pad={0}>
        {events.map((e, i, arr) => (
          <AdminActivityRow key={e.id} e={e} theme={theme} last={i === arr.length - 1} role={role}/>
        ))}
        {events.length === 0 && <div style={{ padding: 40, textAlign: 'center', color: theme.inkMute, fontSize: 13 }}>No events to display.</div>}
      </Card>
    </div>
  );
}

function AdminActivityRow({ e, theme, last, role, compact }) {
  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;
  const author = e.author === 'system' ? 'System' : (repById(e.author)?.name || 'Unknown');

  return (
    <div style={{
      display: 'flex', gap: 12, padding: '13px 16px',
      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: 30, height: 30, borderRadius: 8, flexShrink: 0,
        background: m.bg, color: m.color,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon name={m.icon} size={14} color={m.color}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: theme.ink, lineHeight: 1.3 }}>{e.title}</div>
            {isInternal && (
              <span style={{
                fontSize: 9, fontWeight: 700, letterSpacing: 0.7,
                padding: '2px 6px', borderRadius: 99,
                background: '#F0DDB2', color: '#7A5A1B',
                display: 'inline-flex', alignItems: 'center', gap: 4,
              }}>
                <svg width="9" height="9" viewBox="0 0 24 24" fill="none">
                  <rect x="4" y="11" width="16" height="10" rx="2" stroke="#7A5A1B" strokeWidth="2"/>
                  <path d="M8 11V7a4 4 0 018 0v4" stroke="#7A5A1B" strokeWidth="2"/>
                </svg>
                INTERNAL
              </span>
            )}
          </div>
          {e.amount && (
            <span className="serif tnum" style={{
              fontSize: 13, fontWeight: 600, color: e.type === 'settled' ? '#2F6A4F' : theme.ink, whiteSpace: 'nowrap',
            }}>
              {e.type === 'settled' || e.type === 'offer' ? '↑ ' : ''}${e.amount.toLocaleString()}
            </span>
          )}
        </div>
        {!compact && e.body && (
          <div style={{ fontSize: 12.5, color: theme.inkDim, marginTop: 4, lineHeight: 1.45 }}>{e.body}</div>
        )}
        <div style={{ fontSize: 11, color: theme.inkMute, marginTop: 5, display: 'flex', gap: 8, alignItems: 'center' }}>
          <span>{e.when} · {e.time}</span>
          <span>·</span>
          <span>{author}</span>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// PAYMENTS TAB
// ─────────────────────────────────────────────────────────────
function PaymentsTab({ client, theme, role, onUpdatePayment }) {
  const payments = paymentsForClient(client.id);
  if (payments.length === 0) {
    return <EmptyTab theme={theme} icon="pay" title="No payments recorded" body="Set a reserve schedule on the Plan tab."/>;
  }

  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: 'repeat(3, 1fr)', gap: 14, marginBottom: 18 }}>
        <PaymentStat theme={theme} label="Next contribution" v={next ? `$${next.amount.toLocaleString()}` : '—'} sub={next ? next.date : ''}/>
        <PaymentStat theme={theme} label="Posted to reserve" v={`$${totalPosted.toLocaleString()}`} sub={`${posted.length} payments`}/>
        <PaymentStat theme={theme} label="Funding source"   v={`${client.bankBrand}`} sub={`••${client.bankLast4}`}/>
      </div>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
        <SectionHeader theme={theme}>Schedule & history</SectionHeader>
        {role === 'admin' && (
          <button onClick={onUpdatePayment} style={{
            padding: '7px 12px', borderRadius: 8,
            background: theme.surface, color: theme.onSurface,
            fontSize: 12, fontWeight: 600,
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <Icon name="pay" size={12} color={theme.onSurface}/>
            Edit schedule
          </button>
        )}
      </div>

      <Card theme={theme} pad={0}>
        <div style={{
          display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr 130px 40px',
          gap: 10, padding: '11px 14px', alignItems: 'center',
          borderBottom: `1px solid ${theme.rule}`,
          fontSize: 10, fontWeight: 600, letterSpacing: 1.4, textTransform: 'uppercase', color: theme.inkMute,
        }}>
          <span>Date</span>
          <span style={{ textAlign: 'right' }}>Amount</span>
          <span>Confirmation</span>
          <span>Settled</span>
          <span>Status</span>
          <span/>
        </div>
        {payments.map((p, i, arr) => (
          <div key={i} style={{
            display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr 130px 40px',
            gap: 10, padding: '12px 14px', alignItems: 'center',
            borderBottom: i < arr.length - 1 ? `1px solid ${theme.rule}` : 'none',
          }}>
            <span style={{ fontSize: 13, fontWeight: 500, color: theme.ink }}>{p.date}</span>
            <span className="serif tnum" style={{ fontSize: 14, color: theme.ink, textAlign: 'right' }}>${p.amount.toLocaleString()}</span>
            <span className="mono" style={{ fontSize: 11, color: theme.inkMute }}>{p.conf || '—'}</span>
            <span className="tnum" style={{ fontSize: 12, color: theme.inkDim }}>{p.settled || '—'}</span>
            <span>
              <span style={{
                fontSize: 10, fontWeight: 700, letterSpacing: 0.6,
                padding: '3px 8px', borderRadius: 99,
                background: p.status === 'Posted' ? '#DBE7DC' : (p.status === 'Failed' ? '#F5DFC9' : '#D9E5F4'),
                color:      p.status === 'Posted' ? '#173C2C' : (p.status === 'Failed' ? '#7A2E11' : '#1F4A8B'),
              }}>{p.status.toUpperCase()}</span>
            </span>
            <button style={{ color: theme.inkMute, display: 'flex', justifyContent: 'flex-end' }}>
              <Icon name="moreH" size={14} color={theme.inkMute}/>
            </button>
          </div>
        ))}
      </Card>
    </div>
  );
}

function PaymentStat({ theme, label, v, sub }) {
  return (
    <Card theme={theme} pad={14}>
      <div style={{ fontSize: 10, color: theme.inkMute, fontWeight: 600, letterSpacing: 1.4, textTransform: 'uppercase' }}>{label}</div>
      <div className="serif tnum" style={{ fontSize: 22, fontWeight: 500, color: theme.ink, marginTop: 5, lineHeight: 1 }}>{v}</div>
      {sub && <div style={{ fontSize: 11.5, color: theme.inkMute, marginTop: 6 }}>{sub}</div>}
    </Card>
  );
}

// ─────────────────────────────────────────────────────────────
// VAULT TAB
// ─────────────────────────────────────────────────────────────
function VaultTab({ client, theme, role, onUploadDoc }) {
  const [folder, setFolder] = React.useState('All');
  const docs = docsForClient(client.id, role);
  const folders = ['All', ...Array.from(new Set(docs.map(d => d.folder)))];
  const filtered = folder === 'All' ? docs : docs.filter(d => d.folder === folder);

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12, gap: 12, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap' }}>
          {folders.map(f => (
            <button key={f} onClick={() => setFolder(f)} style={{
              padding: '6px 11px', borderRadius: 99,
              fontSize: 11.5, fontWeight: 600,
              background: folder === f ? theme.surface : 'transparent',
              color:      folder === f ? theme.onSurface : theme.inkDim,
              border: `1px solid ${folder === f ? theme.surface : theme.rule}`,
            }}>{f}</button>
          ))}
        </div>
        {role === 'admin' && (
          <button onClick={onUploadDoc} style={{
            padding: '7px 12px', borderRadius: 8,
            background: theme.surface, color: theme.onSurface,
            fontSize: 12, fontWeight: 600,
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <Icon name="upload" size={12} color={theme.onSurface}/>
            Upload document
          </button>
        )}
      </div>
      <Card theme={theme} pad={0}>
        {filtered.map((d, i, arr) => (
          <div key={i} style={{
            display: 'grid', gridTemplateColumns: '46px 1fr 1fr 1fr 110px 40px',
            gap: 12, padding: '11px 14px', alignItems: 'center',
            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,
              position: 'relative',
            }}>
              <div style={{ position: 'absolute', top: 4, right: 4, width: 8, height: 8, borderTop: `1px solid ${theme.rule}`, borderRight: `1px solid ${theme.rule}` }}/>
              <span className="mono" style={{ fontSize: 8, fontWeight: 700, color: theme.accent.solid, letterSpacing: 0.5 }}>PDF</span>
            </div>
            <div style={{ 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} · uploaded by {d.uploadedBy === 'system' ? 'System' : (repById(d.uploadedBy)?.name || 'Unknown')}
              </div>
            </div>
            <div style={{ fontSize: 12, color: theme.inkDim }}>{d.date}</div>
            <div className="tnum" style={{ fontSize: 12, color: theme.inkMute }}>{d.size}</div>
            <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap' }}>
              {d.tag && (
                <span style={{
                  fontSize: 9.5, fontWeight: 700, letterSpacing: 0.5,
                  padding: '2px 7px', borderRadius: 99,
                  background: theme.accent.soft, color: theme.accent.ink,
                }}>{d.tag.toUpperCase()}</span>
              )}
              {d.visibility === 'internal' && (
                <span style={{
                  fontSize: 9.5, fontWeight: 700, letterSpacing: 0.5,
                  padding: '2px 7px', borderRadius: 99,
                  background: '#F0DDB2', color: '#7A5A1B',
                }}>INTERNAL</span>
              )}
            </div>
            <button style={{ color: theme.inkDim, display: 'flex', justifyContent: 'flex-end' }}>
              <Icon name="download" size={14} color={theme.inkDim}/>
            </button>
          </div>
        ))}
        {filtered.length === 0 && (
          <div style={{ padding: 40, textAlign: 'center', color: theme.inkMute, fontSize: 13 }}>No documents in this folder.</div>
        )}
      </Card>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// SPECIALIST / PLAN TAB
// ─────────────────────────────────────────────────────────────
function SpecialistTab({ client, theme, role, onAssignRep }) {
  const rep = repById(client.rep);
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
      <Card theme={theme} pad={18}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ fontSize: 11, color: theme.inkMute, fontWeight: 600, letterSpacing: 1.4, textTransform: 'uppercase' }}>Assigned specialist</div>
          {role === 'admin' && <button onClick={onAssignRep} style={{ fontSize: 12, fontWeight: 600, color: theme.surface }}>Reassign</button>}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 14 }}>
          <div style={{
            width: 54, height: 54, borderRadius: 99,
            background: `linear-gradient(135deg, ${theme.accent.solid}, ${theme.accent.ink})`,
            color: '#fff', fontSize: 17, fontWeight: 600,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'Newsreader, serif',
          }}>{rep?.initials}</div>
          <div style={{ flex: 1 }}>
            <div className="serif" style={{ fontSize: 20, fontWeight: 500, color: theme.ink, lineHeight: 1 }}>{rep?.name}</div>
            <div style={{ fontSize: 12, color: theme.inkMute, marginTop: 4 }}>{rep?.role}</div>
            <div className="tnum" style={{ fontSize: 11, color: theme.inkMute, marginTop: 3 }}>
              Caseload {rep?.caseload}/{rep?.capacity} · Status: {rep?.status}
            </div>
          </div>
        </div>
      </Card>

      <Card theme={theme} pad={18}>
        <div style={{ fontSize: 11, color: theme.inkMute, fontWeight: 600, letterSpacing: 1.4, textTransform: 'uppercase' }}>Plan terms</div>
        <KVRow theme={theme} k="Program"           v={client.plan}/>
        <KVRow theme={theme} k="Plan duration"     v={`${client.planMonths} months`}/>
        <KVRow theme={theme} k="Months completed"  v={`${client.planMonthsDone}`}/>
        <KVRow theme={theme} k="Estimated finish"  v="Dec 2027"/>
        <KVRow theme={theme} k="Member since"      v={client.member} last/>
      </Card>
    </div>
  );
}

function EmptyTab({ theme, icon, title, body }) {
  return (
    <div style={{
      padding: '64px 40px', textAlign: 'center',
      color: theme.inkMute,
    }}>
      <div style={{
        width: 56, height: 56, borderRadius: 16, margin: '0 auto 14px',
        background: theme.canvas2, border: `1px solid ${theme.rule}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}><Icon name={icon} size={22} color={theme.inkDim}/></div>
      <div className="serif" style={{ fontSize: 18, color: theme.ink, fontWeight: 500 }}>{title}</div>
      <div style={{ fontSize: 13, color: theme.inkMute, marginTop: 6 }}>{body}</div>
    </div>
  );
}

Object.assign(window, {
  AdminClientFile, ClientHeader,
  OverviewTab, OverviewStat, KVRow,
  LendersTab, ActivityTab, AdminActivityRow,
  PaymentsTab, PaymentStat,
  VaultTab, SpecialistTab, EmptyTab,
});
