// screens-admin-analytics.jsx — Operator Console / Analytics workspace.
// Real-feeling charts (sparkline area, bar, donut, heatmap) using inline SVG.
// All data is per-tenant and shaped from a deterministic seed so the three
// tenants feel distinct (WVU, Utah, OSU) without needing real numbers.

// ─── Tenant-flavored data (seeded so it's deterministic) ──────
function _seed(s) {
  let h = 2166136261;
  for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); }
  return () => {
    h += 0x6D2B79F5; let t = h;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

function _series(seed, n, base, vol) {
  const out = []; let v = base;
  for (let i = 0; i < n; i++) {
    v = Math.max(base * 0.55, v + (seed() - 0.45) * vol);
    // Saturday spikes (every 7th)
    if (i % 7 === 6) v *= 1.8 + seed() * 0.3;
    out.push(Math.round(v));
  }
  return out;
}

function _analyticsFor(tenantId) {
  const tenantData = {
    wvu:  { fans: 184_320, dau: 47_210, base: 38_000, gmv: 412_800, retention: 68 },
    utah: { fans: 162_540, dau: 41_880, base: 33_500, gmv: 386_400, retention: 71 },
    osu:  { fans: 318_200, dau: 88_410, base: 71_000, gmv: 928_300, retention: 74 },
  };
  const d = tenantData[tenantId] || tenantData.wvu;
  const seed = _seed(tenantId);

  return {
    kpis: [
      { label: 'Daily active fans', value: d.dau.toLocaleString(), delta: '+12.4%', up: true, sub: 'vs last week' },
      { label: 'Game-day check-ins', value: '24,816', delta: '+38.2%',  up: true,  sub: 'home games · season' },
      { label: 'Merch GMV',          value: '$' + (d.gmv).toLocaleString(), delta: '+8.1%', up: true, sub: 'last 30 days' },
      { label: 'Avg session',        value: '6m 42s', delta: '+1m 04s',  up: true, sub: 'vs last week' },
    ],
    dauSeries:    _series(_seed(tenantId+'a'), 30, d.base, 4_500),
    revSeries:    _series(_seed(tenantId+'b'), 30, d.gmv/30, 12_000),
    funnel: [
      { label: 'App opens',     pct: 100, n: d.dau },
      { label: 'Viewed game',   pct: 72,  n: Math.round(d.dau * 0.72) },
      { label: 'Engaged stat',  pct: 54,  n: Math.round(d.dau * 0.54) },
      { label: 'Spent (any)',   pct: 21,  n: Math.round(d.dau * 0.21) },
      { label: 'Repeat visit',  pct: 13,  n: Math.round(d.dau * 0.13) },
    ],
    revenueMix: [
      { label: 'Tickets',     pct: 41, color: '#5B8DEF' },
      { label: 'Merch',       pct: 26, color: '#22C55E' },
      { label: 'Concessions', pct: 14, color: '#F59E0B' },
      { label: 'NIL · Tips',  pct: 11, color: '#A855F7' },
      { label: 'Sponsors',    pct:  8, color: '#EC4899' },
    ],
    cohorts: ['M','T','W','T','F','S','S'].map((d, di) => (
      Array.from({length: 8}, (_, hi) => ({
        d, h: 9 + hi * 2,
        // Saturday game-day spike at 12-4pm
        v: di === 5 && hi >= 1 && hi <= 4 ? 0.85 + seed()*0.15
           : di >= 5 ? 0.4 + seed()*0.3
           : 0.15 + seed()*0.4,
      }))
    )).flat(),
    sports: [
      { id: 'fb',  label: 'Football',     fans: 142_310, share: 78, dau: 32_600 },
      { id: 'mbb', label: 'Men\u2019s BB', fans:  84_220, share: 46, dau: 12_400 },
      { id: 'wbb', label: 'Women\u2019s BB',fans: 38_440, share: 21, dau:  4_180 },
      { id: 'gym', label: 'Gymnastics',   fans:  41_900, share: 23, dau:  3_900 },
      { id: 'wr',  label: 'Wrestling',    fans:  22_300, share: 12, dau:  1_710 },
      { id: 'ski', label: 'Skiing',       fans:  17_140, share:  9, dau:  1_220 },
    ],
    sponsors: [
      { brand: 'Mylan',          spend: 184_500, ctr: 6.8, redeems: 4_812, status: 'live' },
      { brand: 'WV Lottery',     spend: 121_000, ctr: 4.1, redeems: 2_188, status: 'live' },
      { brand: 'Mountaineer Energy', spend: 88_400,  ctr: 5.4, redeems: 1_904, status: 'live' },
      { brand: 'Sheetz',         spend: 71_200,  ctr: 7.2, redeems: 3_104, status: 'paused' },
      { brand: 'Coca-Cola',      spend: 312_000, ctr: 3.9, redeems: 6_410, status: 'live' },
      { brand: 'Nike',           spend: 410_000, ctr: 5.1, redeems: 8_902, status: 'live' },
    ],
  };
}

// ═══════════════════════════════════════════════════════════════
// Main workspace
// ═══════════════════════════════════════════════════════════════
function AnalyticsWorkspace({ T, accent, fontMono, pendingTenant }) {
  const [range, setRange] = React.useState('30d');
  const [compare, setCompare] = React.useState(true);
  const data = React.useMemo(() => _analyticsFor(pendingTenant.id), [pendingTenant.id]);

  return (
    <div style={{ padding: '20px 24px', maxWidth: 1280 }}>

      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16, marginBottom: 20 }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 19, fontWeight: 700, letterSpacing: '-0.015em' }}>
            Analytics &middot; {pendingTenant.short}
          </div>
          <div style={{ fontSize: 12.5, color: T.textDim, marginTop: 4 }}>
            Live engagement, revenue, and sponsor performance across the {pendingTenant.short} tenant.
          </div>
        </div>

        {/* Range tabs */}
        <div style={{
          display: 'flex', gap: 2, padding: 2,
          background: T.chipBg, borderRadius: 6,
          border: `1px solid ${T.border}`,
        }}>
          {['7d','30d','90d','YTD'].map(r => {
            const active = r === range;
            return (
              <button key={r}
                onClick={() => setRange(r)}
                style={{
                  padding: '4px 10px', borderRadius: 4,
                  background: active ? T.surface : 'transparent',
                  border: active ? `1px solid ${T.border}` : '1px solid transparent',
                  boxShadow: active ? T.shadow : 'none',
                  color: active ? T.text : T.textDim,
                  fontSize: 11, fontWeight: 600, cursor: 'pointer',
                  fontFamily: 'inherit',
                }}>{r}</button>
            );
          })}
        </div>

        <button onClick={() => setCompare(!compare)}
          style={{
            padding: '5px 11px', borderRadius: 5,
            background: compare ? T.activeBg : 'transparent',
            border: `1px solid ${T.border}`,
            color: T.text, fontSize: 11, fontWeight: 500,
            cursor: 'pointer', fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
          <span style={{
            width: 10, height: 10, borderRadius: 2,
            border: `1.5px solid ${compare ? accent : T.textFaint}`,
            background: compare ? accent : 'transparent',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: 'white', fontSize: 8,
          }}>{compare && '✓'}</span>
          Compare
        </button>

        <button style={{
          padding: '5px 11px', borderRadius: 5,
          background: 'transparent', border: `1px solid ${T.border}`,
          color: T.text, fontSize: 11, fontWeight: 500,
          cursor: 'pointer', fontFamily: 'inherit',
        }}>Export CSV</button>
      </div>

      {/* KPI row */}
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12,
        marginBottom: 14,
      }}>
        {data.kpis.map((k, i) => (
          <KpiCard key={i} T={T} accent={accent} fontMono={fontMono} {...k} sparkline={i % 2 === 0 ? data.dauSeries : data.revSeries} />
        ))}
      </div>

      {/* Big chart row: DAU area + Revenue bars */}
      <div style={{
        display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 12,
        marginBottom: 14,
      }}>
        <Card T={T} title="Daily active fans" sub={`Past ${range} \u00b7 ${pendingTenant.short}`} headerRight={
          <div style={{ display: 'flex', gap: 12, fontSize: 11, color: T.textDim }}>
            <Legend dot={accent}    label="This period" />
            {compare && <Legend dot={T.textFaint} label="Last period" dashed />}
          </div>
        }>
          <AreaChart series={data.dauSeries} compare={compare} accent={accent} T={T} fontMono={fontMono} />
        </Card>

        <Card T={T} title="Revenue mix" sub="Last 30 days">
          <Donut data={data.revenueMix} T={T} fontMono={fontMono} />
        </Card>
      </div>

      {/* Bars + Funnel */}
      <div style={{
        display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 12,
        marginBottom: 14,
      }}>
        <Card T={T} title="Daily revenue" sub={`Past ${range} \u00b7 includes tickets, merch, concessions, NIL`}>
          <BarChart series={data.revSeries} accent={accent} T={T} fontMono={fontMono} />
        </Card>

        <Card T={T} title="Engagement funnel" sub="App-open → repeat visit">
          <Funnel data={data.funnel} accent={accent} T={T} fontMono={fontMono} />
        </Card>
      </div>

      {/* Heatmap + Sport breakdown */}
      <div style={{
        display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 12,
        marginBottom: 14,
      }}>
        <Card T={T} title="Activity heatmap" sub="Average concurrent users by day &amp; hour">
          <Heatmap data={data.cohorts} accent={accent} T={T} fontMono={fontMono} />
        </Card>

        <Card T={T} title="Sport breakdown" sub="Fans following each program">
          <SportBars data={data.sports} accent={accent} T={T} fontMono={fontMono} />
        </Card>
      </div>

      {/* Sponsor table */}
      <Card T={T} title="Sponsor performance" sub="Last 30 days &middot; click any row to drill in">
        <SponsorTable data={data.sponsors} T={T} fontMono={fontMono} accent={accent} />
      </Card>

      <div style={{ height: 24 }} />
    </div>
  );
}

