// hq-cockpit.jsx — the single read-only "Operator cockpit" screen.
// Principle: READ HERE, ACT THERE. Every mutating path is a deep-link OUT
// to Stripe (billing) or Supabase (app data). Nothing here writes.

function HqCockpit() {
  const A = HQ_AGENCIES;
  const [sel, setSel] = React.useState(null);

  // Derive KPIs straight from the (mirrored) operator data so everything ties out.
  const active   = A.filter(a => a.status === 'active');
  const trialing = A.filter(a => a.status === 'trial');
  const pastDue  = A.filter(a => a.status === 'past_due');
  const canceled = A.filter(a => a.status === 'churned');
  const mrr      = A.reduce((s, a) => s + a.mrr, 0);            // active + past-due owe
  const pilgrims = A.reduce((s, a) => s + a.pilgrims, 0);

  // MRR sparkline scaled to land on the live figure.
  const sc = mrr / (HQ_MRR_SERIES[HQ_MRR_SERIES.length - 1] * 1000);
  const mrrSpark = HQ_MRR_SERIES.map(v => v * 1000 * sc);
  const pilgrimSpark = HQ_PILGRIM_SERIES.map(v => v * (pilgrims / HQ_PILGRIM_SERIES[HQ_PILGRIM_SERIES.length - 1]));

  return (
    <main style={{ flex: 1, overflowY: 'auto', background: 'var(--ug-surface)' }}>
      <div style={{ padding: '22px 26px 56px', maxWidth: 1440, margin: '0 auto' }}>

        {/* Header strip */}
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 20, marginBottom: 18, flexWrap: 'wrap' }}>
          <div>
            <div style={{ fontFamily: 'var(--ug-display)', fontSize: 25, fontWeight: 'var(--ug-display-weight)', letterSpacing: 'var(--ug-display-letter)', color: 'var(--ug-ink)', lineHeight: 1.1 }}>
              Subscriber overview
            </div>
            <div style={{ fontSize: 13, color: 'var(--ug-muted)', marginTop: 4 }}>
              {A.length} operators on Muyassir · {pilgrims.toLocaleString('en-GB')} pilgrims under management
            </div>
          </div>
          <SyncStrip />
        </div>

        {/* KPI row */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 13, marginBottom: 16 }}>
          <KpiCard label="Monthly recurring revenue" value={hqMoney(mrr)} accent="var(--ug-primary)"
            foot={<><HqDelta value={HQ_KPI.mrrDeltaPct} /><span style={{ fontSize: 11.5, color: 'var(--ug-muted)' }}>vs last month</span></>}
            chart={<HqSpark data={mrrSpark} width={150} height={34} color="var(--ug-success)" />} />
          <KpiCard label="Active subscribers" value={active.length} accent="var(--ug-primary)"
            foot={<span style={{ fontSize: 11.5, color: 'var(--ug-muted)' }}>{trialing.length} trialing · {canceled.length} canceled</span>} />
          <KpiCard label="Pilgrims · all operators" value={pilgrims.toLocaleString('en-GB')} accent="var(--ug-primary)"
            foot={<span style={{ fontSize: 11.5, color: 'var(--ug-muted)' }}>live + upcoming batches</span>}
            chart={<HqSpark data={pilgrimSpark} width={150} height={34} color="var(--ug-gold)" />} />
          <KpiCard label="Past due / failed" value={pastDue.length + 1} alert={pastDue.length + 1 > 0}
            foot={<span style={{ fontSize: 11.5, color: 'var(--ug-danger)', fontWeight: 600 }}>{pastDue.length} past-due · 1 failed charge</span>} />
          <KpiCard label="Trials / onboarding" value={trialing.length} accent="#5B7A9A"
            foot={<span style={{ fontSize: 11.5, color: 'var(--ug-muted)' }}>1 converts in 6 days</span>} />
        </div>

        {/* Main grid */}
        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.62fr) minmax(320px, 1fr)', gap: 16, alignItems: 'start' }}>
          <OperatorsPanel agencies={A} onSelect={setSel} />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <AttentionPanel />
            <RevenueMix agencies={A} mrr={mrr} />
          </div>
        </div>
      </div>

      <HqOperatorDrawer agency={sel} onClose={() => setSel(null)} />
    </main>
  );
}

