// Reports — comprehensive financial reports view
// Renders multiple report sections: P&L, Cash flow, Balance sheet, Revenue,
// Burn/runway, Treasury, FX, Crypto, Customers, Cohorts, Tax
// Exposes window.ReportsView

(function() {
  const { useState, useMemo, useEffect, useRef } = React;
  const C = window.Charts;
  const F = C.fmt;

  const PERIODS = ['MTD', 'QTD', 'YTD', 'TTM', '2025', '2024'];

  const SECTIONS = [
    { id: 'overview',   label: 'Overview' },
    { id: 'pnl',        label: 'P&L' },
    { id: 'cashflow',   label: 'Cash Flow' },
    { id: 'balance',    label: 'Balance Sheet' },
    { id: 'revenue',    label: 'Revenue' },
    { id: 'burn',       label: 'Burn / Runway' },
    { id: 'treasury',   label: 'Treasury' },
    { id: 'fx',         label: 'FX' },
    { id: 'crypto',     label: 'Crypto' },
    { id: 'customers',  label: 'Customers' },
    { id: 'cohorts',    label: 'Cohorts' },
    { id: 'ar_ap',      label: 'AR / AP' },
    { id: 'tax',        label: 'Tax' },
    { id: 'audit',      label: 'Audit' },
  ];

  // ---------- seed data (monthly, 12mo) ----------
  const months = ['May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr'];
  const revenue    = [142, 138, 151, 162, 158, 174, 181, 192, 198, 210, 228, 241.88];
  const cogs       = [ 32,  30,  33,  36,  35,  38,  40,  41,  43,  47,  50,  52.4];
  const opex       = [ 86,  82,  91,  97,  96, 104, 108, 114, 117, 121, 126, 129.1];
  const net        = revenue.map((r,i) => r - cogs[i] - opex[i]);
  const cashIn     = revenue.map(v => v + (Math.sin(v)*3));
  const cashOut    = cogs.map((c,i) => c + opex[i] + [2,3,5,4,6,8,4,7,5,6,5,6][i]);
  const cashBal    = (() => { let c = 142; return cashIn.map((ci,i) => (c += ci - cashOut[i])); })();
  const mrr        = [118, 122, 129, 138, 142, 149, 156, 163, 170, 178, 189, 198.4];
  const arr        = mrr.map(v => v * 12);
  const customers  = [ 84,  89,  96, 102, 108, 118, 127, 134, 142, 151, 163, 178];
  const newCust    = [  7,   8,  10,   9,  11,  14,  12,  11,  13,  14,  16,  19];
  const churned    = [  3,   3,   3,   3,   5,   4,   3,   4,   5,   5,   4,   4];
  const burnRate   = cashOut.map((v,i) => Math.max(0, v - cashIn[i]));
  const headcount  = [ 11,  12,  12,  13,  14,  14,  15,  16,  16,  17,  18,  18];

  // ---------- formatters ----------
  const $k = (n) => (n < 0 ? '−' : '') + '$' + Math.abs(n).toFixed(1) + 'k';
  const $ = (n) => (n < 0 ? '−' : '') + '$' + Math.abs(n).toLocaleString('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
  const pct = (n, d=1) => (n >= 0 ? '+' : '') + n.toFixed(d) + '%';
  const accent = 'var(--accent)';
  const catColors = {
    payroll: 'var(--cat-amber)', infra: 'var(--cat-cyan)', saas: 'var(--cat-violet)',
    contract: 'var(--cat-teal)', travel: 'var(--cat-magenta)', meals: 'var(--cat-red)',
    tax: 'var(--cat-blue)', fees: 'var(--fg-3)', revenue: 'var(--cat-lime)',
  };

  // ---------- KPIs ----------
  function KPI({ label, value, delta, deltaClass, spark, sparkColor }) {
    return (
      <div className="kpi">
        <div className="label">{label}</div>
        <div className="value">{value}</div>
        {delta != null && <div className="delta" style={{ color: deltaClass === 'pos' ? 'var(--pos)' : deltaClass === 'neg' ? 'var(--neg)' : 'var(--fg-2)' }}>{delta}</div>}
        {spark && <div className="spark-line"><C.Spark data={spark} w={120} h={28} color={sparkColor || accent} /></div>}
      </div>
    );
  }

  // ---------- Overview ----------
  function Overview() {
    return (
      <>
        <div className="kpi-grid">
          <KPI label="Revenue · TTM" value="$2.18M" delta="+34.2% YoY" deltaClass="pos" spark={revenue} sparkColor="var(--cat-lime)" />
          <KPI label="Net Income · TTM" value="$724k" delta="+52.1% YoY" deltaClass="pos" spark={net} sparkColor="var(--accent)" />
          <KPI label="Cash · EoP" value="$284k" delta="+$12.8k · 30d" deltaClass="pos" spark={cashBal} sparkColor="var(--cat-cyan)" />
          <KPI label="Runway" value="18.4 mo" delta="+0.6 mo" deltaClass="pos" spark={[14,14,15,15,15,16,16,17,17,17,18,18.4]} sparkColor="var(--cat-amber)" />
        </div>
        <div className="kpi-grid">
          <KPI label="MRR" value="$198.4k" delta="+5.0% MoM" deltaClass="pos" spark={mrr} sparkColor="var(--cat-violet)" />
          <KPI label="Burn (net)" value="$94.2k/mo" delta="−3.1% MoM" deltaClass="pos" spark={burnRate.slice().reverse()} sparkColor="var(--neg)" />
          <KPI label="Gross Margin" value="78.4%" delta="+1.2pp" deltaClass="pos" spark={revenue.map((r,i)=>((r-cogs[i])/r)*100)} sparkColor="var(--cat-lime)" />
          <KPI label="Customers" value="178" delta="+19 new / −4 churn" deltaClass="pos" spark={customers} sparkColor="var(--cat-teal)" />
        </div>

        <Section id="overview-charts" title="The year in three charts" note="TTM · all accounts · USD">
          <div className="report-grid-3">
            <Card title="Revenue vs. Expenses" right="monthly · $k">
              <C.LineChart
                series={[
                  { name: 'revenue',  data: revenue, color: 'var(--cat-lime)', width: 1.8 },
                  { name: 'expenses', data: revenue.map((_,i) => cogs[i]+opex[i]), color: 'var(--neg)', width: 1.4 },
                  { name: 'net',      data: net, color: accent, width: 1.8, dots: true },
                ]}
                w={540} h={240} labels={months} area={false} yFmt={F.k}
              />
            </Card>
            <Card title="Cash position" right="EoM · $k">
              <C.LineChart
                series={[{ name: 'cash', data: cashBal, color: 'var(--cat-cyan)', width: 1.8 }]}
                w={540} h={240} labels={months} area yFmt={F.k}
              />
            </Card>
            <Card title="Expense mix" right="TTM">
              <C.Donut
                slices={[
                  { label: 'payroll',   value: 720, color: catColors.payroll },
                  { label: 'infra',     value: 286, color: catColors.infra },
                  { label: 'saas',      value: 102, color: catColors.saas },
                  { label: 'contract',  value: 148, color: catColors.contract },
                  { label: 'travel',    value:  62, color: catColors.travel },
                  { label: 'tax',       value: 212, color: catColors.tax },
                  { label: 'fees',      value:  14, color: catColors.fees },
                ]}
                w={260} h={240} center={{ label: 'total opex', value: '$1.54M' }}
              />
            </Card>
          </div>
        </Section>
      </>
    );
  }

  // ---------- Section + Card helpers ----------
  function Section({ id, title, note, children }) {
    return (
      <section id={id} className="report-section">
        <div className="report-section-head">
          <div className="title">{title}</div>
          {note && <div className="note">{note}</div>}
        </div>
        {children}
      </section>
    );
  }
  function Card({ title, right, children, flush }) {
    return (
      <div className="report-card">
        <div className="report-card-head">
          <span>{title}</span>
          {right && <span className="right">{right}</span>}
        </div>
        <div className={'report-card-body' + (flush ? ' flush' : '')}>{children}</div>
      </div>
    );
  }

  // ---------- P&L ----------
  function PnL() {
    const row = (label, vals, opts={}) => ({ label, vals, ...opts });
    const totalRev = 241.88;
    const rows = [
      row('Revenue', null, { head: true }),
      row('Subscription — MRR', [198.4, 189.0, 170.2]),
      row('Subscription — Annual', [32.4, 28.1, 20.0]),
      row('Services', [8.0, 6.4, 5.1]),
      row('Other', [3.08, 2.1, 1.2]),
      row('Total Revenue', [totalRev, 225.6, 196.5], { total: true }),
      row('Cost of Revenue', null, { head: true }),
      row('Hosting & infra', [42.8, 40.2, 34.1]),
      row('3rd-party APIs (OpenAI, etc)', [6.2, 5.8, 4.4]),
      row('Processing fees (Stripe)', [3.4, 3.1, 2.7]),
      row('Total COGS', [52.4, 49.1, 41.2], { total: true }),
      row('Gross Profit', [189.48, 176.5, 155.3], { total: true }),
      row('Operating Expenses', null, { head: true }),
      row('Payroll & benefits', [72.4, 68.8, 58.2]),
      row('Contractors', [12.6, 10.4, 8.8]),
      row('SaaS & tooling', [8.5, 8.2, 7.1]),
      row('Cloud infra (non-COGS)', [5.1, 4.8, 4.0]),
      row('Travel & entertainment', [3.1, 2.8, 2.4]),
      row('Legal & professional', [4.2, 1.1, 1.8]),
      row('Rent & utilities', [1.5, 1.5, 1.4]),
      row('Marketing', [14.8, 12.1, 9.2]),
      row('Other', [6.9, 5.4, 4.2]),
      row('Total OpEx', [129.1, 115.1, 97.1], { total: true }),
      row('Operating Income', [60.38, 61.4, 58.2], { total: true }),
      row('Other income / (expense)', null, { head: true }),
      row('Interest income', [1.2, 1.1, 0.9]),
      row('FX gain / (loss)', [-0.4, 0.2, -0.1]),
      row('Total Other', [0.8, 1.3, 0.8], { total: true }),
      row('Net Income', [61.18, 62.7, 59.0], { grand: true }),
    ];

    return (
      <Section id="pnl" title="Profit & Loss" note="April 2026 · vs. prior month · vs. 6-mo avg">
        <div className="report-grid-2">
          <Card title="Statement" right="amounts in $k">
            <table className="pnl-table">
              <thead>
                <tr><th>Line item</th><th>Apr 26</th><th>Mar 26</th><th>6mo avg</th><th>Δ m/m</th></tr>
              </thead>
              <tbody>
                {rows.map((r, i) => {
                  if (r.head) return <tr key={i} className="section-head"><td colSpan={5}>{r.label}</td></tr>;
                  const cls = r.grand ? 'grand' : r.total ? 'total' : 'sub';
                  const v = r.vals;
                  const chg = v[1] ? ((v[0]-v[1])/Math.abs(v[1]))*100 : 0;
                  return (
                    <tr key={i} className={cls}>
                      <td>{r.label}</td>
                      <td className="num">{v[0].toFixed(1)}</td>
                      <td className="num" style={{ color: 'var(--fg-2)' }}>{v[1].toFixed(1)}</td>
                      <td className="num" style={{ color: 'var(--fg-2)' }}>{v[2].toFixed(1)}</td>
                      <td className="chg" style={{ color: chg >= 0 ? 'var(--pos)' : 'var(--neg)' }}>{pct(chg, 1)}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </Card>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <Card title="Revenue vs. expenses" right="trailing 12 mo · $k">
              <C.StackedBars
                groups={months.map((m, i) => ({ m, COGS: cogs[i], OpEx: opex[i], Net: Math.max(0, net[i]) }))}
                keys={['COGS', 'OpEx', 'Net']}
                colors={['var(--neg)', catColors.payroll, 'var(--pos)']}
                w={420} h={240} labels={months} yFmt={v => v+'k'}
              />
            </Card>
            <Card title="Margins" right="trailing 12 mo">
              <C.LineChart
                series={[
                  { name: 'gross', data: revenue.map((r,i)=>((r-cogs[i])/r)*100), color: 'var(--cat-lime)' },
                  { name: 'operating', data: revenue.map((r,i)=>((r-cogs[i]-opex[i])/r)*100), color: accent },
                  { name: 'net', data: revenue.map((r,i)=>(net[i]/r)*100), color: 'var(--cat-cyan)', dash: '4 3' },
                ]}
                w={420} h={200} labels={months} yFmt={v => v.toFixed(0)+'%'}
              />
            </Card>
          </div>
        </div>
      </Section>
    );
  }

  // ---------- Cash Flow (Waterfall) ----------
  function CashFlow() {
    return (
      <Section id="cashflow" title="Cash Flow" note="April 2026 · indirect method · $k">
        <div className="report-grid-2">
          <Card title="Sources & Uses · waterfall" right="starting → ending cash">
            <C.Waterfall
              items={[
                { label: 'Start',       value: 271.2, type: 'start' },
                { label: 'Revenue',     value: 241.9, type: 'pos' },
                { label: 'Hosting',     value: -42.8, type: 'neg' },
                { label: 'Payroll',     value: -72.4, type: 'neg' },
                { label: 'Contractors', value: -12.6, type: 'neg' },
                { label: 'SaaS',        value:  -8.5, type: 'neg' },
                { label: 'Marketing',   value: -14.8, type: 'neg' },
                { label: 'Tax xfer',    value: -72.6, type: 'neg' },
                { label: 'Other',       value: -16.7, type: 'neg' },
                { label: 'Int. inc.',   value:   1.2, type: 'pos' },
                { label: 'Ending',      value: 284.0, type: 'end' },
              ]}
              w={620} h={320} padL={52} padR={10} padT={20} padB={60}
              yFmt={v => v.toFixed(0)+'k'}
            />
          </Card>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <Card title="Operating · Investing · Financing">
              <table className="pnl-table">
                <tbody>
                  <tr className="section-head"><td colSpan={2}>Operating</td></tr>
                  <tr className="sub"><td>Net income</td><td className="num">61.2</td></tr>
                  <tr className="sub"><td>Δ Receivables</td><td className="num">−8.4</td></tr>
                  <tr className="sub"><td>Δ Payables</td><td className="num">2.1</td></tr>
                  <tr className="sub"><td>D&A</td><td className="num">0.8</td></tr>
                  <tr className="total"><td>Cash from ops</td><td className="num">55.7</td></tr>
                  <tr className="section-head"><td colSpan={2}>Investing</td></tr>
                  <tr className="sub"><td>Capex (laptops)</td><td className="num">−4.2</td></tr>
                  <tr className="total"><td>Cash used in inv.</td><td className="num">−4.2</td></tr>
                  <tr className="section-head"><td colSpan={2}>Financing</td></tr>
                  <tr className="sub"><td>SAFE conversion</td><td className="num">0.0</td></tr>
                  <tr className="sub"><td>Treasury yield</td><td className="num">1.2</td></tr>
                  <tr className="total"><td>Cash from fin.</td><td className="num">1.2</td></tr>
                  <tr className="grand"><td>Δ Cash</td><td className="num">+12.7</td></tr>
                </tbody>
              </table>
            </Card>
            <Card title="Monthly cash in vs. out" right="$k">
              <C.BarChart
                data={cashIn.map((v,i) => v - cashOut[i])}
                w={420} h={180} labels={months} yFmt={v => v.toFixed(0)+'k'}
                color="var(--pos)" negColor="var(--neg)"
              />
            </Card>
          </div>
        </div>
      </Section>
    );
  }

  // ---------- Balance Sheet ----------
  function Balance() {
    const assets = [
      ['Current assets', null, true],
      ['Operating cash', 284.0],
      ['Tax reserve', 64.8],
      ['Payroll', 52.1],
      ['Mercury USD', 18.4],
      ['Wise EUR (USD eq.)', 12.9],
      ['Receivables (net)', 84.2],
      ['Prepaid expenses', 14.1],
      ['Total current', 530.5, false, 'total'],
      ['Non-current assets', null, true],
      ['Investments (IB)', 184.2],
      ['Crypto (Coinbase + on-chain)', 73.8],
      ['PP&E (net)', 11.4],
      ['Goodwill', 0.0],
      ['Total non-current', 269.4, false, 'total'],
      ['Total Assets', 799.9, false, 'grand'],
    ];
    const liab = [
      ['Current liabilities', null, true],
      ['Credit cards', 10.6],
      ['Payables', 18.2],
      ['Accrued payroll', 12.4],
      ['Deferred revenue', 48.1],
      ['Tax liability', 40.8],
      ['Total current', 130.1, false, 'total'],
      ['Long-term liabilities', null, true],
      ['Notes payable', 0.0],
      ['SAFE notes', 250.0],
      ['Total long-term', 250.0, false, 'total'],
      ['Total Liabilities', 380.1, false, 'grand'],
      ['Equity', null, true],
      ['Common stock', 10.0],
      ['Additional paid-in', 125.0],
      ['Retained earnings', 284.8],
      ['Total Equity', 419.8, false, 'grand'],
    ];
    const renderRows = (data) => data.map((r,i) => {
      if (r[2]) return <tr key={i} className="section-head"><td colSpan={2}>{r[0]}</td></tr>;
      const cls = r[3] === 'grand' ? 'grand' : r[3] === 'total' ? 'total' : 'sub';
      return <tr key={i} className={cls}><td>{r[0]}</td><td className="num">{r[1].toFixed(1)}</td></tr>;
    });

    return (
      <Section id="balance" title="Balance Sheet" note="as of 30 Apr 2026 · $k">
        <div className="report-grid-2">
          <Card title="Assets = $799.9k" right="liquid ratio 4.1×">
            <table className="pnl-table"><tbody>{renderRows(assets)}</tbody></table>
          </Card>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <Card title="Liabilities & Equity">
              <table className="pnl-table"><tbody>{renderRows(liab)}</tbody></table>
            </Card>
            <Card title="Asset composition" right="treemap">
              <C.Treemap
                items={[
                  { label: 'Ops Cash',     value: 284, color: catColors.infra },
                  { label: 'Investments',  value: 184, color: catColors.saas },
                  { label: 'Receivables',  value:  84, color: catColors.contract },
                  { label: 'Crypto',       value:  74, color: catColors.amber || 'var(--cat-amber)' },
                  { label: 'Tax Reserve',  value:  65, color: catColors.tax },
                  { label: 'Payroll',      value:  52, color: catColors.payroll },
                  { label: 'Other',        value:  57, color: 'var(--fg-2)' },
                ]}
                w={420} h={220}
              />
            </Card>
          </div>
        </div>
      </Section>
    );
  }

  // ---------- Revenue deep-dive ----------
  function Revenue() {
    return (
      <Section id="revenue" title="Revenue" note="April 2026 · expansion +12.4% · contraction 2.1%">
        <div className="report-grid-2">
          <Card title="ARR · waterfall" right="starting → ending ARR ($k)">
            <C.Waterfall
              items={[
                { label: 'Start ARR',  value: 2268, type: 'start' },
                { label: 'New',        value: 142.8, type: 'pos' },
                { label: 'Expansion',  value:  68.4, type: 'pos' },
                { label: 'Reactivation',value: 12.0,  type: 'pos' },
                { label: 'Contraction',value: -22.0,  type: 'neg' },
                { label: 'Churn',      value: -88.4,  type: 'neg' },
                { label: 'End ARR',    value: 2380.8, type: 'end' },
              ]}
              w={620} h={300} padB={60} yFmt={v => v.toFixed(0)+'k'}
            />
          </Card>
          <Card title="Revenue mix" right="April 2026">
            <div style={{ display: 'flex', gap: 12, alignItems: 'center', justifyContent: 'space-around' }}>
              <C.Donut
                slices={[
                  { label: 'Subscription', value: 198.4, color: 'var(--cat-lime)' },
                  { label: 'Annual',       value:  32.4, color: 'var(--cat-violet)' },
                  { label: 'Services',     value:   8.0, color: 'var(--cat-cyan)' },
                  { label: 'Other',        value:   3.08, color: 'var(--fg-2)' },
                ]}
                w={220} h={220} center={{ label: 'revenue · apr', value: '$241.9k' }}
              />
              <div className="legend" style={{ minWidth: 200 }}>
                <div className="row"><span><span className="sw" style={{background:'var(--cat-lime)'}}></span>Subscription</span><span>$198.4k</span><span>82.0%</span></div>
                <div className="row"><span><span className="sw" style={{background:'var(--cat-violet)'}}></span>Annual</span><span>$32.4k</span><span>13.4%</span></div>
                <div className="row"><span><span className="sw" style={{background:'var(--cat-cyan)'}}></span>Services</span><span>$8.0k</span><span>3.3%</span></div>
                <div className="row"><span><span className="sw" style={{background:'var(--fg-2)'}}></span>Other</span><span>$3.1k</span><span>1.3%</span></div>
              </div>
            </div>
          </Card>
        </div>

        <div style={{ height: 16 }} />

        <div className="report-grid-2">
          <Card title="MRR vs. new / churned">
            <C.LineChart
              series={[{ name: 'MRR', data: mrr, color: accent, width: 1.8 }]}
              w={520} h={220} labels={months} area yFmt={v => v.toFixed(0)+'k'}
            />
          </Card>
          <Card title="Top customers · April">
            <C.HBars
              items={[
                { label: 'Acme Corp', value: 32400 },
                { label: 'Initech', value: 24200 },
                { label: 'Hooli',    value: 18400 },
                { label: 'Stark Ind.',value: 16100 },
                { label: 'Globex',   value: 12800 },
                { label: 'Umbrella', value: 10200 },
                { label: 'Wayne Ent.',value: 9800 },
                { label: 'Dunder M.', value: 7400 },
                { label: 'Other · 170',value: 110580, color: 'var(--fg-3)' },
              ]}
              w={520} rowH={24}
            />
          </Card>
        </div>
      </Section>
    );
  }

  // ---------- Burn / Runway ----------
  function Burn() {
    return (
      <Section id="burn" title="Burn & Runway" note="default scenario · net burn on current trajectory">
        <div className="report-grid-3">
          <Card title="Runway">
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 10 }}>
              <C.Gauge value={18.4} min={0} max={36} w={260} h={160} color="var(--cat-amber)" label="18.4 mo" sublabel="months of runway" />
            </div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--fg-2)', textAlign: 'center', padding: '0 8px 8px', letterSpacing: '0.06em' }}>
              based on net burn of $94.2k/mo · cash + investments $468k
            </div>
          </Card>
          <Card title="Net burn" right="monthly · $k">
            <C.BarChart
              data={burnRate.slice(-12)} w={400} h={220} labels={months} yFmt={v => v.toFixed(0)+'k'}
              color="var(--neg)" />
          </Card>
          <Card title="Scenarios · runway sensitivity">
            <C.HBars
              items={[
                { label: 'Hire +2 eng',  value: 14.2, color: 'var(--neg)' },
                { label: 'Flat',         value: 18.4, color: accent },
                { label: '−10% OpEx',    value: 22.1, color: 'var(--pos)' },
                { label: '+$500k SAFE',  value: 24.9, color: 'var(--cat-cyan)' },
                { label: '−20% OpEx + 30% growth', value: 34.6, color: 'var(--cat-lime)' },
              ]}
              w={360} rowH={26} max={36}
              xFmt={(v) => v.toFixed(1) + ' mo'}
            />
          </Card>
        </div>

        <div style={{ height: 16 }} />

        <div className="report-grid-2">
          <Card title="Headcount vs. revenue · per-head productivity">
            <svg width={620} height={240} viewBox="0 0 620 240">
              {/* dual axis via two LineCharts would be ideal; draw inline */}
              {(() => {
                const padL=52, padR=52, padT=18, padB=28, w=620, h=240;
                const pW = w-padL-padR, pH = h-padT-padB;
                const rMin=100, rMax=260;
                const hMin=10, hMax=20;
                const xOf = i => padL + (i/(months.length-1)) * pW;
                const yOfR = v => padT + pH - ((v-rMin)/(rMax-rMin))*pH;
                const yOfH = v => padT + pH - ((v-hMin)/(hMax-hMin))*pH;
                return (
                  <g>
                    {[100,150,200,250].map((t,i) => (
                      <g key={i}>
                        <line x1={padL} x2={w-padR} y1={yOfR(t)} y2={yOfR(t)} stroke="var(--line)" strokeDasharray="1 3" />
                        <text x={padL-6} y={yOfR(t)+3} textAnchor="end" fontSize="10" fill="var(--cat-lime)" fontFamily="var(--font-mono)">{t}k</text>
                      </g>
                    ))}
                    {[10,14,18].map((t,i) => (
                      <text key={i} x={w-padR+6} y={yOfH(t)+3} fontSize="10" fill="var(--cat-amber)" fontFamily="var(--font-mono)">{t}</text>
                    ))}
                    <path d={revenue.map((v,i) => (i?'L':'M')+xOf(i)+' '+yOfR(v)).join(' ')} fill="none" stroke="var(--cat-lime)" strokeWidth="1.8" />
                    <path d={headcount.map((v,i) => (i?'L':'M')+xOf(i)+' '+yOfH(v)).join(' ')} fill="none" stroke="var(--cat-amber)" strokeWidth="1.6" strokeDasharray="4 2" />
                    {months.map((m,i) => (
                      <text key={i} x={xOf(i)} y={h-padB+14} textAnchor="middle" fontSize="10" fill="var(--fg-2)" fontFamily="var(--font-mono)">{m}</text>
                    ))}
                    <g transform={`translate(${padL} ${padT-8})`}>
                      <rect width="10" height="2" fill="var(--cat-lime)" /><text x="14" y="2" fontSize="10" fill="var(--fg-1)" fontFamily="var(--font-mono)" style={{textTransform:'uppercase',letterSpacing:'0.08em'}}>revenue</text>
                      <rect x="90" width="10" height="2" fill="var(--cat-amber)" /><text x="104" y="2" fontSize="10" fill="var(--fg-1)" fontFamily="var(--font-mono)" style={{textTransform:'uppercase',letterSpacing:'0.08em'}}>headcount</text>
                    </g>
                  </g>
                );
              })()}
            </svg>
          </Card>
          <Card title="Efficiency ratios">
            <table className="pnl-table">
              <tbody>
                <tr className="sub"><td>Revenue per head</td><td className="num">$13.4k / mo</td></tr>
                <tr className="sub"><td>Burn multiple</td><td className="num">0.39</td></tr>
                <tr className="sub"><td>CAC · blended</td><td className="num">$782</td></tr>
                <tr className="sub"><td>CAC payback</td><td className="num">5.1 mo</td></tr>
                <tr className="sub"><td>LTV / CAC</td><td className="num">11.4×</td></tr>
                <tr className="sub"><td>Magic number</td><td className="num">1.82</td></tr>
                <tr className="sub"><td>Rule of 40</td><td className="num">+58.3</td></tr>
                <tr className="total"><td>Efficiency grade</td><td className="num" style={{color:'var(--pos)'}}>A</td></tr>
              </tbody>
            </table>
          </Card>
        </div>
      </Section>
    );
  }

  // ---------- Treasury ----------
  function Treasury() {
    return (
      <Section id="treasury" title="Treasury" note="cash laddering · yield · concentration">
        <div className="report-grid-2">
          <Card title="Cash position by account" right="$">
            <C.HBars
              items={[
                { label: 'Operating ·0142', value: 284013 },
                { label: 'IB Treasury',     value: 184210, color: 'var(--cat-cyan)' },
                { label: 'Coinbase',        value:  41233, color: 'var(--cat-amber)' },
                { label: 'Tax Reserve ·0923', value: 64820, color: 'var(--cat-blue)' },
                { label: 'Payroll ·1188',   value:  52100, color: catColors.payroll },
                { label: 'Mercury ·4491',   value:  18402, color: 'var(--cat-violet)' },
                { label: 'Wise EUR',        value:  12890, color: 'var(--cat-teal)' },
              ]}
              w={480} rowH={26}
            />
          </Card>
          <Card title="Yield ladder" right="4-wk rolling T-bills">
            <table className="pnl-table">
              <thead><tr><th>Tranche</th><th>Matures</th><th>Rate</th><th>Principal</th><th>Int.</th></tr></thead>
              <tbody>
                <tr className="sub"><td>4W · #a128</td><td>May 14</td><td className="num">5.34%</td><td className="num">$40k</td><td className="num">$182</td></tr>
                <tr className="sub"><td>4W · #a129</td><td>May 21</td><td className="num">5.32%</td><td className="num">$40k</td><td className="num">$182</td></tr>
                <tr className="sub"><td>4W · #a130</td><td>May 28</td><td className="num">5.31%</td><td className="num">$40k</td><td className="num">$181</td></tr>
                <tr className="sub"><td>4W · #a131</td><td>Jun 04</td><td className="num">5.29%</td><td className="num">$40k</td><td className="num">$180</td></tr>
                <tr className="sub"><td>MMF · Vanguard</td><td>—</td><td className="num">5.28%</td><td className="num">$24.2k</td><td className="num">$107</td></tr>
                <tr className="total"><td>Weighted avg</td><td>—</td><td className="num">5.31%</td><td className="num">$184.2k</td><td className="num">$832 / mo</td></tr>
              </tbody>
            </table>
          </Card>
        </div>

        <div style={{ height: 16 }} />

        <div className="report-grid-3">
          <Card title="FDIC exposure">
            <div style={{ padding: 10 }}>
              <div style={{ fontFamily: 'var(--font-serif)', fontSize: 28, letterSpacing: '-0.01em' }}>$250k <span style={{ color: 'var(--fg-3)' }}>/ $411k</span></div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--fg-2)', letterSpacing: '0.08em' }}>FDIC-insured / at bankx partner banks</div>
              <div style={{ marginTop: 14, height: 10, background: 'var(--bg-3)' }}>
                <div style={{ width: (250/411*100)+'%', height: '100%', background: 'var(--pos)' }} />
              </div>
              <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', marginTop: 8, letterSpacing: '0.06em' }}>
                $161k swept across 4 partner banks · coverage up to $1M via IntraFi
              </div>
            </div>
          </Card>
          <Card title="Counterparty concentration">
            <C.Donut
              slices={[
                { label: 'bankx partners', value: 354, color: accent },
                { label: 'IB',             value: 184, color: 'var(--cat-cyan)' },
                { label: 'Coinbase',       value:  41, color: 'var(--cat-amber)' },
                { label: 'Chase',          value:   0, color: 'var(--cat-violet)' },
              ].filter(s => s.value > 0)}
              w={220} h={200} center={{ label: 'total', value: '$579k' }}
            />
          </Card>
          <Card title="Interest income · TTM">
            <C.LineChart
              series={[{ name: 'interest', data: [310,340,380,420,460,510,580,640,720,800,882,942], color: 'var(--pos)', width: 1.8 }]}
              w={300} h={200} labels={months} area yFmt={v => '$'+v}
            />
          </Card>
        </div>
      </Section>
    );
  }

  // ---------- FX ----------
  function FX() {
    const eurUsd = Array.from({length: 30}, (_, i) => ({
      o: 1.062 + Math.sin(i*0.4)*0.01,
      h: 1.070 + Math.sin(i*0.4)*0.01 + 0.004,
      l: 1.058 + Math.sin(i*0.4)*0.01 - 0.003,
      c: 1.065 + Math.sin(i*0.4+0.5)*0.01,
    }));
    return (
      <Section id="fx" title="FX exposure" note="2 non-USD positions · 24% international revenue">
        <div className="report-grid-2">
          <Card title="EUR/USD · 30d" right="spot 1.0684">
            <C.Candles data={eurUsd} w={540} h={220} labels={eurUsd.map((_,i)=>i%5===0?'d'+i:'')} />
          </Card>
          <Card title="Exposure by currency">
            <table className="pnl-table">
              <thead><tr><th>Ccy</th><th>Amount</th><th>Spot</th><th>USD eq.</th><th>% NAV</th></tr></thead>
              <tbody>
                <tr className="sub"><td>USD</td><td className="num">580.1k</td><td className="num">1.0000</td><td className="num">$580.1k</td><td className="num">87.2%</td></tr>
                <tr className="sub"><td>EUR</td><td className="num">12.0k</td><td className="num">1.0684</td><td className="num">$12.8k</td><td className="num">1.9%</td></tr>
                <tr className="sub"><td>BTC</td><td className="num">0.482</td><td className="num">67,412</td><td className="num">$32.5k</td><td className="num">4.9%</td></tr>
                <tr className="sub"><td>ETH</td><td className="num">12.4</td><td className="num">3,312</td><td className="num">$41.1k</td><td className="num">6.0%</td></tr>
                <tr className="total"><td>Total</td><td></td><td></td><td className="num">$666.5k</td><td className="num">100.0%</td></tr>
              </tbody>
            </table>
          </Card>
        </div>
      </Section>
    );
  }

  // ---------- Crypto ----------
  function Crypto() {
    const btc = Array.from({length: 90}, (_, i) => 61 + Math.sin(i*0.15)*4 + i*0.08);
    return (
      <Section id="crypto" title="Crypto" note="on-chain + exchange · cost basis tracking">
        <div className="report-grid-2">
          <Card title="BTC price · 90d" right="$67,412 spot">
            <C.LineChart
              series={[{ name:'BTC', data: btc, color: 'var(--cat-amber)', width: 1.6 }]}
              w={540} h={220} labels={Array.from({length:90}, (_,i) => i%15===0 ? 'd'+i : '')}
              yFmt={v => '$'+v.toFixed(0)+'k'} area
            />
          </Card>
          <Card title="Holdings · FIFO basis">
            <table className="pnl-table">
              <thead><tr><th>Asset</th><th>Qty</th><th>Basis</th><th>Mkt</th><th>P&L</th></tr></thead>
              <tbody>
                <tr className="sub"><td>BTC</td><td className="num">0.4823</td><td className="num">$24,102</td><td className="num">$32,510</td><td className="num" style={{color:'var(--pos)'}}>+$8,408</td></tr>
                <tr className="sub"><td>ETH</td><td className="num">12.4000</td><td className="num">$34,480</td><td className="num">$41,069</td><td className="num" style={{color:'var(--pos)'}}>+$6,589</td></tr>
                <tr className="sub"><td>USDC</td><td className="num">8,200</td><td className="num">$8,200</td><td className="num">$8,200</td><td className="num" style={{color:'var(--fg-2)'}}>—</td></tr>
                <tr className="total"><td>Total</td><td></td><td className="num">$66,782</td><td className="num">$81,779</td><td className="num" style={{color:'var(--pos)'}}>+$14,997</td></tr>
              </tbody>
            </table>
            <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', padding: '10px 4px 0', letterSpacing: '0.08em' }}>
              unrealized · taxable when sold · auto-mark-to-market nightly
            </div>
          </Card>
        </div>
      </Section>
    );
  }

  // ---------- Customers / Cohorts ----------
  function Customers() {
    return (
      <Section id="customers" title="Customers" note="178 active · $1,358 ARPU · 18% net expansion">
        <div className="report-grid-2">
          <Card title="New vs. churned · monthly">
            <svg width={540} height={220} viewBox="0 0 540 220">
              {(() => {
                const padL=48, padR=14, padT=14, padB=28, w=540, h=220;
                const pW=w-padL-padR, pH=h-padT-padB;
                const mx = Math.max(...newCust, ...churned);
                const step = pW/months.length;
                const bw = step*0.38;
                const yOf = v => padT + pH - (v/mx)*pH;
                return (
                  <g>
                    {[0,5,10,15,20].map(t => (
                      <g key={t}>
                        <line x1={padL} x2={w-padR} y1={yOf(t)} y2={yOf(t)} stroke="var(--line)" strokeDasharray="1 3" />
                        <text x={padL-6} y={yOf(t)+3} textAnchor="end" fontSize="10" fill="var(--fg-2)" fontFamily="var(--font-mono)">{t}</text>
                      </g>
                    ))}
                    {months.map((m,i) => {
                      const x0 = padL + i*step + step/2 - bw - 1;
                      const x1 = padL + i*step + step/2 + 1;
                      return (
                        <g key={i}>
                          <rect x={x0} y={yOf(newCust[i])} width={bw} height={yOf(0)-yOf(newCust[i])} fill="var(--pos)" />
                          <rect x={x1} y={yOf(churned[i])} width={bw} height={yOf(0)-yOf(churned[i])} fill="var(--neg)" />
                          <text x={padL + i*step + step/2} y={h-padB+14} textAnchor="middle" fontSize="10" fill="var(--fg-2)" fontFamily="var(--font-mono)">{m}</text>
                        </g>
                      );
                    })}
                    <g transform={`translate(${padL} ${padT-8})`}>
                      <rect width="10" height="10" y="-10" fill="var(--pos)" /><text x="14" y="-2" fontSize="10" fill="var(--fg-1)" fontFamily="var(--font-mono)" style={{textTransform:'uppercase',letterSpacing:'0.08em'}}>new</text>
                      <rect x="60" y="-10" width="10" height="10" fill="var(--neg)" /><text x="74" y="-2" fontSize="10" fill="var(--fg-1)" fontFamily="var(--font-mono)" style={{textTransform:'uppercase',letterSpacing:'0.08em'}}>churned</text>
                    </g>
                  </g>
                );
              })()}
            </svg>
          </Card>
          <Card title="ARPU · monthly">
            <C.LineChart
              series={[{ name: 'ARPU', data: mrr.map((m,i) => (m*1000)/customers[i]), color: accent, width: 1.8, dots: true }]}
              w={540} h={220} labels={months} yFmt={v => '$'+v.toFixed(0)} area
            />
          </Card>
        </div>
      </Section>
    );
  }

  function Cohorts() {
    const cohortMonths = ['Nov 24','Dec 24','Jan 25','Feb 25','Mar 25','Apr 25','May 25','Jun 25','Jul 25','Aug 25','Sep 25','Oct 25','Nov 25'];
    const periodCols = ['M0','M1','M2','M3','M4','M5','M6','M7','M8','M9','M10','M11'];
    // retention matrix — upper triangle filled
    const ret = cohortMonths.map((_, r) => periodCols.map((_, c) => {
      if (r + c > cohortMonths.length - 1) return null;
      const base = 100 - c*2.2 - Math.max(0, c-1)*1.3 + Math.sin(r*0.4)*2;
      return Math.max(74, Math.round(base));
    }));
    return (
      <Section id="cohorts" title="Cohort retention" note="net revenue retention by signup month · %">
        <div className="report-grid-2">
          <Card title="Retention heatmap" flush>
            <div style={{ padding: 14 }}>
              <C.Heatmap
                rows={cohortMonths} cols={periodCols} values={ret}
                w={560} h={340} pad={60}
                colorMin="var(--bg-2)" colorMax="var(--cat-lime)"
                fmt={v => v + '%'}
              />
            </div>
          </Card>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <Card title="NRR · TTM">
              <C.LineChart
                series={[{ name: 'NRR', data: [104,106,108,107,110,111,113,114,115,116,117,118], color: 'var(--cat-lime)', width: 1.8 }]}
                w={380} h={200} labels={months} yFmt={v => v + '%'} area
              />
            </Card>
            <Card title="Segment retention @ M6">
              <C.HBars
                items={[
                  { label: 'Enterprise', value: 112, color: 'var(--cat-lime)' },
                  { label: 'Mid-market', value: 98, color: accent },
                  { label: 'SMB',        value: 84, color: 'var(--cat-amber)' },
                  { label: 'Free→Paid',  value: 62, color: 'var(--neg)' },
                ]}
                w={380} rowH={26} max={120}
                xFmt={(v) => v + '%'}
              />
            </Card>
          </div>
        </div>
      </Section>
    );
  }

  // ---------- AR / AP ----------
  function ARAP() {
    return (
      <Section id="ar_ap" title="Receivables & Payables" note="aging analysis · DSO 32d · DPO 18d">
        <div className="report-grid-2">
          <Card title="Receivables aging" right="$84.2k outstanding">
            <table className="pnl-table">
              <thead><tr><th>Customer</th><th>Invoice</th><th>Due</th><th>Aging</th><th>Amount</th></tr></thead>
              <tbody>
                <tr className="sub"><td>Acme Corp</td><td className="num">#1042</td><td>May 02</td><td><span className="aging-pill">Current</span></td><td className="num">$12,400</td></tr>
                <tr className="sub"><td>Initech</td><td className="num">#1038</td><td>Apr 28</td><td><span className="aging-pill">Current</span></td><td className="num">$8,200</td></tr>
                <tr className="sub"><td>Hooli</td><td className="num">#1033</td><td>Apr 22</td><td><span className="aging-pill warn">8d</span></td><td className="num">$18,400</td></tr>
                <tr className="sub"><td>Stark Ind.</td><td className="num">#1029</td><td>Apr 16</td><td><span className="aging-pill warn">14d</span></td><td className="num">$16,100</td></tr>
                <tr className="sub"><td>Globex</td><td className="num">#1024</td><td>Apr 08</td><td><span className="aging-pill bad">22d</span></td><td className="num">$12,800</td></tr>
                <tr className="sub"><td>Umbrella Co.</td><td className="num">#1019</td><td>Mar 31</td><td><span className="aging-pill bad">30d</span></td><td className="num">$10,200</td></tr>
                <tr className="sub"><td>Wayne Ent.</td><td className="num">#1012</td><td>Mar 18</td><td><span className="aging-pill bad">43d</span></td><td className="num">$6,100</td></tr>
                <tr className="total"><td>Total AR</td><td></td><td></td><td></td><td className="num">$84,200</td></tr>
              </tbody>
            </table>
          </Card>
          <Card title="Payables aging" right="$18.2k owed">
            <table className="pnl-table">
              <thead><tr><th>Vendor</th><th>Due</th><th>Aging</th><th>Amount</th></tr></thead>
              <tbody>
                <tr className="sub"><td>AWS</td><td>May 04</td><td><span className="aging-pill">Current</span></td><td className="num">$12,480</td></tr>
                <tr className="sub"><td>Gusto</td><td>May 01</td><td><span className="aging-pill">Current</span></td><td className="num">$1,200</td></tr>
                <tr className="sub"><td>Datadog</td><td>Apr 30</td><td><span className="aging-pill">Today</span></td><td className="num">$2,400</td></tr>
                <tr className="sub"><td>Vercel</td><td>Apr 28</td><td><span className="aging-pill warn">2d</span></td><td className="num">$412</td></tr>
                <tr className="sub"><td>Linear</td><td>Apr 28</td><td><span className="aging-pill warn">2d</span></td><td className="num">$240</td></tr>
                <tr className="sub"><td>Cloudflare</td><td>Apr 26</td><td><span className="aging-pill warn">4d</span></td><td className="num">$250</td></tr>
                <tr className="sub"><td>Figma</td><td>Apr 22</td><td><span className="aging-pill bad">8d</span></td><td className="num">$180</td></tr>
                <tr className="sub"><td>Notion</td><td>Apr 20</td><td><span className="aging-pill bad">10d</span></td><td className="num">$96</td></tr>
                <tr className="sub"><td>Sentry</td><td>Apr 18</td><td><span className="aging-pill bad">12d</span></td><td className="num">$190</td></tr>
                <tr className="total"><td>Total AP</td><td></td><td></td><td className="num">$18,188</td></tr>
              </tbody>
            </table>
          </Card>
        </div>
      </Section>
    );
  }

  // ---------- Tax reserve summary ----------
  function Tax() {
    return (
      <Section id="tax" title="Tax" note="summary view · see /tax for full schedules & filings">
        <div className="report-grid-3">
          <Card title="Tax reserve · progress" >
            <div style={{ padding: 14 }}>
              <div style={{ fontFamily: 'var(--font-serif)', fontSize: 28 }}>$64.8k <span style={{color:'var(--fg-3)'}}>/ $72.5k</span></div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--fg-2)', marginTop: 4, letterSpacing: '0.08em' }}>89% funded · Q2 estimate</div>
              <div style={{ marginTop: 14, height: 10, background: 'var(--bg-3)' }}>
                <div style={{ width: '89%', height: '100%', background: 'var(--cat-blue)' }} />
              </div>
            </div>
          </Card>
          <Card title="Effective rate · TTM">
            <C.LineChart
              series={[{ name: 'eff rate', data: [26.1,25.8,25.5,25.2,25.0,25.1,25.0,24.9,24.8,24.8,24.8,24.8], color: 'var(--cat-blue)', width: 1.8 }]}
              w={360} h={160} labels={months} yFmt={v => v.toFixed(0)+'%'}
            />
          </Card>
          <Card title="Deadlines">
            <table className="pnl-table">
              <tbody>
                <tr className="sub"><td>Q2 estimate</td><td className="num">Jun 16</td><td className="num" style={{color:'var(--cat-amber)'}}>57d</td></tr>
                <tr className="sub"><td>Q3 estimate</td><td className="num">Sep 15</td><td className="num" style={{color:'var(--fg-2)'}}>148d</td></tr>
                <tr className="sub"><td>1099 delivery</td><td className="num">Jan 31</td><td className="num" style={{color:'var(--fg-2)'}}>286d</td></tr>
                <tr className="sub"><td>CA franchise</td><td className="num">Apr 15</td><td className="num" style={{color:'var(--fg-2)'}}>360d</td></tr>
              </tbody>
            </table>
          </Card>
        </div>
      </Section>
    );
  }

  // ---------- Audit / Trial Balance ----------
  function Audit() {
    const tb = [
      ['1000 · Operating Cash',        284013, 0],
      ['1010 · Tax Reserve',            64820, 0],
      ['1020 · Payroll',                52100, 0],
      ['1030 · Mercury',                18402, 0],
      ['1040 · Wise EUR',               12890, 0],
      ['1200 · Accounts Receivable',    84200, 0],
      ['1400 · Prepaid Expenses',       14100, 0],
      ['1500 · Investments (IB)',      184210, 0],
      ['1600 · Crypto',                 81779, 0],
      ['1700 · PP&E',                   11400, 0],
      ['2000 · Credit Cards',               0, 10554],
      ['2100 · Accounts Payable',           0, 18188],
      ['2200 · Accrued Payroll',            0, 12400],
      ['2300 · Deferred Revenue',           0, 48100],
      ['2400 · Tax Liability',              0, 40800],
      ['2500 · SAFE Notes',                 0, 250000],
      ['3000 · Common Stock',               0, 10000],
      ['3100 · Paid-in Capital',            0, 125000],
      ['3200 · Retained Earnings',          0, 284822],
      ['4000 · Revenue',                    0, 241880],
      ['5000 · COGS',                   52400, 0],
      ['5100 · Payroll',                72400, 0],
      ['5200 · Contractors',            12600, 0],
      ['5300 · Cloud Infra',             5100, 0],
      ['5400 · SaaS',                    8500, 0],
      ['5500 · Travel',                  3100, 0],
      ['5600 · Marketing',              14800, 0],
      ['5700 · Other',                  11300, 0],
      ['5800 · Interest Income',            0, 1200],
      ['5900 · FX Loss',                  400, 0],
    ];
    const dr = tb.reduce((a,r) => a + r[1], 0);
    const cr = tb.reduce((a,r) => a + r[2], 0);
    return (
      <Section id="audit" title="Trial Balance" note={`as of 30 Apr 2026 · auto-closed · Dr $${dr.toLocaleString()} · Cr $${cr.toLocaleString()}`}>
        <div className="report-grid-2">
          <Card title="Accounts" right={dr === cr ? <span className="tb-balanced">· balanced ✓</span> : 'unbalanced'}>
            <table className="pnl-table">
              <thead><tr><th>Account</th><th>Debit</th><th>Credit</th></tr></thead>
              <tbody>
                {tb.map((r,i) => (
                  <tr key={i} className="sub">
                    <td style={{ fontFamily: 'var(--font-mono)', fontSize: 11 }}>{r[0]}</td>
                    <td className="num">{r[1] ? '$'+r[1].toLocaleString() : <span style={{color:'var(--fg-3)'}}>—</span>}</td>
                    <td className="num">{r[2] ? '$'+r[2].toLocaleString() : <span style={{color:'var(--fg-3)'}}>—</span>}</td>
                  </tr>
                ))}
                <tr className="grand">
                  <td>Totals</td>
                  <td className="num">${dr.toLocaleString()}</td>
                  <td className="num">${cr.toLocaleString()}</td>
                </tr>
              </tbody>
            </table>
          </Card>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <Card title="Reconciliation status">
              <table className="pnl-table">
                <tbody>
                  <tr className="sub"><td>Operating ·0142</td><td className="num" style={{color:'var(--pos)'}}>reconciled · 2s</td></tr>
                  <tr className="sub"><td>Tax Reserve ·0923</td><td className="num" style={{color:'var(--pos)'}}>reconciled · 12s</td></tr>
                  <tr className="sub"><td>Payroll ·1188</td><td className="num" style={{color:'var(--pos)'}}>reconciled · 1m</td></tr>
                  <tr className="sub"><td>Chase Ink</td><td className="num" style={{color:'var(--pos)'}}>reconciled · 4m</td></tr>
                  <tr className="sub"><td>Amex Plat</td><td className="num" style={{color:'var(--cat-amber)'}}>2 unmatched · 1m</td></tr>
                  <tr className="sub"><td>Mercury</td><td className="num" style={{color:'var(--pos)'}}>reconciled · 4m</td></tr>
                  <tr className="sub"><td>Wise EUR</td><td className="num" style={{color:'var(--pos)'}}>reconciled · 8m</td></tr>
                  <tr className="sub"><td>Coinbase</td><td className="num" style={{color:'var(--pos)'}}>reconciled · 1m</td></tr>
                  <tr className="sub"><td>BTC on-chain</td><td className="num" style={{color:'var(--pos)'}}>reconciled · 30s</td></tr>
                  <tr className="sub"><td>IB</td><td className="num" style={{color:'var(--cat-amber)'}}>degraded · 2h</td></tr>
                </tbody>
              </table>
            </Card>
            <Card title="Journal · today">
              <table className="pnl-table">
                <tbody>
                  <tr className="sub"><td style={{fontFamily:'var(--font-mono)',fontSize:11}}>je_9421 · auto</td><td className="num">$72,564 tax xfer</td></tr>
                  <tr className="sub"><td style={{fontFamily:'var(--font-mono)',fontSize:11}}>je_9420 · auto</td><td className="num">$48,201 Stripe revenue</td></tr>
                  <tr className="sub"><td style={{fontFamily:'var(--font-mono)',fontSize:11}}>je_9419 · auto</td><td className="num">$12,480 AWS</td></tr>
                  <tr className="sub"><td style={{fontFamily:'var(--font-mono)',fontSize:11}}>je_9418 · manual</td><td className="num">$320 reclass</td></tr>
                  <tr className="sub"><td style={{fontFamily:'var(--font-mono)',fontSize:11}}>je_9417 · auto</td><td className="num">$54,200 Gusto</td></tr>
                </tbody>
              </table>
            </Card>
          </div>
        </div>
      </Section>
    );
  }

  // ---------- Root ----------
  // Tab-based hero header used on every reports page.
  function ReportsHero({ activePage }) {
    const [period, setPeriod] = useState('YTD');
    return (
      <div className="reports-hero">
        <div className="crumb mono" style={{ fontSize: 11, color: 'var(--fg-2)', letterSpacing: '0.14em', textTransform: 'uppercase', marginBottom: 8 }}>
          workspace <span style={{opacity:0.4}}>›</span> reports <span style={{opacity:0.4}}>›</span> {SECTIONS.find(s => s.id === activePage)?.label || 'financials'}
        </div>
        <h1>Reports <span style={{ color: 'var(--fg-3)', fontStyle: 'italic', fontSize: 22 }}>· 30 Apr 2026</span></h1>
        <div className="sub">13 reports · 4 accountants have read access · last closed 2026-03 · snapshot bx://snap/2026-04</div>
        <div className="reports-controls">
          <div className="period-pick">
            {PERIODS.map(p => (
              <button key={p} className={period===p?'on':''} onClick={() => setPeriod(p)}>{p}</button>
            ))}
          </div>
          <div style={{ flex: 1 }} />
          <button className="btn">Download · PDF</button>
          <button className="btn">Export · XLSX</button>
          <button className="btn">Send to accountant</button>
          <button className="btn primary">Close April</button>
        </div>
      </div>
    );
  }

  function ReportsTabs({ activePage, goto }) {
    return (
      <nav className="reports-tabs">
        {SECTIONS.map(s => (
          <a key={s.id}
             className={activePage === s.id ? 'on' : ''}
             onClick={(e) => { e.preventDefault(); goto && goto('reports/' + s.id); }}
             href={'#reports/' + s.id}>{s.label}</a>
        ))}
      </nav>
    );
  }

  function ReportPage({ pageId, goto, children }) {
    return (
      <div className="reports">
        <ReportsHero activePage={pageId} />
        <ReportsTabs activePage={pageId} goto={goto} />
        <div className="reports-body">
          {children}
        </div>
        <div style={{ padding: '40px var(--pad-x) 80px', textAlign: 'center' }}>
          <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', letterSpacing: '0.2em', textTransform: 'uppercase' }}>
            signed bx-audit-a12f8 · generated in {30 + Math.round(Math.random()*60)}ms · section {pageId}
          </div>
        </div>
      </div>
    );
  }

  // Per-page wrappers — one per section, with shared chrome
  const sectionRenderers = {
    overview:  Overview,
    pnl:       PnL,
    cashflow:  CashFlow,
    balance:   Balance,
    revenue:   Revenue,
    burn:      Burn,
    treasury:  Treasury,
    fx:        FX,
    crypto:    Crypto,
    customers: Customers,
    cohorts:   Cohorts,
    ar_ap:     ARAP,
    tax:       Tax,
    audit:     Audit,
  };

  function ReportsPage(pageId) {
    return function Wrapped({ goto }) {
      const Inner = sectionRenderers[pageId];
      return (
        <ReportPage pageId={pageId} goto={goto}>
          {Inner && <Inner />}
        </ReportPage>
      );
    };
  }

  // Legacy single-page view — renders all sections (used by 'data' mode when available)
  function Reports({ goto }) {
    return (
      <ReportPage pageId="overview" goto={goto}>
        <Overview />
        <PnL />
        <CashFlow />
        <Balance />
        <Revenue />
        <Burn />
        <Treasury />
        <FX />
        <Crypto />
        <Customers />
        <Cohorts />
        <ARAP />
        <Tax />
        <Audit />
      </ReportPage>
    );
  }

  window.ReportsView = Reports;
  window.ReportsPages = {};
  for (const key of Object.keys(sectionRenderers)) {
    window.ReportsPages[key] = ReportsPage(key);
  }
})();