// ─── KPI card with mini sparkline ─────────────────────
function KpiCard({ T, accent, fontMono, label, value, delta, up, sub, sparkline }) {
  return (
    <div style={{
      background: T.surface, border: `1px solid ${T.border}`, borderRadius: 8,
      padding: '12px 14px', position: 'relative', overflow: 'hidden',
    }}>
      <div style={{ fontSize: 11.5, color: T.textDim, marginBottom: 6 }}>{label}</div>
      <div style={{
        display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 4,
      }}>
        <div style={{
          fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em',
          fontVariantNumeric: 'tabular-nums', color: T.text,
        }}>{value}</div>
        <div style={{
          fontSize: 11, fontWeight: 600,
          color: up ? '#1A8A4E' : '#C0392B',
          display: 'flex', alignItems: 'center', gap: 2,
          fontFamily: fontMono,
        }}>
          <svg width="9" height="9" viewBox="0 0 9 9">
            {up
              ? <path d="M1.5 6.5L4.5 2.5L7.5 6.5" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
              : <path d="M1.5 2.5L4.5 6.5L7.5 2.5" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
            }
          </svg>
          {delta}
        </div>
      </div>
      <div style={{ fontSize: 10.5, color: T.textFaint }}>{sub}</div>

      {/* Mini sparkline pinned to bottom-right */}
      <div style={{ position: 'absolute', right: 10, top: 10, opacity: 0.55 }}>
        <Sparkline series={sparkline.slice(-12)} color={accent} w={64} h={22} />
      </div>
    </div>
  );
}