// ── Sync strip (top-right) ───────────────────────────────────────────────
function SyncStrip() {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      {['stripe', 'supabase'].map(k => {
        const s = HQ_SYNC[k];
        return (
          <div key={k} title={s.what} style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '8px 13px', borderRadius: 10, background: 'var(--ug-card)', border: '1px solid var(--ug-hairline)' }}>
            <span style={{ width: 8, height: 8, borderRadius: 2, background: s.color, flexShrink: 0 }} />
            <div style={{ lineHeight: 1.25 }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ug-ink)' }}>{s.label} <span style={{ fontWeight: 500, color: 'var(--ug-muted)' }}>· {s.purpose}</span></div>
              <div style={{ fontSize: 10.5, color: 'var(--ug-muted)' }}>synced {s.synced}</div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ── KPI card ─────────────────────────────────────────────────────────────
function KpiCard({ label, value, foot, chart, alert, accent }) {
  return (
    <div style={{
      background: alert ? 'color-mix(in srgb, var(--ug-danger) 6%, var(--ug-card))' : 'var(--ug-card)',
      border: alert ? '1px solid color-mix(in srgb, var(--ug-danger) 35%, transparent)' : '1px solid var(--ug-hairline)',
      borderRadius: 14, padding: '15px 16px', display: 'flex', flexDirection: 'column', gap: 9, minHeight: 118,
    }}>
      <div style={{ fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: alert ? 'var(--ug-danger)' : 'var(--ug-muted)', fontWeight: 600 }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 8 }}>
        <div style={{ fontFamily: 'var(--ug-display)', fontSize: 30, fontWeight: 'var(--ug-display-weight)', color: alert ? 'var(--ug-danger)' : 'var(--ug-ink)', lineHeight: 1, letterSpacing: '-0.01em' }}>{value}</div>
        {chart && <div style={{ marginBottom: 1 }}>{chart}</div>}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginTop: 'auto' }}>{foot}</div>
    </div>
  );
}

