/* WPSiteBeam — SA AI Usage dashboard
   v1.0.0 — May 14 2026 (Phase 3 of AI usage ledger)

   Consumes GET /sa/ai-usage/burndown from Railway. Read-only view over
   ai_usage_ledger rows: window summary, monthly Anthropic cap status,
   daily burndown, breakdowns by module / provider+model / account, and
   the most recent N rows raw.

   Gated to super_admin / dev_admin / internal_partner / admin via
   Shell.jsx NAV_SA + App.jsx allowed-pages.
*/
(function () {
  'use strict';

  const { useState, useEffect, useCallback } = React;
  const RAILWAY = (window.WPSB && window.WPSB.RAILWAY) || 'https://wpsitebeam-railway-api-production.up.railway.app';

  // ── helpers ─────────────────────────────────────────────────────
  function fmtUSD(n) {
    if (n == null || isNaN(n)) return '\u2014';
    if (n === 0) return '$0.00';
    if (n < 0.01)  return '$' + n.toFixed(6);
    if (n < 1)     return '$' + n.toFixed(4);
    if (n < 100)   return '$' + n.toFixed(2);
    return '$' + Math.round(n).toLocaleString();
  }
  function fmtInt(n) {
    if (n == null || isNaN(n)) return '\u2014';
    return Number(n).toLocaleString();
  }
  function fmtPct(p) {
    if (p == null || isNaN(p)) return '\u2014';
    return (p * 100).toFixed(1) + '%';
  }
  function fmtDate(iso) {
    if (!iso) return '\u2014';
    try {
      const d = new Date(iso);
      const diff = (Date.now() - d) / 1000;
      if (diff < 60)     return 'just now';
      if (diff < 3600)   return Math.floor(diff / 60) + ' min ago';
      if (diff < 86400)  return Math.floor(diff / 3600) + ' hr ago';
      if (diff < 604800) return Math.floor(diff / 86400) + 'd ago';
      return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
    } catch (e) { return iso; }
  }
  function shortDay(iso) {
    if (!iso) return '';
    try { return iso.slice(5, 10); } catch (e) { return iso; }
  }
  function shortId(s) {
    if (!s) return '';
    const str = String(s);
    return str.length > 14 ? str.slice(0, 8) + '\u2026' : str;
  }

  // ── KPI card ────────────────────────────────────────────────────
  function KPI({ label, value, sub, accent }) {
    return (
      <div style={{
        background: 'var(--panel)', border: '1px solid var(--border)',
        borderRadius: 8, padding: '14px 16px', minWidth: 0,
      }}>
        <div style={{ fontSize: '.7rem', color: 'var(--dim)', textTransform: 'uppercase', letterSpacing: '.05em', fontWeight: 600 }}>{label}</div>
        <div style={{ marginTop: 6, fontSize: '1.5rem', fontWeight: 700, color: accent || 'var(--text)', fontFamily: 'var(--font-mono, monospace)' }}>{value}</div>
        {sub != null && <div style={{ marginTop: 2, fontSize: '.72rem', color: 'var(--dim)' }}>{sub}</div>}
      </div>
    );
  }

  // ── Monthly cap meter ───────────────────────────────────────────
  function CapMeter({ spend, cap, pct }) {
    // pct from API is whole-number percent (e.g. 12.3); fall back to local compute
    const computed = (cap > 0 && spend != null) ? (spend / cap) * 100 : 0;
    const p = (pct != null && !isNaN(pct)) ? pct : computed;
    const clamped = Math.max(0, Math.min(p, 100));
    const overflow = p > 100;
    const tone =
      p >= 100 ? 'var(--red)' :
      p >=  85 ? 'var(--warn)' :
      p >=  60 ? 'var(--orange)' :
      'var(--beam)';
    const toneBg =
      p >= 100 ? 'var(--red-dim)' :
      p >=  85 ? 'var(--warn-dim)' :
      p >=  60 ? 'var(--orange-dim)' :
      'var(--beam-dim)';
    return (
      <div style={{
        background: 'var(--panel)', border: '1px solid var(--border)',
        borderRadius: 8, padding: '14px 18px',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
          <div style={{ fontSize: '.78rem', color: 'var(--dim)', textTransform: 'uppercase', letterSpacing: '.05em', fontWeight: 600 }}>Month-to-date Anthropic spend</div>
          <div style={{ fontSize: '.72rem', color: 'var(--dim)' }}>cap {fmtUSD(cap)} / mo</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 10 }}>
          <div style={{ fontSize: '1.7rem', fontWeight: 700, color: tone, fontFamily: 'var(--font-mono, monospace)' }}>{fmtUSD(spend)}</div>
          <div style={{ fontSize: '.85rem', color: 'var(--dim)' }}>{p.toFixed(1)}% of cap</div>
          {overflow && (
            <div style={{ marginLeft: 'auto', fontSize: '.7rem', color: 'var(--red)', fontWeight: 700, textTransform: 'uppercase' }}>over cap</div>
          )}
        </div>
        <div style={{ position: 'relative', height: 10, background: toneBg, borderRadius: 5, overflow: 'hidden' }}>
          <div style={{ position: 'absolute', inset: 0, width: clamped + '%', background: tone, transition: 'width .3s' }}/>
        </div>
      </div>
    );
  }

  // ── Simple SVG bar chart for by_day ─────────────────────────────
  function DailyBars({ data }) {
    if (!data || data.length === 0) return null;
    const vb = { w: 760, h: 200, padL: 56, padR: 12, padT: 14, padB: 30 };
    const cw = vb.w - vb.padL - vb.padR;
    const ch = vb.h - vb.padT - vb.padB;
    const max = Math.max(0.0001, ...data.map(d => d.cost_usd || 0));
    const gap = 6;
    const bw = (cw - gap * (data.length - 1)) / data.length;
    const ticks = 4;
    const tickVals = Array.from({ length: ticks + 1 }, (_, i) => (max * i / ticks));
    return (
      <svg viewBox={`0 0 ${vb.w} ${vb.h}`} style={{ width: '100%', height: 200, display: 'block' }}>
        {tickVals.map((v, i) => {
          const y = vb.padT + ch - (v / max) * ch;
          return (
            <g key={i}>
              <line x1={vb.padL} x2={vb.padL + cw} y1={y} y2={y} stroke="var(--border)" strokeDasharray="2 3"/>
              <text x={vb.padL - 6} y={y + 3} textAnchor="end" fontSize="9" fill="var(--dim)" fontFamily="var(--font-mono, monospace)">{fmtUSD(v)}</text>
            </g>
          );
        })}
        {data.map((d, i) => {
          const x = vb.padL + i * (bw + gap);
          const h = max > 0 ? Math.max(1, (d.cost_usd / max) * ch) : 1;
          const y = vb.padT + ch - h;
          const isEmpty = (d.cost_usd || 0) === 0 && (d.calls || 0) === 0;
          return (
            <g key={i}>
              <rect x={x} y={y} width={bw} height={h} fill={isEmpty ? 'var(--border)' : 'var(--beam)'} rx="2" opacity={isEmpty ? 0.4 : 1}/>
              {!isEmpty && <text x={x + bw / 2} y={y - 4} textAnchor="middle" fontSize="9" fill="var(--text)" fontWeight="600">{fmtInt(d.calls)}</text>}
              <text x={x + bw / 2} y={vb.padT + ch + 14} textAnchor="middle" fontSize="9" fill="var(--dim)">{shortDay(d.day)}</text>
            </g>
          );
        })}
      </svg>
    );
  }

  // ── Cost bar row (horizontal) — for breakdowns ──────────────────
  function CostBar({ label, sub, calls, cost, max, accent }) {
    const w = max > 0 ? Math.max(2, (cost / max) * 100) : 0;
    return (
      <div style={{
        display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 70px 90px', gap: 10,
        alignItems: 'center', padding: '8px 0', borderBottom: '1px solid var(--border)',
        fontSize: '.78rem',
      }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ color: 'var(--text)', fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{label}</div>
          {sub && <div style={{ fontSize: '.68rem', color: 'var(--dim)', marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{sub}</div>}
          <div style={{ position: 'relative', height: 4, background: 'var(--border)', borderRadius: 2, marginTop: 6, overflow: 'hidden' }}>
            <div style={{ position: 'absolute', inset: 0, width: w + '%', background: accent || 'var(--beam)' }}/>
          </div>
        </div>
        <div style={{ color: 'var(--dim)', fontFamily: 'var(--font-mono, monospace)', textAlign: 'right' }}>{fmtInt(calls)}</div>
        <div style={{ color: 'var(--text)', fontFamily: 'var(--font-mono, monospace)', textAlign: 'right', fontWeight: 600 }}>{fmtUSD(cost)}</div>
      </div>
    );
  }

  // ── Status pill ─────────────────────────────────────────────────
  function StatusPill({ status }) {
    const style =
      status === 'success'         ? { bg: 'var(--green-dim)', fg: 'var(--green)' } :
      status === 'error'           ? { bg: 'var(--red-dim)',   fg: 'var(--red)'   } :
      status === 'short_circuited' ? { bg: 'var(--warn-dim)',  fg: 'var(--warn)'  } :
                                     { bg: 'var(--border)',    fg: 'var(--dim)'   };
    return (
      <span style={{
        display: 'inline-block', padding: '2px 8px', borderRadius: 10, fontSize: '.66rem',
        fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.04em',
        background: style.bg, color: style.fg, whiteSpace: 'nowrap',
      }}>{status}</span>
    );
  }

  // ── Main component ──────────────────────────────────────────────
  function AIUsage() {
    const [days, setDays] = useState(7);
    const [recent, setRecent] = useState(25);
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [lastFetched, setLastFetched] = useState(null);

    const load = useCallback(async () => {
      setLoading(true);
      setError(null);
      try {
        const token = (window.WPSB && window.WPSB.getToken && window.WPSB.getToken()) || localStorage.getItem('wpsb-auth-token');
        if (!token) throw new Error('Not authenticated');
        const url = RAILWAY + '/sa/ai-usage/burndown?days=' + days + '&recent=' + recent;
        const r = await fetch(url, { headers: { 'Authorization': 'Bearer ' + token } });
        if (!r.ok) {
          const body = await r.text().catch(() => '');
          throw new Error('HTTP ' + r.status + (body ? ' \u2014 ' + body.slice(0, 140) : ''));
        }
        const json = await r.json();
        if (!json.ok) throw new Error(json.error || 'Unknown error');
        setData(json);
        setLastFetched(new Date());
      } catch (e) {
        setError(e.message || String(e));
        setData(null);
      } finally {
        setLoading(false);
      }
    }, [days, recent]);

    useEffect(() => { load(); }, [load]);

    // Derived: max values for proportional bars
    const maxByModule       = data ? Math.max(0.0001, ...data.by_module.map(r => r.cost_usd || 0)) : 1;
    const maxByProviderModel= data ? Math.max(0.0001, ...data.by_provider_model.map(r => r.cost_usd || 0)) : 1;
    const maxByAccount      = data ? Math.max(0.0001, ...data.by_account.map(r => r.cost_usd || 0)) : 1;

    const hasErrors = data && data.error_reasons && data.error_reasons.length > 0;

    /* Width fix 2026-05-18 — removed `padding:24, maxWidth:1280, margin:'0 auto'`
       to match Brand Profile / Account / Billing standard width.
       The .main grid container in shell.css handles overall width + padding. */
    return (
      <div>
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 6, flexWrap: 'wrap', gap: 12 }}>
          <div>
            <h1 style={{ margin: 0, fontSize: '1.5rem', fontWeight: 700, color: 'var(--text)' }}>AI Usage</h1>
            <div style={{ marginTop: 4, fontSize: '.82rem', color: 'var(--dim)' }}>
              Burndown across Anthropic + Voyage calls.
              {lastFetched && <span> Last fetched {fmtDate(lastFetched.toISOString())}.</span>}
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <label style={{ fontSize: '.78rem', color: 'var(--dim)' }}>Window</label>
            <select value={days} onChange={e => setDays(parseInt(e.target.value, 10))}
              style={{ padding: '6px 10px', background: 'var(--panel)', color: 'var(--text)', border: '1px solid var(--border)', borderRadius: 6, fontSize: '.82rem' }}>
              <option value={1}>1 day</option>
              <option value={7}>7 days</option>
              <option value={14}>14 days</option>
              <option value={30}>30 days</option>
              <option value={60}>60 days</option>
              <option value={90}>90 days</option>
            </select>
            <label style={{ fontSize: '.78rem', color: 'var(--dim)', marginLeft: 6 }}>Recent</label>
            <select value={recent} onChange={e => setRecent(parseInt(e.target.value, 10))}
              style={{ padding: '6px 10px', background: 'var(--panel)', color: 'var(--text)', border: '1px solid var(--border)', borderRadius: 6, fontSize: '.82rem' }}>
              <option value={10}>10</option>
              <option value={25}>25</option>
              <option value={50}>50</option>
              <option value={100}>100</option>
              <option value={200}>200</option>
            </select>
            <button onClick={load} disabled={loading}
              style={{ padding: '6px 14px', background: 'var(--beam)', color: '#001018', border: 'none', borderRadius: 6, fontSize: '.82rem', fontWeight: 600, cursor: loading ? 'wait' : 'pointer', opacity: loading ? 0.6 : 1 }}>
              {loading ? 'Loading\u2026' : 'Refresh'}
            </button>
          </div>
        </div>

        {/* Error banner */}
        {error && (
          <div style={{
            padding: 14, marginTop: 16, background: 'var(--red-dim)', color: 'var(--red)',
            border: '1px solid var(--red)', borderRadius: 8, fontSize: '.85rem',
          }}>
            <strong>Could not load burndown:</strong> {error}
            <div style={{ marginTop: 6, fontSize: '.74rem', color: 'var(--dim)' }}>
              If this is right after a fresh deploy, the <code>ai_usage_ledger</code> table may be empty — that's expected and would return 200 with zero rows. If you're seeing this banner, it's an auth or endpoint error, not empty data.
            </div>
          </div>
        )}

        {/* Loading placeholder */}
        {loading && !data && !error && (
          <div style={{ padding: 60, textAlign: 'center', color: 'var(--dim)', fontSize: '.85rem' }}>Loading…</div>
        )}

        {data && (
          <>
            {/* KPI row */}
            <div style={{
              display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(170px, 1fr))',
              gap: 12, marginTop: 18,
            }}>
              <KPI label="Calls" value={fmtInt(data.summary.total_calls)}
                sub={`${data.summary.success_calls} ok \u00b7 ${data.summary.error_calls} err`} />
              <KPI label="Total cost" value={fmtUSD(data.summary.total_cost_usd)}
                sub={`${fmtInt(data.summary.total_tokens)} tokens`}
                accent={data.summary.total_cost_usd > 10 ? 'var(--warn)' : 'var(--text)'} />
              <KPI label="Success rate" value={data.summary.success_rate == null ? '\u2014' : fmtPct(data.summary.success_rate)}
                sub={`${data.summary.short_circuited} short-circuit`}
                accent={data.summary.success_rate != null && data.summary.success_rate < 0.9 ? 'var(--warn)' : 'var(--green)'} />
              <KPI label="Unique accounts" value={fmtInt(data.summary.unique_accounts)}
                sub={`${data.summary.unique_users} unique users`} />
            </div>

            {/* Monthly cap meter */}
            <div style={{ marginTop: 16 }}>
              <CapMeter
                spend={data.month_to_date.anthropic_spend_usd}
                cap={data.month_to_date.anthropic_cap_usd}
                pct={data.month_to_date.anthropic_cap_pct}
              />
            </div>

            {/* Daily burndown chart */}
            <div style={{
              marginTop: 16, padding: '16px 18px',
              background: 'var(--panel)', border: '1px solid var(--border)', borderRadius: 8,
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
                <div style={{ fontSize: '.78rem', color: 'var(--dim)', textTransform: 'uppercase', letterSpacing: '.05em', fontWeight: 600 }}>Daily burndown ({days}d)</div>
                <div style={{ fontSize: '.72rem', color: 'var(--dim)' }}>cost bars; call count above bar</div>
              </div>
              <DailyBars data={data.by_day} />
            </div>

            {/* 3-column breakdowns */}
            <div style={{
              display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))',
              gap: 12, marginTop: 16,
            }}>
              {/* By module */}
              <div style={{ background: 'var(--panel)', border: '1px solid var(--border)', borderRadius: 8, padding: '14px 16px' }}>
                <div style={{ fontSize: '.78rem', color: 'var(--dim)', textTransform: 'uppercase', letterSpacing: '.05em', fontWeight: 600, marginBottom: 8 }}>By module</div>
                {data.by_module.length === 0 ? (
                  <div style={{ padding: 20, textAlign: 'center', color: 'var(--dim)', fontSize: '.82rem' }}>No calls in window.</div>
                ) : (
                  <>
                    <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 70px 90px', gap: 10, fontSize: '.66rem', color: 'var(--dim)', textTransform: 'uppercase', letterSpacing: '.04em', fontWeight: 600, paddingBottom: 6, borderBottom: '1px solid var(--border)' }}>
                      <div>Module</div>
                      <div style={{ textAlign: 'right' }}>Calls</div>
                      <div style={{ textAlign: 'right' }}>Cost</div>
                    </div>
                    {data.by_module.map(r => (
                      <CostBar key={r.module}
                        label={r.module}
                        sub={fmtInt(r.tokens) + ' tokens'}
                        calls={r.calls} cost={r.cost_usd} max={maxByModule}
                        accent="var(--orange)" />
                    ))}
                  </>
                )}
              </div>

              {/* By provider+model */}
              <div style={{ background: 'var(--panel)', border: '1px solid var(--border)', borderRadius: 8, padding: '14px 16px' }}>
                <div style={{ fontSize: '.78rem', color: 'var(--dim)', textTransform: 'uppercase', letterSpacing: '.05em', fontWeight: 600, marginBottom: 8 }}>By provider · model</div>
                {data.by_provider_model.length === 0 ? (
                  <div style={{ padding: 20, textAlign: 'center', color: 'var(--dim)', fontSize: '.82rem' }}>No calls in window.</div>
                ) : (
                  <>
                    <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 70px 90px', gap: 10, fontSize: '.66rem', color: 'var(--dim)', textTransform: 'uppercase', letterSpacing: '.04em', fontWeight: 600, paddingBottom: 6, borderBottom: '1px solid var(--border)' }}>
                      <div>Provider / model</div>
                      <div style={{ textAlign: 'right' }}>Calls</div>
                      <div style={{ textAlign: 'right' }}>Cost</div>
                    </div>
                    {data.by_provider_model.map(r => {
                      const accent = r.provider === 'anthropic' ? 'var(--beam)' : r.provider === 'voyage' ? 'var(--purple)' : 'var(--orange)';
                      return (
                        <CostBar key={r.provider + '|' + r.model}
                          label={r.model}
                          sub={r.provider + ' \u00b7 ' + fmtInt(r.in_tokens) + ' in \u00b7 ' + fmtInt(r.out_tokens) + ' out'}
                          calls={r.calls} cost={r.cost_usd} max={maxByProviderModel}
                          accent={accent} />
                      );
                    })}
                  </>
                )}
              </div>

              {/* By account */}
              <div style={{ background: 'var(--panel)', border: '1px solid var(--border)', borderRadius: 8, padding: '14px 16px' }}>
                <div style={{ fontSize: '.78rem', color: 'var(--dim)', textTransform: 'uppercase', letterSpacing: '.05em', fontWeight: 600, marginBottom: 8 }}>By account</div>
                {data.by_account.length === 0 ? (
                  <div style={{ padding: 20, textAlign: 'center', color: 'var(--dim)', fontSize: '.82rem' }}>No account-attributed calls yet. Internal calls are excluded from this view.</div>
                ) : (
                  <>
                    <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 70px 90px', gap: 10, fontSize: '.66rem', color: 'var(--dim)', textTransform: 'uppercase', letterSpacing: '.04em', fontWeight: 600, paddingBottom: 6, borderBottom: '1px solid var(--border)' }}>
                      <div>Account</div>
                      <div style={{ textAlign: 'right' }}>Calls</div>
                      <div style={{ textAlign: 'right' }}>Cost</div>
                    </div>
                    {data.by_account.slice(0, 12).map(r => (
                      <CostBar key={r.account_id}
                        label={r.account_name || shortId(r.account_id)}
                        sub={(r.account_plan || 'unknown plan') + ' \u00b7 ' + shortId(r.account_id)}
                        calls={r.calls} cost={r.cost_usd} max={maxByAccount}
                        accent="var(--green)" />
                    ))}
                  </>
                )}
              </div>
            </div>

            {/* Error reasons (collapsed unless errors present) */}
            {hasErrors && (
              <div style={{
                marginTop: 16, padding: '14px 16px',
                background: 'var(--red-dim)', border: '1px solid var(--red)', borderRadius: 8,
              }}>
                <div style={{ fontSize: '.78rem', color: 'var(--red)', textTransform: 'uppercase', letterSpacing: '.05em', fontWeight: 700, marginBottom: 8 }}>Error reasons in window</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                  {data.error_reasons.map(e => (
                    <div key={e.error_code} style={{
                      padding: '4px 10px', background: 'var(--panel)', border: '1px solid var(--red)',
                      borderRadius: 12, fontSize: '.74rem', color: 'var(--text)',
                    }}>
                      <code style={{ fontFamily: 'var(--font-mono, monospace)', color: 'var(--red)' }}>{e.error_code}</code>
                      <span style={{ marginLeft: 6, color: 'var(--dim)' }}>× {fmtInt(e.count)}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Recent rows */}
            <div style={{
              marginTop: 16, background: 'var(--panel)', border: '1px solid var(--border)',
              borderRadius: 8, overflow: 'hidden',
            }}>
              <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--border)' }}>
                <div style={{ fontSize: '.78rem', color: 'var(--dim)', textTransform: 'uppercase', letterSpacing: '.05em', fontWeight: 600 }}>Recent calls ({data.recent.length} of last {recent})</div>
              </div>
              {data.recent.length === 0 ? (
                <div style={{ padding: 36, textAlign: 'center', color: 'var(--dim)', fontSize: '.85rem' }}>
                  No ledger rows in this window yet. Trigger a /brain/chat or /brain/scan to populate.
                </div>
              ) : (
                <div style={{ overflowX: 'auto' }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '.78rem' }}>
                    <thead>
                      <tr style={{ background: 'rgba(255,255,255,0.02)', borderBottom: '1px solid var(--border)' }}>
                        {['When', 'Module', 'Provider \u00b7 Model', 'Tokens in/out', 'Cost', 'Status', 'Actor', 'Account', 'Context'].map(h => (
                          <th key={h} style={{ padding: '8px 10px', textAlign: 'left', fontWeight: 600, color: 'var(--dim)', fontSize: '.7rem', textTransform: 'uppercase', letterSpacing: '.04em', whiteSpace: 'nowrap' }}>{h}</th>
                        ))}
                      </tr>
                    </thead>
                    <tbody>
                      {data.recent.map(r => (
                        <tr key={r.id} style={{ borderBottom: '1px solid var(--border)' }}>
                          <td style={{ padding: '6px 10px', color: 'var(--dim)', whiteSpace: 'nowrap' }} title={r.created_at}>{fmtDate(r.created_at)}</td>
                          <td style={{ padding: '6px 10px', color: 'var(--text)', fontFamily: 'var(--font-mono, monospace)' }}>{r.module}</td>
                          <td style={{ padding: '6px 10px', color: 'var(--text)' }}>
                            <span style={{ color: 'var(--dim)' }}>{r.provider}</span>
                            <span style={{ marginLeft: 6, fontFamily: 'var(--font-mono, monospace)', fontSize: '.74rem' }}>{r.model}</span>
                          </td>
                          <td style={{ padding: '6px 10px', color: 'var(--text)', fontFamily: 'var(--font-mono, monospace)', whiteSpace: 'nowrap' }}>
                            {fmtInt(r.input_tokens)} / {fmtInt(r.output_tokens)}
                          </td>
                          <td style={{ padding: '6px 10px', color: 'var(--text)', fontFamily: 'var(--font-mono, monospace)', fontWeight: 600 }}>{fmtUSD(r.cost_usd)}</td>
                          <td style={{ padding: '6px 10px' }}><StatusPill status={r.status} /></td>
                          <td style={{ padding: '6px 10px', color: 'var(--dim)' }}>{r.actor_type}</td>
                          <td style={{ padding: '6px 10px', color: 'var(--text)' }} title={r.account_id || ''}>{r.account_name || (r.account_id ? shortId(r.account_id) : '\u2014')}</td>
                          <td style={{ padding: '6px 10px', color: 'var(--dim)', fontSize: '.72rem' }} title={r.context_id || ''}>
                            {r.context_type ? r.context_type + (r.context_id ? ' \u00b7 ' + shortId(r.context_id) : '') : '\u2014'}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>

            {/* Footer: window meta + pricing dict reference */}
            <div style={{
              marginTop: 18, padding: '10px 14px',
              background: 'var(--panel)', border: '1px dashed var(--border)', borderRadius: 8,
              fontSize: '.72rem', color: 'var(--dim)',
            }}>
              <div>Window: <code style={{ fontFamily: 'var(--font-mono, monospace)' }}>{data.window.start}</code> → <code style={{ fontFamily: 'var(--font-mono, monospace)' }}>{data.window.end}</code> ({data.window.days}d)</div>
              <div style={{ marginTop: 4 }}>
                Rates loaded from <code style={{ fontFamily: 'var(--font-mono, monospace)' }}>AI_PRICING</code> dict in server.js. When Anthropic or Voyage reprice, update that dict and redeploy — schema stays the same.
              </div>
            </div>
          </>
        )}
      </div>
    );
  }

  window.AIUsage = AIUsage;
  console.log('[WPSB] AIUsage v1.0.0 loaded (SA AI Usage dashboard \u2014 consumes /sa/ai-usage/burndown)');
})();