function Sparkline({ series, color, w = 80, h = 24 }) {
  if (!series || !series.length) return null;
  const min = Math.min(...series), max = Math.max(...series);
  const span = max - min || 1;
  const pts = series.map((v, i) => {
    const x = (i / (series.length - 1)) * w;
    const y = h - ((v - min) / span) * (h - 2) - 1;
    return [x, y];
  });
  const path = pts.map(([x, y], i) => `${i === 0 ? 'M' : 'L'}${x.toFixed(1)},${y.toFixed(1)}`).join(' ');
  return (
    <svg width={w} height={h}>
      <path d={path} stroke={color} strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

function Legend({ dot, label, dashed }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
      <span style={{
        width: 10, height: 2, background: dot, borderRadius: 1,
        opacity: dashed ? 0.7 : 1,
        ...(dashed ? { backgroundImage: `linear-gradient(90deg, ${dot} 50%, transparent 50%)`, backgroundSize: '4px 2px' } : {}),
      }} />
      {label}
    </span>
  );
}

// ─── Area chart with grid + compare overlay ───────────
function AreaChart({ series, compare, accent, T, fontMono }) {
  const W = 560, H = 200, padL = 36, padR = 8, padT = 10, padB = 22;
  const innerW = W - padL - padR, innerH = H - padT - padB;
  if (!series.length) return null;

  const max = Math.max(...series) * 1.1;
  const min = 0;
  const span = max - min || 1;

  const pts = series.map((v, i) => {
    const x = padL + (i / (series.length - 1)) * innerW;
    const y = padT + innerH - ((v - min) / span) * innerH;
    return [x, y];
  });
  const linePath = pts.map(([x, y], i) => `${i === 0 ? 'M' : 'L'}${x.toFixed(1)},${y.toFixed(1)}`).join(' ');
  const areaPath = `${linePath} L${pts[pts.length-1][0]},${padT+innerH} L${pts[0][0]},${padT+innerH} Z`;

  // "Compare" series: shift backwards 12% so it looks like last period was lower
  const compareSeries = series.map(v => v * (0.84 + 0.08 * Math.random()));
  const cPts = compareSeries.map((v, i) => {
    const x = padL + (i / (compareSeries.length - 1)) * innerW;
    const y = padT + innerH - ((v - min) / span) * innerH;
    return [x, y];
  });
  const cPath = cPts.map(([x, y], i) => `${i === 0 ? 'M' : 'L'}${x.toFixed(1)},${y.toFixed(1)}`).join(' ');

  // Y axis labels
  const yTicks = [0, 0.25, 0.5, 0.75, 1].map(p => Math.round((min + span * p)));

  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 200, display: 'block' }}>
      <defs>
        <linearGradient id="areaFill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%"   stopColor={accent} stopOpacity="0.32" />
          <stop offset="100%" stopColor={accent} stopOpacity="0" />
        </linearGradient>
      </defs>

      {/* Grid */}
      {yTicks.map((v, i) => {
        const y = padT + innerH - (i / (yTicks.length - 1)) * innerH;
        return (
          <g key={i}>
            <line x1={padL} x2={W - padR} y1={y} y2={y} stroke={T.borderSoft} strokeWidth="1" />
            <text x={padL - 6} y={y + 3} textAnchor="end"
              fontFamily={fontMono} fontSize="9" fill={T.textFaint}>
              {v >= 1000 ? (v/1000).toFixed(1) + 'k' : v}
            </text>
          </g>
        );
      })}

      {/* X axis labels (every ~5th) */}
      {series.map((_, i) => {
        if (i % 5 !== 0 && i !== series.length - 1) return null;
        const x = padL + (i / (series.length - 1)) * innerW;
        const label = `D${i + 1}`;
        return <text key={i} x={x} y={H - 6} textAnchor="middle"
          fontFamily={fontMono} fontSize="9" fill={T.textFaint}>{label}</text>;
      })}

      {/* Compare line */}
      {compare && (
        <path d={cPath} stroke={T.textFaint} strokeWidth="1.4" fill="none"
              strokeDasharray="4 3" strokeLinecap="round" strokeLinejoin="round" opacity="0.7" />
      )}

      {/* Main area + line */}
      <path d={areaPath} fill="url(#areaFill)" />
      <path d={linePath} stroke={accent} strokeWidth="2" fill="none"
            strokeLinecap="round" strokeLinejoin="round" />

      {/* End-of-period dot */}
      <circle cx={pts[pts.length-1][0]} cy={pts[pts.length-1][1]} r="3.5" fill={accent} />
      <circle cx={pts[pts.length-1][0]} cy={pts[pts.length-1][1]} r="6" fill={accent} opacity="0.18" />
    </svg>
  );
}