// ── Operators panel (search + filters + table) ───────────────────────────
function OperatorsPanel({ agencies, onSelect }) {
  const [q, setQ] = React.useState('');
  const [filter, setFilter] = React.useState('all');

  const counts = {
    all: agencies.length,
    active: agencies.filter(a => a.status === 'active').length,
    trial: agencies.filter(a => a.status === 'trial').length,
    past_due: agencies.filter(a => a.status === 'past_due').length,
    churned: agencies.filter(a => a.status === 'churned').length,
  };
  const TABS = [
    { id: 'all', label: 'All' }, { id: 'active', label: 'Active' }, { id: 'trial', label: 'Trialing' },
    { id: 'past_due', label: 'Past due' }, { id: 'churned', label: 'Canceled' },
  ];

  const rows = agencies
    .filter(a => filter === 'all' || a.status === filter)
    .filter(a => !q || a.name.toLowerCase().includes(q.toLowerCase()) || a.country.toLowerCase().includes(q.toLowerCase()))
    .sort((a, b) => b.mrr - a.mrr);

  return (
    <HqCard pad={0} style={{ overflow: 'hidden' }}>
      {/* Header: title + search */}
      <div style={{ padding: '16px 18px 12px', display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
        <div style={{ flex: 1, minWidth: 160 }}>
          <div style={{ fontFamily: 'var(--ug-display)', fontSize: 16.5, fontWeight: 'var(--ug-display-weight)', color: 'var(--ug-ink)' }}>Operators</div>
          <div style={{ fontSize: 11.5, color: 'var(--ug-muted)', marginTop: 2 }}>Tap a name for the full account. Change billing in Stripe, account data in Supabase.</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px', borderRadius: 9, background: 'var(--ug-surface-alt)', width: 230 }}>
          <HqIcon name="search" size={16} color="var(--ug-muted)" />
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search operator or country…" style={{ border: 'none', background: 'transparent', outline: 'none', fontFamily: 'var(--ug-body)', fontSize: 12.5, color: 'var(--ug-ink)', width: '100%' }} />
        </div>
      </div>

      {/* Filter tabs */}
      <div style={{ display: 'flex', gap: 6, padding: '0 18px 12px', flexWrap: 'wrap' }}>
        {TABS.map(t => {
          const on = filter === t.id;
          return (
            <button key={t.id} onClick={() => setFilter(t.id)} style={{
              display: 'inline-flex', alignItems: 'center', gap: 7, padding: '6px 12px', borderRadius: 8, cursor: 'pointer',
              fontFamily: 'var(--ug-body)', fontSize: 12.5, fontWeight: 600, transition: 'background .15s',
              border: on ? '1px solid var(--ug-primary)' : '1px solid var(--ug-hairline)',
              background: on ? 'var(--ug-primary)' : 'var(--ug-card)', color: on ? 'var(--ug-primary-ink)' : 'var(--ug-ink-soft)',
            }}>
              {t.label}
              <span style={{ fontSize: 11, fontWeight: 700, padding: '1px 6px', borderRadius: 6, background: on ? 'rgba(255,255,255,0.18)' : 'var(--ug-surface-alt)', color: on ? 'var(--ug-primary-ink)' : 'var(--ug-muted)' }}>{counts[t.id]}</span>
            </button>
          );
        })}
      </div>

      {/* Table header */}
      <div style={{ display: 'grid', gridTemplateColumns: '3fr 0.9fr 1.05fr 0.7fr 0.65fr 0.9fr 1.5fr', gap: 12, padding: '9px 18px', borderTop: '1px solid var(--ug-hairline)', borderBottom: '1px solid var(--ug-hairline)', background: 'var(--ug-surface)' }}>
        {['Operator', 'Plan', 'Status', 'MRR', 'Pilgrims', 'Last active', ''].map((h, i) => (
          <div key={i} style={{ fontSize: 10.5, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ug-muted)', fontWeight: 600, textAlign: i >= 3 && i <= 4 ? 'right' : 'left' }}>{h}</div>
        ))}
      </div>

      {/* Rows */}
      <div>
        {rows.map((a, i) => <OperatorRow key={a.id} a={a} last={i === rows.length - 1} onSelect={onSelect} />)}
        {rows.length === 0 && <div style={{ padding: '34px 18px', textAlign: 'center', fontSize: 13, color: 'var(--ug-muted)' }}>No operators match.</div>}
      </div>

      <div style={{ padding: '11px 18px', borderTop: '1px solid var(--ug-hairline)', fontSize: 11.5, color: 'var(--ug-muted)', display: 'flex', justifyContent: 'space-between' }}>
        <span>Showing {rows.length} of {agencies.length} operators</span>
        <span>Sorted by MRR</span>
      </div>
    </HqCard>
  );
}

function OperatorRow({ a, last, onSelect }) {
  const st = HQ_STATUS[a.status];
  const trial = a.status === 'trial', canceled = a.status === 'churned';
  return (
    <div onClick={() => onSelect && onSelect(a)} style={{
      display: 'grid', gridTemplateColumns: '3fr 0.9fr 1.05fr 0.7fr 0.65fr 0.9fr 1.5fr', gap: 12, alignItems: 'center',
      padding: '12px 18px', borderBottom: last ? 'none' : '1px solid var(--ug-hairline)',
      transition: 'background .12s', cursor: 'pointer',
    }}
      onMouseEnter={e => e.currentTarget.style.background = 'var(--ug-surface)'}
      onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
    >
      {/* Operator */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 11, minWidth: 0 }}>
        <HqAvatar a={a} size={36} />
        <div style={{ minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
            <span style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ug-ink)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', minWidth: 0 }}>{a.name}</span>
            {a.verified && <HqIcon name="check" size={13} color="var(--ug-success)" stroke={2.6} />}
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--ug-muted)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{a.country}</div>
        </div>
      </div>
      {/* Plan */}
      <div><HqPlanChip plan={a.plan} /></div>
      {/* Status */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
        <HqBadge label={st.label} color={st.tone} />
        {a.status === 'past_due' && <span style={{ fontSize: 10.5, color: 'var(--ug-danger)', fontWeight: 600 }}>{a.overdueDays}d overdue</span>}
        {trial && <span style={{ fontSize: 10.5, color: 'var(--ug-muted)' }}>{a.trialDays}d left</span>}
      </div>
      {/* MRR */}
      <div style={{ textAlign: 'right', fontSize: 13.5, fontWeight: 600, color: (trial || canceled) ? 'var(--ug-muted)' : 'var(--ug-ink)' }}>
        {(trial || canceled) ? '—' : hqMoney(a.mrr)}
      </div>
      {/* Pilgrims */}
      <div style={{ textAlign: 'right', fontSize: 13, color: 'var(--ug-ink-soft)' }}>{a.pilgrims || '—'}</div>
      {/* Last active */}
      <div style={{ fontSize: 12, color: 'var(--ug-muted)' }}>{a.lastActive}</div>
      {/* Actions — deep links OUT (named by purpose) */}
      <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
        <HqLinkOut tool="stripe" label="Billing" />
        <HqLinkOut tool="supabase" label="Account" />
      </div>
    </div>
  );
}

// ── Needs attention ──────────────────────────────────────────────────────
const HQ_SEV = { high: 'var(--ug-danger)', medium: '#C77D3A', low: 'var(--ug-gold)' };
function AttentionPanel() {
  return (
    <HqCard pad={0}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '15px 18px 12px' }}>
        <div style={{ width: 30, height: 30, borderRadius: 9, background: 'color-mix(in srgb, var(--ug-danger) 12%, transparent)', color: 'var(--ug-danger)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <HqIcon name="alert" size={17} />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: 'var(--ug-display)', fontSize: 16, fontWeight: 'var(--ug-display-weight)', color: 'var(--ug-ink)' }}>Needs attention</div>
          <div style={{ fontSize: 11.5, color: 'var(--ug-muted)', marginTop: 1 }}>Resolve in the source tool</div>
        </div>
        <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--ug-danger)', background: 'color-mix(in srgb, var(--ug-danger) 12%, transparent)', padding: '3px 9px', borderRadius: 7 }}>{HQ_ATTENTION.length}</span>
      </div>
      <div>
        {HQ_ATTENTION.map((it, i) => (
          <div key={it.id} style={{ display: 'flex', gap: 11, padding: '13px 18px', borderTop: '1px solid var(--ug-hairline)' }}>
            <span style={{ width: 8, height: 8, borderRadius: 4, background: HQ_SEV[it.sev], marginTop: 5, flexShrink: 0 }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 8 }}>
                <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--ug-ink)' }}>{it.title}</span>
              </div>
              <div style={{ fontSize: 12, color: 'var(--ug-ink-soft)', marginTop: 2, fontWeight: 600 }}>{it.agency}</div>
              <div style={{ fontSize: 11.5, color: 'var(--ug-muted)', marginTop: 2, lineHeight: 1.45 }}>{it.detail}</div>
              <div style={{ marginTop: 8 }}>
                <HqLinkOut tool={it.tool} label={it.tool === 'stripe' ? 'Resolve billing in Stripe' : 'Review in Supabase'} />
              </div>
            </div>
          </div>
        ))}
      </div>
    </HqCard>
  );
}

