// Admin roster — list of all clients for the agency.
// Clicking a row "enters" that client's portal (for demo we just switch to client view).

function AdminRoster({ pal, onOpenClient }) {
  const [q, setQ] = React.useState('');
  const [tier, setTier] = React.useState('all');
  const [sort, setSort] = React.useState('touch');
  const [roster, setRoster] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      const r = await window.Portal.loadRoster();
      if (!cancelled) { setRoster(r); setLoading(false); }
    })();
    return () => { cancelled = true; };
  }, []);

  let clients = roster.slice();
  if (tier !== 'all') clients = clients.filter(c => c.tier === tier);
  if (q.trim()) {
    const n = q.toLowerCase();
    clients = clients.filter(c => (c.name + ' ' + c.site).toLowerCase().includes(n));
  }
  clients.sort((a, b) => {
    if (sort === 'name') return a.name.localeCompare(b.name);
    if (sort === 'mrr') return b.mrr - a.mrr;
    if (sort === 'hours') return (b.used / b.total) - (a.used / a.total);
    return 0;
  });

  const totalMrr = roster.reduce((s, c) => s + (c.mrr || 0), 0);
  const totalOpen = roster.reduce((s, c) => s + (c.openRequests || 0), 0);
  const needAttention = roster.filter(c => c.health && c.health !== 'good').length;
  const atRisk = roster.filter(c => c.total && c.used / c.total > 0.8).length;
  const today = new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric' });

  return (
    <Page pal={pal}
      kicker={`Agency view · ${today}`}
      title={<>Client <em style={{ fontStyle: 'italic', color: pal.accent }}>roster</em></>}
      sub={loading ? 'Loading roster…' : `${roster.length} active care plans · $${totalMrr.toLocaleString()} monthly recurring`}
      actions={<>
        <BtnGhost pal={pal}>Export</BtnGhost>
        <BtnPrimary pal={pal}>+ Invite client</BtnPrimary>
      </>}
    >
      {/* KPI strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 26 }}>
        <KpiTile pal={pal} kicker="MRR" big={`$${totalMrr.toLocaleString()}`} sub={`${roster.length} clients`} />
        <KpiTile pal={pal} kicker="Open requests" big={totalOpen} sub="across all clients" />
        <KpiTile pal={pal} kicker="Need attention" big={needAttention} sub="health not green" tone={needAttention > 0 ? 'warn' : 'good'} />
        <KpiTile pal={pal} kicker="Hours at risk" big={atRisk} sub=">80% used" tone={atRisk > 0 ? 'warn' : 'good'} />
      </div>

      {/* Filters */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16, gap: 16, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', gap: 8 }}>
          {['all', 'Essentials', 'Growth', 'Stewardship'].map(k => (
            <Pill key={k} pal={pal} active={tier === k} onClick={() => setTier(k)}>{k === 'all' ? 'All tiers' : k}</Pill>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <div style={{ width: 220 }}>
            <Input pal={pal} placeholder="Search clients…" value={q} onChange={e => setQ(e.target.value)} />
          </div>
          <select value={sort} onChange={e => setSort(e.target.value)} style={{
            padding: '10px 14px', fontSize: 12, color: pal.textStrong,
            background: pal.warm, border: `1px solid ${pal.border}`, borderRadius: 10,
            outline: 'none', cursor: 'pointer', fontFamily: 'inherit',
          }}>
            <option value="touch">Sort · Recent</option>
            <option value="name">Sort · Name</option>
            <option value="mrr">Sort · MRR</option>
            <option value="hours">Sort · Hours used</option>
          </select>
        </div>
      </div>

      {/* Client table */}
      <Card pal={pal}>
        <div style={{
          display: 'grid', gridTemplateColumns: '1.6fr 140px 1.4fr 100px 100px 110px 80px',
          padding: '14px 24px', borderBottom: `1px solid ${pal.border}`,
          fontSize: 10, fontWeight: 700, letterSpacing: '0.1em',
          textTransform: 'uppercase', color: pal.muted,
        }}>
          <div>Client</div>
          <div>Plan</div>
          <div>Hours this cycle</div>
          <div>Open</div>
          <div>MRR</div>
          <div>Last touch</div>
          <div></div>
        </div>
        {clients.map((c, i) => {
          const slug = c.slug || (c.name || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
          const pct = c.used / Math.max(c.total, 1);
          const rgb = hexToRgb(pal.accent);
          return (
            <div key={c.name} onClick={() => {
              // Switch URL to ?c=slug — keep view=admin&key=... so admin context persists
              const url = new URL(window.location.href);
              url.searchParams.set('c', slug);
              window.history.replaceState({}, '', url);
              onOpenClient && onOpenClient(slug);
            }} style={{
              display: 'grid', gridTemplateColumns: '1.6fr 140px 1.4fr 100px 100px 110px 80px',
              padding: '18px 24px', alignItems: 'center',
              borderTop: i === 0 ? 'none' : `1px solid ${pal.border}`,
              cursor: 'pointer',
              transition: 'background 0.12s',
            }}
              onMouseEnter={e => { e.currentTarget.style.background = pal.warm; }}
              onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
            >
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <HealthDot pal={pal} status={c.health} label="" />
                <div>
                  <div style={{ fontSize: 14, color: pal.textStrong, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 8 }}>
                    {c.name}
                  </div>
                  <div style={{ fontSize: 11, color: pal.muted, marginTop: 2 }}>{c.site}</div>
                </div>
              </div>
              <div><TierBadge pal={pal} tier={c.tier} /></div>
              <div style={{ paddingRight: 16 }}>
                <HoursBar pal={pal} used={c.used} total={c.total} segments={c.total * 2} compact />
                <div style={{ fontSize: 11, color: pct > 0.9 ? pal.warn : pal.muted, marginTop: 6, fontFamily: "'JetBrains Mono', monospace" }}>
                  {c.used.toFixed(2)} / {c.total} hrs
                </div>
              </div>
              <div style={{
                fontSize: 13, fontWeight: 600,
                color: c.openRequests > 0 ? pal.accent : pal.muted,
                fontFamily: "'JetBrains Mono', monospace",
              }}>{c.openRequests}</div>
              <div style={{ fontSize: 13, color: pal.textStrong, fontWeight: 500, fontFamily: "'JetBrains Mono', monospace" }}>${c.mrr}</div>
              <div style={{ fontSize: 12, color: pal.muted }}>{c.lastTouch}</div>
              <div style={{ textAlign: 'right', fontSize: 14, color: pal.accent }}>→</div>
            </div>
          );
        })}
      </Card>

      <div style={{ marginTop: 18, fontSize: 12, color: pal.muted, textAlign: 'center', fontStyle: 'italic' }}>
        Click any row to open that client's portal view.
      </div>
    </Page>
  );
}

function KpiTile({ pal, kicker, big, sub, tone }) {
  const toneColor = tone === 'warn' ? pal.warn : tone === 'good' ? pal.success : pal.navy;
  return (
    <Card pal={pal} padding={22}>
      <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color: pal.muted, marginBottom: 8 }}>{kicker}</div>
      <div style={{ fontFamily: "'Playfair Display', serif", fontSize: 34, fontWeight: 800, color: toneColor, letterSpacing: '-0.02em', lineHeight: 1 }}>{big}</div>
      <div style={{ fontSize: 11, color: pal.muted, marginTop: 8 }}>{sub}</div>
    </Card>
  );
}

window.AdminRoster = AdminRoster;