// ─── Bar chart ─────────────────────────────────────
function BarChart({ series, accent, T, fontMono }) {
  const W = 560, H = 200, padL = 36, padR = 8, padT = 10, padB = 22;
  const innerW = W - padL - padR, innerH = H - padT - padB;
  const max = Math.max(...series) * 1.1;
  const barW = innerW / series.length * 0.7;
  const gap = innerW / series.length * 0.3;

  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 200, display: 'block' }}>
      {/* Grid */}
      {[0, 0.25, 0.5, 0.75, 1].map((p, i) => {
        const y = padT + innerH - p * innerH;
        const v = Math.round(max * p);
        return (
          <g key={i}>
            <line x1={padL} x2={W - padR} y1={y} y2={y} stroke={T.borderSoft} strokeWidth="1" />
            <text x={padL - 6} y={y + 3} textAnchor="end"
              fontFamily={fontMono} fontSize="9" fill={T.textFaint}>
              ${v >= 1000 ? (v/1000).toFixed(0) + 'k' : v}
            </text>
          </g>
        );
      })}

      {series.map((v, i) => {
        const h = (v / max) * innerH;
        const x = padL + i * (barW + gap) + gap/2;
        const y = padT + innerH - h;
        const isWeekend = i % 7 === 6;
        return (
          <g key={i}>
            <rect x={x} y={y} width={barW} height={h}
                  fill={isWeekend ? accent : `${accent}88`}
                  rx="1" />
          </g>
        );
      })}

      {/* X labels */}
      {series.map((_, i) => {
        if (i % 5 !== 0 && i !== series.length - 1) return null;
        const x = padL + i * (barW + gap) + gap/2 + barW/2;
        return <text key={i} x={x} y={H - 6} textAnchor="middle"
          fontFamily={fontMono} fontSize="9" fill={T.textFaint}>D{i+1}</text>;
      })}
    </svg>
  );
}