// ── Revenue mix (plan distribution) ──────────────────────────────────────
function RevenueMix({ agencies, mrr }) {
  const order = ['premium', 'base'];
  const byPlan = order.map(k => {
    const items = agencies.filter(a => a.plan === k && a.mrr > 0);
    return { key: k, label: HQ_PLANS[k].label, color: HQ_PLANS[k].tone, count: items.length, sum: items.reduce((s, a) => s + a.mrr, 0) };
  }).filter(p => p.sum > 0);

  return (
    <HqCard>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
        <div style={{ fontFamily: 'var(--ug-display)', fontSize: 16, fontWeight: 'var(--ug-display-weight)', color: 'var(--ug-ink)' }}>MRR by plan</div>
        <HqLinkOut tool="stripe" label="Stripe billing" />
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 13 }}>
        {byPlan.map(p => (
          <div key={p.key}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 5 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ width: 9, height: 9, borderRadius: 3, background: p.color }} />
                <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--ug-ink)' }}>{p.label}</span>
                <span style={{ fontSize: 11.5, color: 'var(--ug-muted)' }}>· {p.count}</span>
              </div>
              <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--ug-ink)' }}>{hqMoney(p.sum)}</span>
            </div>
            <HqMeter value={p.sum / mrr} color={p.color} />
          </div>
        ))}
      </div>
      <div style={{ marginTop: 16, paddingTop: 14, borderTop: '1px solid var(--ug-hairline)', display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
        <span style={{ fontSize: 12, color: 'var(--ug-muted)' }}>Total MRR</span>
        <span style={{ fontFamily: 'var(--ug-display)', fontSize: 21, fontWeight: 'var(--ug-display-weight)', color: 'var(--ug-ink)' }}>{hqMoney(mrr)}<span style={{ fontSize: 12, color: 'var(--ug-muted)', fontWeight: 400, fontFamily: 'var(--ug-body)' }}> /mo</span></span>
      </div>
    </HqCard>
  );
}

// ── Operator detail drawer (read-only profile, opens on row click) ────────
function HqOperatorDrawer({ agency, onClose }) {
  const open = !!agency;
  const [a, setA] = React.useState(agency);
  React.useEffect(() => { if (agency) setA(agency); }, [agency]);
  React.useEffect(() => {
    const onKey = e => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);
  if (!a) return null;

  const st = HQ_STATUS[a.status], hl = HQ_HEALTH[a.health], trial = a.status === 'trial', canceled = a.status === 'churned';
  const invoices = HQ_INVOICES.filter(iv => iv.agency === a.name).slice(0, 4);

  const Stat = ({ label, value, accent }) => (
    <div style={{ background: 'var(--ug-surface)', border: '1px solid var(--ug-hairline)', borderRadius: 11, padding: '11px 13px' }}>
      <div style={{ fontSize: 10.5, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ug-muted)', fontWeight: 600 }}>{label}</div>
      <div style={{ fontSize: 17, fontWeight: 700, color: accent || 'var(--ug-ink)', marginTop: 4, fontFamily: 'var(--ug-display)' }}>{value}</div>
    </div>
  );
  const SectionHead = ({ tool, title }) => {
    const s = HQ_SYNC[tool];
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
        <span style={{ width: 8, height: 8, borderRadius: 2, background: s.color }} />
        <div style={{ fontFamily: 'var(--ug-display)', fontSize: 15, fontWeight: 'var(--ug-display-weight)', color: 'var(--ug-ink)' }}>{title}</div>
        <span style={{ fontSize: 11, color: 'var(--ug-muted)', marginLeft: 'auto' }}>from {s.label}</span>
      </div>
    );
  };

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 60, display: open ? 'block' : 'none' }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(20,20,18,0.34)', opacity: open ? 1 : 0, transition: 'opacity .2s' }} />
      <div style={{
        position: 'absolute', top: 0, right: 0, height: '100%', width: 452, maxWidth: '92vw', background: 'var(--ug-card)',
        boxShadow: '-18px 0 50px rgba(20,20,18,0.18)', display: 'flex', flexDirection: 'column',
        transform: open ? 'translateX(0)' : 'translateX(100%)', transition: 'transform .26s cubic-bezier(.4,0,.2,1)',
      }}>
        {/* Header */}
        <div style={{ padding: '20px 22px 18px', borderBottom: '1px solid var(--ug-hairline)' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 13 }}>
            <HqAvatar a={a} size={46} radius={13} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                <span style={{ fontFamily: 'var(--ug-display)', fontSize: 19, fontWeight: 'var(--ug-display-weight)', color: 'var(--ug-ink)' }}>{a.name}</span>
                {a.verified && <HqIcon name="check" size={14} color="var(--ug-success)" stroke={2.6} />}
              </div>
              <div style={{ fontSize: 12.5, color: 'var(--ug-muted)', marginTop: 2 }}>{a.country} · operator since {a.joined.startsWith('Trial') ? 'trial' : a.joined}</div>
              <div style={{ display: 'flex', gap: 7, marginTop: 9, flexWrap: 'wrap' }}>
                <HqBadge label={st.label} color={st.tone} />
                <HqPlanChip plan={a.plan} />
                {!trial && !canceled && <HqBadge label={hl.label} color={hl.tone} />}
              </div>
            </div>
            <button onClick={onClose} style={{ ...hqIconBtn, width: 34, height: 34 }} aria-label="Close">
              <HqIcon name="x" size={17} color="var(--ug-ink-soft)" />
            </button>
          </div>
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '18px 22px 28px', display: 'flex', flexDirection: 'column', gap: 22 }}>

          {/* Subscription & billing — Stripe */}
          <div>
            <SectionHead tool="stripe" title="Subscription & billing" />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 9, marginBottom: 11 }}>
              <Stat label="Plan" value={HQ_PLANS[a.plan].label} accent="var(--ug-primary)" />
              <Stat label="MRR" value={(trial || canceled) ? '—' : hqMoney(a.mrr)} />
              <Stat label="Lifetime value" value={hqMoney(a.ltv)} />
              <Stat label={a.status === 'past_due' ? 'Overdue' : trial ? 'Trial ends' : 'Status'} value={a.status === 'past_due' ? `${a.overdueDays} days` : trial ? `${a.trialDays} days` : st.label} accent={a.status === 'past_due' ? 'var(--ug-danger)' : undefined} />
            </div>
            {a.status === 'past_due' && (
              <div style={{ fontSize: 12, color: 'var(--ug-danger)', background: 'color-mix(in srgb, var(--ug-danger) 8%, transparent)', borderRadius: 9, padding: '9px 12px', marginBottom: 11, fontWeight: 600 }}>
                Card declined ×2 · subscription cancels in 7 days if unpaid.
              </div>
            )}
            <HqLinkOut tool="stripe" label="Manage billing & invoices in Stripe" block size="md" />
            {invoices.length > 0 && (
              <div style={{ marginTop: 13 }}>
                <div style={{ fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ug-muted)', fontWeight: 600, marginBottom: 7 }}>Recent invoices</div>
                {invoices.map(iv => (
                  <div key={iv.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '7px 0', borderTop: '1px solid var(--ug-hairline)' }}>
                    <span style={{ fontSize: 12, fontFamily: 'var(--ug-body)', color: 'var(--ug-ink-soft)', fontWeight: 600 }}>{iv.id}</span>
                    <span style={{ fontSize: 11.5, color: 'var(--ug-muted)' }}>{iv.date}</span>
                    <span style={{ marginLeft: 'auto', fontSize: 12.5, fontWeight: 700, color: 'var(--ug-ink)' }}>{hqMoney(iv.amount)}</span>
                    <HqBadge label={HQ_INVOICE_STATUS[iv.status].label} color={HQ_INVOICE_STATUS[iv.status].tone} />
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Account & usage — Supabase */}
          <div>
            <SectionHead tool="supabase" title="Account & usage" />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 9, marginBottom: 12 }}>
              <Stat label="Pilgrims" value={a.pilgrims || '—'} />
              <Stat label="Batches" value={a.batches || '—'} />
              <Stat label="Leaders" value={a.leaders || '—'} />
            </div>
            <div style={{ marginBottom: 13 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 5 }}>
                <span style={{ fontSize: 12, color: 'var(--ug-muted)' }}>Feature adoption this month</span>
                <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--ug-ink)' }}>{Math.round(a.usage * 100)}%</span>
              </div>
              <HqMeter value={a.usage} color={a.usage < 0.4 ? 'var(--ug-danger)' : a.usage < 0.7 ? 'var(--ug-gold)' : 'var(--ug-success)'} />
              <div style={{ fontSize: 11.5, color: 'var(--ug-muted)', marginTop: 6 }}>Last active {a.lastActive} · licence {a.verified ? 'verified' : 'not yet uploaded'}</div>
            </div>
            <HqLinkOut tool="supabase" label="Open operator record in Supabase" block size="md" />
          </div>

          {/* Primary contact */}
          <div>
            <div style={{ fontFamily: 'var(--ug-display)', fontSize: 15, fontWeight: 'var(--ug-display-weight)', color: 'var(--ug-ink)', marginBottom: 10 }}>Primary contact</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 11, background: 'var(--ug-surface)', border: '1px solid var(--ug-hairline)', borderRadius: 11, padding: '12px 14px' }}>
              <div style={{ width: 36, height: 36, borderRadius: 18, background: 'var(--ug-surface-alt)', color: 'var(--ug-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <HqIcon name="users" size={18} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ug-ink)' }}>{a.owner}</div>
                <div style={{ fontSize: 12, color: 'var(--ug-muted)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{a.ownerEmail}</div>
              </div>
              <a href={`mailto:${a.ownerEmail}`} onClick={e => e.stopPropagation()} style={{ ...hqIconBtn, width: 34, height: 34, textDecoration: 'none' }} title="Email contact">
                <HqIcon name="external" size={15} color="var(--ug-ink-soft)" stroke={1.8} />
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function HqApp() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100vh', overflow: 'hidden', ...ugThemeVars('forest', 'editorial'), background: 'var(--ug-surface)' }}>
      <HqTopbar />
      <HqCockpit />
    </div>
  );
}

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