// admin-shell.jsx — Admin console layout: TopBar, ClientListRail, ContextRail
// Uses tokens from components.jsx (DL_PALETTES, DL_ACCENTS, Icon, etc.)

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

// ─────────────────────────────────────────────────────────────
// TOP BAR — sits across the full viewport, brand-blue surface
// ─────────────────────────────────────────────────────────────
function AdminTopBar({ theme, role, user, view, onChangeView, onCmdK, onSignOut }) {
  const [menuOpen, setMenuOpen] = React.useState(false);
  return (
    <div style={{
      height: 56, flexShrink: 0,
      background: theme.surface,
      borderBottom: `1px solid ${theme.surface3}`,
      display: 'flex', alignItems: 'center', gap: 16,
      padding: '0 18px',
      color: theme.onSurface,
      position: 'relative', zIndex: 50,
    }}>
      {/* Wordmark */}
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 10, flexShrink: 0 }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 2.5, marginBottom: 4 }}>
          <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: '#FFFFFF',                borderRadius: 1.5 }}/>
        </div>
        <span className="serif" style={{ fontSize: 22, fontWeight: 500, color: theme.onSurface, letterSpacing: -0.4, lineHeight: 1 }}>
          debtlift
        </span>
      </div>

      {/* View tabs (admins only) */}
      {role === 'admin' && view !== undefined && (
        <div style={{
          display: 'flex',
          background: 'rgba(255,255,255,0.08)',
          border: '1px solid rgba(255,255,255,0.15)',
          borderRadius: 8, padding: 2,
          marginLeft: 8,
        }}>
          {[
            { id: 'clients', label: 'Clients' },
            { id: 'team',    label: 'Team' },
          ].map(t => (
            <button key={t.id} onClick={() => onChangeView?.(t.id)} style={{
              padding: '5px 13px', borderRadius: 6,
              fontSize: 12, fontWeight: 600, letterSpacing: 0.2,
              background: view === t.id ? 'rgba(255,255,255,0.95)' : 'transparent',
              color:      view === t.id ? theme.surface : 'rgba(255,255,255,0.85)',
            }}>{t.label}</button>
          ))}
        </div>
      )}

      {/* Command search (center) */}
      <button onClick={onCmdK} style={{
        flex: 1, maxWidth: 480, margin: '0 auto',
        height: 34, borderRadius: 8,
        background: 'rgba(255,255,255,0.10)', border: '1px solid rgba(255,255,255,0.15)',
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '0 12px',
        color: 'rgba(255,255,255,0.78)',
        textAlign: 'left',
      }}>
        <Icon name="search" size={14} color="rgba(255,255,255,0.65)"/>
        <span style={{ fontSize: 13, flex: 1 }}>
          Search clients, lenders, payments…
        </span>
        <span style={{
          fontSize: 10, fontWeight: 600, letterSpacing: 0.5,
          padding: '3px 6px', borderRadius: 4,
          background: 'rgba(255,255,255,0.10)', border: '1px solid rgba(255,255,255,0.18)',
          fontFamily: 'JetBrains Mono, monospace',
        }}>⌘K</span>
      </button>

      {/* Right cluster */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
        {/* Role badge */}
        <div style={{
          padding: '4px 9px', borderRadius: 99,
          background: role === 'referral' ? '#F0DDB2' : 'rgba(255,255,255,0.15)',
          color: role === 'referral' ? '#7A5A1B' : theme.onSurface,
          fontSize: 10, fontWeight: 700, letterSpacing: 0.6,
        }}>
          {role === 'referral' ? 'REFERRAL · READ-ONLY' : 'ADMIN'}
        </div>

        {/* Alerts */}
        <button style={{
          width: 34, height: 34, borderRadius: 8,
          background: 'rgba(255,255,255,0.08)', border: '1px solid rgba(255,255,255,0.15)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          position: 'relative',
        }}>
          <Icon name="bell" size={15} color={theme.onSurface}/>
        </button>

        {/* User menu */}
        <div style={{ position: 'relative' }}>
          <button onClick={() => setMenuOpen(o => !o)} style={{
            display: 'flex', alignItems: 'center', gap: 9, paddingLeft: 6,
          }}>
            <div style={{
              width: 30, height: 30, borderRadius: 99,
              background: 'rgba(255,255,255,0.95)', color: theme.surface,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 11, fontWeight: 700, letterSpacing: 0.5,
            }}>{initialsOf(user?.name)}</div>
            <div style={{ lineHeight: 1.1, textAlign: 'left' }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, color: theme.onSurface }}>{user?.name || '—'}</div>
              <div style={{ fontSize: 10.5, color: 'rgba(255,255,255,0.65)', marginTop: 1 }}>{user?.email}</div>
            </div>
          </button>
          {menuOpen && (
            <>
              <div onClick={() => setMenuOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 1 }}/>
              <div style={{
                position: 'absolute', top: '110%', right: 0, zIndex: 2,
                minWidth: 220, background: theme.raised, color: theme.ink,
                borderRadius: 10, border: `1px solid ${theme.rule}`,
                boxShadow: '0 18px 40px rgba(0,0,0,0.18)',
                overflow: 'hidden', padding: '4px 0',
              }}>
                <button onClick={() => { setMenuOpen(false); onSignOut?.(); }} style={{
                  width: '100%', textAlign: 'left',
                  padding: '10px 14px', fontSize: 13, color: '#B5481D', fontWeight: 600,
                  display: 'flex', alignItems: 'center', gap: 8,
                }}>
                  <Icon name="lock" size={13} color="#B5481D"/>
                  Sign out
                </button>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// LEFT RAIL — client list (server-scoped to role)
// ─────────────────────────────────────────────────────────────
function AdminLeftRail({ theme, role, selectedId, onSelect, onNewClient, loading, error, rev }) {
  const [filter, setFilter] = React.useState('all');
  const [q, setQ] = React.useState('');

  // The API already filters referral users to their own clients, so we render
  // ADMIN_CLIENTS directly. `rev` triggers re-render when the roster updates.
  const pool = ADMIN_CLIENTS;

  const filters = role === 'admin'
    ? [
        { 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 },
        { id: 'at-risk',  label: 'At risk',  count: pool.filter(c => c.flagsAtRisk).length },
      ]
    : [
        { id: 'all',      label: 'All referred', count: pool.length },
        { id: 'Active',   label: 'Active',       count: pool.filter(c => c.status === 'Active').length },
        { id: 'Settled',  label: 'Settled',      count: pool.filter(c => c.status === 'Settled').length },
      ];

  let visible = pool;
  if (filter === 'at-risk') visible = visible.filter(c => c.flagsAtRisk);
  else if (filter !== 'all') visible = visible.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={{
      width: 336, flexShrink: 0,
      background: theme.raised,
      borderRight: `1px solid ${theme.rule}`,
      display: 'flex', flexDirection: 'column',
      overflow: 'hidden',
    }}>
      {/* Header */}
      <div style={{
        padding: '14px 16px 10px',
        borderBottom: `1px solid ${theme.rule}`,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8,
      }}>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontSize: 10, color: theme.inkMute, fontWeight: 600, letterSpacing: 1.6, textTransform: 'uppercase' }}>
            {role === 'admin' ? 'Roster' : 'Your portfolio'}
          </div>
          <div className="serif" style={{ fontSize: 19, fontWeight: 500, color: theme.ink, marginTop: 4, lineHeight: 1.1, letterSpacing: -0.2 }}>
            {role === 'admin' ? 'Clients' : 'Referrals'}
          </div>
        </div>
        {role === 'admin' && (
          <button onClick={onNewClient} style={{
            padding: '7px 11px', borderRadius: 8,
            background: theme.surface, color: theme.onSurface,
            fontSize: 11.5, fontWeight: 600, letterSpacing: 0.3,
            display: 'flex', alignItems: 'center', gap: 5,
          }}>
            <Icon name="plus" size={13} color={theme.onSurface} strokeWidth={2}/>
            New
          </button>
        )}
      </div>

      {/* Search */}
      <div style={{ padding: '10px 16px 6px' }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '7px 10px', borderRadius: 8,
          background: theme.canvas, border: `1px solid ${theme.rule}`,
        }}>
          <Icon name="search" size={13} color={theme.inkMute}/>
          <input
            value={q} onChange={e => setQ(e.target.value)}
            placeholder="Search name, business, ID…"
            style={{
              flex: 1, border: 0, outline: 0, background: 'transparent',
              fontSize: 12.5, color: theme.ink, fontFamily: 'inherit',
            }}
          />
        </div>
      </div>

      {/* Filter chips */}
      <div className="scroll" style={{
        display: 'flex', gap: 5, overflowX: 'auto',
        padding: '8px 16px 12px',
      }}>
        {filters.map(f => (
          <button key={f.id} onClick={() => setFilter(f.id)} style={{
            padding: '5px 10px', borderRadius: 99,
            fontSize: 11.5, fontWeight: 600, letterSpacing: 0.2,
            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}`,
            whiteSpace: 'nowrap',
            display: 'flex', alignItems: 'center', gap: 5,
          }}>
            {f.label}
            <span className="tnum" 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>

      {/* Client list */}
      <div className="scroll" style={{ flex: 1, overflowY: 'auto', borderTop: `1px solid ${theme.rule}` }}>
        {loading && (
          <div style={{ padding: 40, textAlign: 'center', color: theme.inkMute, fontSize: 12.5 }}>
            Loading clients…
          </div>
        )}
        {!loading && error && (
          <div style={{ padding: 24, textAlign: 'center', color: '#7A2E11', fontSize: 12.5, lineHeight: 1.5 }}>
            Couldn't load roster.
            <br/><span style={{ color: theme.inkMute }}>{error.message}</span>
          </div>
        )}
        {!loading && !error && visible.map(c => (
          <ClientRow key={c.id} c={c} theme={theme} selected={c.id === selectedId} onClick={() => onSelect(c.id)}/>
        ))}
        {!loading && !error && visible.length === 0 && (
          <div style={{ padding: 40, textAlign: 'center', color: theme.inkMute, fontSize: 12.5 }}>
            {pool.length === 0 ? 'No clients yet. Click "New" to create your first.' : 'No clients match.'}
          </div>
        )}
      </div>
    </div>
  );
}

function ClientRow({ c, theme, selected, onClick }) {
  const statusColor = ({
    Active: theme.accent.solid,
    Intake: '#9B6B2F',
    Settled: '#2F6A4F',
  })[c.status] || theme.inkMute;

  return (
    <button onClick={onClick} style={{
      width: '100%', textAlign: 'left',
      padding: '11px 14px 11px 14px',
      borderBottom: `1px solid ${theme.rule}`,
      background: selected ? '#EAF1FB' : 'transparent',
      borderLeft: `3px solid ${selected ? theme.surface : 'transparent'}`,
      display: 'flex', gap: 11, alignItems: 'flex-start',
      position: 'relative',
    }}>
      <div style={{
        width: 34, height: 34, borderRadius: 99, flexShrink: 0,
        background: selected ? theme.surface : theme.canvas2,
        color: selected ? theme.onSurface : theme.ink,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 11, fontWeight: 700, letterSpacing: 0.5,
      }}>{c.initials}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 6 }}>
          <div style={{ fontSize: 13.5, fontWeight: 600, color: theme.ink, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {c.name}
          </div>
          {c.flagsAtRisk && (
            <span style={{ fontSize: 9, fontWeight: 700, letterSpacing: 0.6, color: '#B5481D', flexShrink: 0 }}>
              ⚐ AT RISK
            </span>
          )}
        </div>
        <div style={{ fontSize: 11.5, color: theme.inkMute, marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {c.biz}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6 }}>
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 4,
            fontSize: 10.5, fontWeight: 600, color: statusColor, letterSpacing: 0.3,
          }}>
            <span style={{ width: 5, height: 5, borderRadius: 99, background: statusColor }}/>
            {c.status}
          </span>
          {c.enrolled > 0 && (
            <span className="tnum" style={{ fontSize: 11, color: theme.inkDim, fontWeight: 500 }}>
              ${(c.enrolled / 1000).toFixed(0)}k
            </span>
          )}
          {c.pendingApprovals > 0 && (
            <span style={{
              fontSize: 9.5, fontWeight: 700, letterSpacing: 0.6,
              padding: '2px 6px', borderRadius: 99,
              background: '#FEEFD9', color: '#7A4A0F',
            }}>
              {c.pendingApprovals} PENDING
            </span>
          )}
        </div>
      </div>
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// RIGHT RAIL — context, pending items, audit
// ─────────────────────────────────────────────────────────────
function AdminRightRail({ theme, role, client, onAddEvent, onAssignRep, onLogOffer, onUploadDoc, onUpdatePayment }) {
  if (!client) return <div style={{ width: 320, background: theme.raised, borderLeft: `1px solid ${theme.rule}` }}/>;
  const rep = repById(client.rep);
  const referrer = refById(client.referrer);
  const lenders = lendersForClient(client.id);
  const pendingOffer = lenders.find(l => l.status === 'Offer Received');
  const audit = auditForClient(client.id);

  return (
    <div style={{
      width: 320, flexShrink: 0,
      background: theme.raised,
      borderLeft: `1px solid ${theme.rule}`,
      display: 'flex', flexDirection: 'column',
      overflow: 'hidden',
    }}>
      <div className="scroll" style={{ overflowY: 'auto', flex: 1, padding: '14px 16px 24px' }}>

        {/* Quick actions (admin only) */}
        {role === 'admin' && (
          <div>
            <div style={{ fontSize: 10, color: theme.inkMute, fontWeight: 600, letterSpacing: 1.6, textTransform: 'uppercase' }}>Actions</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6, marginTop: 8 }}>
              <AdminQuickAction icon="plus"    label="Add event"        onClick={onAddEvent}        theme={theme}/>
              <AdminQuickAction icon="upload"  label="Upload doc"       onClick={onUploadDoc}       theme={theme}/>
              <AdminQuickAction icon="spark"   label="Log offer"        onClick={onLogOffer}        theme={theme}/>
              <AdminQuickAction icon="pay"     label="Update payment"   onClick={onUpdatePayment}   theme={theme}/>
              <AdminQuickAction icon="user"    label="Assign rep"       onClick={onAssignRep}       theme={theme} wide/>
            </div>
          </div>
        )}

        {/* Pending approvals */}
        {pendingOffer && (
          <div style={{ marginTop: 18 }}>
            <div style={{ fontSize: 10, color: theme.inkMute, fontWeight: 600, letterSpacing: 1.6, textTransform: 'uppercase' }}>
              Awaiting client
            </div>
            <div style={{
              marginTop: 8, padding: 12,
              background: '#FEEFD9', border: '1px solid #F5D7A1',
              borderRadius: 10,
            }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: '#7A4A0F', letterSpacing: 0.4, textTransform: 'uppercase' }}>
                Offer pending sign-off
              </div>
              <div style={{ fontSize: 13, fontWeight: 600, color: theme.ink, marginTop: 6 }}>
                {pendingOffer.name}
              </div>
              <div className="tnum" style={{ fontSize: 12, color: theme.inkDim, marginTop: 3 }}>
                Settlement ${pendingOffer.settlement?.toLocaleString()} · 59% of balance
              </div>
              {role === 'admin' && (
                <button style={{
                  marginTop: 9, fontSize: 11.5, fontWeight: 600,
                  color: '#7A4A0F', textDecoration: 'underline',
                }}>Send reminder →</button>
              )}
            </div>
          </div>
        )}

        {/* Specialist */}
        <div style={{ marginTop: 18 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <div style={{ fontSize: 10, color: theme.inkMute, fontWeight: 600, letterSpacing: 1.6, textTransform: 'uppercase' }}>
              Assigned Specialist
            </div>
            {role === 'admin' && (
              <button onClick={onAssignRep} style={{ fontSize: 11, fontWeight: 600, color: theme.surface }}>Change</button>
            )}
          </div>
          <div style={{
            marginTop: 8, padding: 12,
            background: theme.canvas, border: `1px solid ${theme.rule}`,
            borderRadius: 10, display: 'flex', alignItems: 'center', gap: 11,
          }}>
            <div style={{
              width: 38, height: 38, borderRadius: 99,
              background: `linear-gradient(135deg, ${theme.accent.solid}, ${theme.accent.ink})`,
              color: '#fff', fontSize: 12, fontWeight: 700, letterSpacing: 0.5,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'Newsreader, serif',
            }}>{rep?.initials}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600, color: theme.ink }}>{rep?.name}</div>
              <div style={{ fontSize: 11.5, color: theme.inkMute, marginTop: 2 }}>{rep?.role}</div>
              <div className="tnum" style={{ fontSize: 10.5, color: theme.inkMute, marginTop: 3 }}>
                Caseload {rep?.caseload}/{rep?.capacity}
              </div>
            </div>
          </div>
        </div>

        {/* Referrer */}
        {referrer && (
          <div style={{ marginTop: 18 }}>
            <div style={{ fontSize: 10, color: theme.inkMute, fontWeight: 600, letterSpacing: 1.6, textTransform: 'uppercase' }}>
              Referral Source
            </div>
            <div style={{
              marginTop: 8, padding: 12,
              background: theme.canvas, border: `1px solid ${theme.rule}`,
              borderRadius: 10,
            }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: theme.ink }}>{referrer.name}</div>
              <div style={{ fontSize: 11.5, color: theme.inkMute, marginTop: 3 }}>{referrer.contact} · {referrer.email}</div>
            </div>
          </div>
        )}

        {/* Audit log (admin only) */}
        {role === 'admin' && audit.length > 0 && (
          <div style={{ marginTop: 18 }}>
            <div style={{ fontSize: 10, color: theme.inkMute, fontWeight: 600, letterSpacing: 1.6, textTransform: 'uppercase' }}>
              Recent activity (internal)
            </div>
            <div style={{
              marginTop: 8, background: theme.canvas, border: `1px solid ${theme.rule}`,
              borderRadius: 10, overflow: 'hidden',
            }}>
              {audit.slice(0, 5).map((a, i, arr) => {
                const who = a.who === 'system' ? 'System' : repById(a.who)?.name;
                return (
                  <div key={i} style={{
                    padding: '9px 12px',
                    borderBottom: i < arr.length - 1 ? `1px solid ${theme.rule}` : 'none',
                  }}>
                    <div style={{ fontSize: 11.5, color: theme.ink, lineHeight: 1.35 }}>{a.what}</div>
                    <div style={{ fontSize: 10.5, color: theme.inkMute, marginTop: 3 }}>{who} · {a.when}</div>
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function AdminQuickAction({ icon, label, onClick, theme, wide }) {
  return (
    <button onClick={onClick} style={{
      gridColumn: wide ? 'span 2' : 'auto',
      padding: '10px 10px', borderRadius: 9,
      background: theme.canvas, border: `1px solid ${theme.rule}`,
      display: 'flex', alignItems: 'center', gap: 8,
      color: theme.ink,
    }}>
      <Icon name={icon} size={14} color={theme.surface}/>
      <span style={{ fontSize: 12, fontWeight: 500, lineHeight: 1 }}>{label}</span>
    </button>
  );
}

Object.assign(window, {
  AdminTopBar, AdminLeftRail, ClientRow, AdminRightRail, AdminQuickAction,
});