// ─── Donut (revenue mix) ──────────────────────────
function Donut({ data, T, fontMono }) {
  const total = data.reduce((s, d) => s + d.pct, 0);
  const R = 64, r = 38, cx = 90, cy = 90;
  let acc = -Math.PI / 2;
  const arcs = data.map(d => {
    const angle = (d.pct / total) * Math.PI * 2;
    const a0 = acc, a1 = acc + angle;
    acc = a1;
    const large = angle > Math.PI ? 1 : 0;
    const x0 = cx + R * Math.cos(a0), y0 = cy + R * Math.sin(a0);
    const x1 = cx + R * Math.cos(a1), y1 = cy + R * Math.sin(a1);
    const xi0 = cx + r * Math.cos(a1), yi0 = cy + r * Math.sin(a1);
    const xi1 = cx + r * Math.cos(a0), yi1 = cy + r * Math.sin(a0);
    return { d, path: `M${x0},${y0} A${R},${R} 0 ${large} 1 ${x1},${y1} L${xi0},${yi0} A${r},${r} 0 ${large} 0 ${xi1},${yi1} Z` };
  });

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
      <svg width="180" height="180" viewBox="0 0 180 180">
        {arcs.map((a, i) => (
          <path key={i} d={a.path} fill={a.d.color} stroke={T.surface} strokeWidth="1.5" />
        ))}
        <text x={cx} y={cy - 2} textAnchor="middle" fontFamily="inherit"
              fontSize="20" fontWeight="700" fill={T.text}
              style={{ letterSpacing: '-0.02em' }}>$2.4M</text>
        <text x={cx} y={cy + 14} textAnchor="middle" fontFamily={fontMono}
              fontSize="9.5" fill={T.textFaint}>30 DAY GMV</text>
      </svg>
      <div style={{ flex: 1 }}>
        {data.map((d, i) => (
          <div key={i} style={{
            display: 'flex', alignItems: 'center', gap: 8,
            padding: '5px 0', fontSize: 12,
            borderTop: i ? `1px solid ${T.borderSoft}` : 'none',
          }}>
            <span style={{ width: 8, height: 8, borderRadius: 2, background: d.color, flexShrink: 0 }} />
            <span style={{ flex: 1, color: T.text }}>{d.label}</span>
            <span style={{ fontFamily: fontMono, color: T.textDim, fontSize: 11.5 }}>{d.pct}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Funnel ────────────────────────────────────────
function Funnel({ data, accent, T, fontMono }) {
  return (
    <div>
      {data.map((step, i) => {
        const drop = i > 0 ? Math.round((1 - step.pct / data[i-1].pct) * 100) : 0;
        return (
          <div key={i} style={{ marginBottom: i === data.length - 1 ? 0 : 10 }}>
            <div style={{
              display: 'flex', justifyContent: 'space-between',
              fontSize: 12, marginBottom: 4,
            }}>
              <span style={{ color: T.text, fontWeight: 500 }}>{step.label}</span>
              <span style={{ fontFamily: fontMono, color: T.textDim, fontSize: 11.5 }}>
                {step.n.toLocaleString()} <span style={{ color: T.textFaint }}>({step.pct}%)</span>
              </span>
            </div>
            <div style={{
              height: 8, borderRadius: 2, background: T.chipBg, overflow: 'hidden',
            }}>
              <div style={{
                width: step.pct + '%', height: '100%',
                background: accent, opacity: 0.3 + 0.7 * (step.pct/100),
              }} />
            </div>
            {i > 0 && (
              <div style={{ fontSize: 10, color: T.textFaint, marginTop: 3, fontFamily: fontMono }}>
                ↓ {drop}% drop-off
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

// ─── Heatmap (day × hour) ─────────────────────────
function Heatmap({ data, accent, T, fontMono }) {
  const days = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
  const hours = [9, 11, 13, 15, 17, 19, 21, 23];
  const cellW = 38, cellH = 22, gap = 3;

  return (
    <div>
      <svg viewBox={`0 0 ${28 + hours.length * (cellW + gap)} ${28 + days.length * (cellH + gap)}`}
        style={{ width: '100%', display: 'block' }}>
        {/* Hour labels */}
        {hours.map((h, i) => (
          <text key={i}
            x={28 + i * (cellW + gap) + cellW/2}
            y={14}
            textAnchor="middle"
            fontFamily={fontMono} fontSize="9" fill={T.textFaint}>
            {h > 12 ? `${h-12}p` : `${h}a`}
          </text>
        ))}
        {/* Day rows */}
        {days.map((d, di) => (
          <g key={di}>
            <text x={22} y={28 + di * (cellH + gap) + cellH/2 + 3}
              textAnchor="end" fontFamily={fontMono} fontSize="9" fill={T.textFaint}>{d}</text>
            {hours.map((h, hi) => {
              const cell = data[di * hours.length + hi];
              if (!cell) return null;
              const v = cell.v;
              return (
                <rect key={hi}
                  x={28 + hi * (cellW + gap)}
                  y={28 + di * (cellH + gap)}
                  width={cellW} height={cellH}
                  rx="2"
                  fill={accent} fillOpacity={0.08 + v * 0.85} />
              );
            })}
          </g>
        ))}
      </svg>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'flex-end',
        gap: 8, marginTop: 8, fontSize: 10, color: T.textFaint, fontFamily: fontMono,
      }}>
        <span>Less</span>
        {[0.1, 0.3, 0.5, 0.7, 0.95].map((o, i) => (
          <span key={i} style={{ width: 14, height: 10, borderRadius: 2, background: accent, opacity: o }} />
        ))}
        <span>More</span>
      </div>
    </div>
  );
}

// ─── Sport breakdown ─────────────────────────────
function SportBars({ data, accent, T, fontMono }) {
  const max = Math.max(...data.map(d => d.fans));
  return (
    <div>
      {data.map((s, i) => (
        <div key={s.id} style={{
          display: 'grid', gridTemplateColumns: '70px 1fr 70px',
          alignItems: 'center', gap: 10,
          padding: '7px 0',
          borderTop: i ? `1px solid ${T.borderSoft}` : 'none',
        }}>
          <span style={{ fontSize: 12, color: T.text, fontWeight: 500 }}>{s.label}</span>
          <div style={{ height: 7, borderRadius: 2, background: T.chipBg, overflow: 'hidden' }}>
            <div style={{
              width: (s.fans / max * 100) + '%', height: '100%',
              background: accent, opacity: 0.4 + 0.6 * (s.fans / max),
            }} />
          </div>
          <span style={{ fontFamily: fontMono, fontSize: 11, color: T.textDim, textAlign: 'right' }}>
            {(s.fans / 1000).toFixed(1)}k
          </span>
        </div>
      ))}
    </div>
  );
}

// ─── Sponsor table ─────────────────────────────
function SponsorTable({ data, T, fontMono, accent }) {
  return (
    <div style={{ marginTop: -4 }}>
      <div style={{
        display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr 1fr 1fr',
        padding: '6px 0', fontSize: 10.5, color: T.textFaint,
        fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase',
        borderBottom: `1px solid ${T.border}`,
      }}>
        <div>Brand</div>
        <div>Spend</div>
        <div>CTR</div>
        <div>Redeems</div>
        <div>Status</div>
      </div>
      {data.map((s, i) => (
        <div key={i} style={{
          display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr 1fr 1fr',
          padding: '10px 0', fontSize: 12, color: T.text,
          borderBottom: i === data.length - 1 ? 'none' : `1px solid ${T.borderSoft}`,
          alignItems: 'center',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{
              width: 22, height: 22, borderRadius: 4,
              background: T.chipBg, border: `1px solid ${T.border}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 10, fontWeight: 700, color: T.textDim,
            }}>{s.brand[0]}</span>
            <span style={{ fontWeight: 500 }}>{s.brand}</span>
          </div>
          <div style={{ fontFamily: fontMono, color: T.text }}>${(s.spend/1000).toFixed(0)}k</div>
          <div style={{ fontFamily: fontMono, color: T.textDim }}>{s.ctr}%</div>
          <div style={{ fontFamily: fontMono, color: T.textDim }}>{s.redeems.toLocaleString()}</div>
          <div>
            <span style={{
              display: 'inline-flex', alignItems: 'center', gap: 5,
              fontSize: 10.5, fontWeight: 600,
              padding: '2px 7px', borderRadius: 3,
              background: s.status === 'live' ? 'rgba(34,197,94,0.12)' : T.chipBg,
              color: s.status === 'live' ? '#1A8A4E' : T.textDim,
            }}>
              <span style={{
                width: 5, height: 5, borderRadius: 3,
                background: s.status === 'live' ? '#22C55E' : T.textFaint,
              }} />
              {s.status === 'live' ? 'Live' : 'Paused'}
            </span>
          </div>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { AnalyticsWorkspace });
