// BILLING & ANALYTICS — 18 opportunity components + 5 hubs
(function () {
  const { useState, useMemo, useEffect, useRef } = React;
  const T = window.ArbiterTokens;
  const bl = window.__bl;
  const ba = window.ba;

  // ── Shared helpers ───────────────────────────────────────
  function BaSubTabs({ tabs, active, onChange }) {
    return (
      <div style={{ display: 'flex', gap: '8px', marginBottom: '16px', flexWrap: 'wrap' }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => onChange(t.id)}
            style={{ ...ba.subTab, ...(active === t.id ? ba.subTabActive : {}) }}>
            {t.label}
          </button>
        ))}
      </div>
    );
  }

  function TH({ children, align }) {
    return <th style={{ ...bl.th, textAlign: align || 'left' }}>{children}</th>;
  }
  function TD({ children, align, mono, color, bold }) {
    return <td style={{ ...bl.td, textAlign: align || 'left', fontFamily: mono ? T.font.mono : T.font.family, color: color || T.color.text.primary, fontWeight: bold ? 700 : 400 }}>{children}</td>;
  }
  function Pill({ children, bg, color, title }) {
    return <span title={title} style={{ ...bl.tag, background: bg, color, fontWeight: 700, letterSpacing: '0.02em' }}>{children}</span>;
  }
  function ProgressBar({ pct, color, height }) {
    const clamp = Math.max(0, Math.min(100, pct));
    return (
      <div style={{ width: '100%', height: height || '6px', background: T.color.bg.secondary, borderRadius: '3px', overflow: 'hidden' }}>
        <div style={{ width: `${clamp}%`, height: '100%', background: color || bl.emerald, transition: 'width 0.3s' }} />
      </div>
    );
  }
  function useCrossRender(topics) {
    const [, force] = React.useReducer(x => x + 1, 0);
    React.useEffect(() => {
      if (!window.BillingAnalyticsStore) return;
      const t = Array.isArray(topics) ? topics : [topics || '*'];
      const offs = t.map(x => window.BillingAnalyticsStore.bus.on(x, () => force()));
      return () => offs.forEach(off => off());
    }, []);
  }
  function Flash({ msg }) {
    if (!msg) return null;
    return (
      <div style={{ padding: '8px 14px', marginBottom: '12px', background: '#1B7A4A10', border: '1px solid #1B7A4A40', borderRadius: '6px', fontSize: '11px', color: '#1B7A4A', fontWeight: 600 }}>{msg}</div>
    );
  }

  // ════════════════════════════════════════════════════════
  // 1. PASSIVE TIME CAPTURE ENGINE
  // ════════════════════════════════════════════════════════
  function Ba1Passive() {
    useCrossRender(['passive.approved', 'passive.rejected', 'passive.bulk-approved']);
    const S = window.BillingAnalyticsStore;
    const D = window.BILLING_ANALYTICS_DATA;
    const [flash, setFlash] = useState(null);
    const f = (m) => { setFlash(m); setTimeout(() => setFlash(null), 2000); };
    const pending = S.passivePending();
    const pendingValue = S.passivePendingValue();

    return (
      <div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: '12px', marginBottom: '16px' }}>
          <div style={bl.stat}><span style={bl.statLabel}>Pending Entries</span><span style={bl.statValue}>{pending.length}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Pending Hours</span><span style={bl.statValue}>{pending.reduce((s, e) => s + e.hours, 0).toFixed(1)}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Est. Value Recovered</span><span style={{ ...bl.statValue, color: bl.emerald }}>{bl.money(pendingValue)}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Avg Confidence</span><span style={bl.statValue}>{pending.length ? (pending.reduce((s, e) => s + e.confidence, 0) / pending.length * 100).toFixed(0) : '—'}%</span></div>
        </div>

        <Flash msg={flash} />

        <div style={ba.card}>
          <div style={ba.cardH}>
            <span>Inferred Time Candidates · awaiting approval</span>
            <button style={ba.btnPrimary} onClick={() => { const n = S.approveAllPassive('M. Kirkland'); f(`Approved ${n} entries · ${bl.money(pendingValue)} recovered`); }}>Approve All</button>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><TH>Date</TH><TH>Matter</TH><TH>Source</TH><TH>Signal</TH><TH align="right">Hours</TH><TH align="right">Conf</TH><TH>Suggested Narrative</TH><TH align="right">Action</TH></tr></thead>
            <tbody>
              {S.state.passiveCapture.filter(e => e.status === 'pending').map(e => (
                <tr key={e.id}>
                  <TD mono>{e.date}</TD>
                  <TD>{e.matterName}</TD>
                  <TD color={T.color.text.tertiary}>{e.source}</TD>
                  <TD color={T.color.text.secondary}>{e.signal}</TD>
                  <TD align="right" mono bold>{e.hours.toFixed(1)}</TD>
                  <TD align="right" mono color={e.confidence >= 0.9 ? bl.emerald : bl.amber} bold>{(e.confidence * 100).toFixed(0)}%</TD>
                  <TD color={T.color.text.secondary}><span style={{ fontSize: '11px', lineHeight: 1.4 }}>{e.suggestedNarrative}</span></TD>
                  <TD align="right">
                    <div style={{ display: 'flex', gap: '4px', justifyContent: 'flex-end' }}>
                      <button style={{ ...ba.btn, background: bl.emerald, color: '#fff', borderColor: bl.emerald, padding: '4px 10px', fontSize: '10px' }} onClick={() => { S.approvePassiveEntry(e.id, 'M. Kirkland'); f(`Approved · ${e.hours}h on ${e.matterName}`); }}>Approve</button>
                      <button style={{ ...ba.btn, padding: '4px 10px', fontSize: '10px' }} onClick={() => { S.rejectPassiveEntry(e.id, 'M. Kirkland'); f('Rejected'); }}>Reject</button>
                    </div>
                  </TD>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    );
  }

  // ════════════════════════════════════════════════════════
  // 2. OCG COMPLIANCE ENGINE
  // ════════════════════════════════════════════════════════
  function Ba2OcgCompliance() {
    useCrossRender(['ocg.resolved']);
    const S = window.BillingAnalyticsStore;
    const [activeClient, setActiveClient] = useState('All');
    const [flash, setFlash] = useState(null);
    const f = (m) => { setFlash(m); setTimeout(() => setFlash(null), 2000); };
    const clients = ['All', ...new Set(S.state.ocgRules.map(r => r.client))];
    const rules = activeClient === 'All' ? S.state.ocgRules : S.state.ocgRules.filter(r => r.client === activeClient);
    const violations = activeClient === 'All' ? S.state.ocgViolations : S.state.ocgViolations.filter(v => v.client === activeClient);
    const sevColor = { critical: bl.crimson, high: bl.amber, medium: bl.slate };

    return (
      <div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: '12px', marginBottom: '16px' }}>
          <div style={bl.stat}><span style={bl.statLabel}>OCG Rules Parsed</span><span style={bl.statValue}>{S.state.ocgRules.length}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Clients Covered</span><span style={bl.statValue}>{new Set(S.state.ocgRules.map(r => r.client)).size}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Open Violations</span><span style={{ ...bl.statValue, color: bl.crimson }}>{S.ocgOpenCount()}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Value at Risk</span><span style={{ ...bl.statValue, color: bl.crimson }}>{bl.money(S.ocgOpenValue())}</span></div>
        </div>

        <Flash msg={flash} />

        <div style={{ display: 'flex', gap: '6px', marginBottom: '12px', flexWrap: 'wrap' }}>
          {clients.map(c => (
            <button key={c} onClick={() => setActiveClient(c)}
              style={{ ...ba.subTab, ...(activeClient === c ? ba.subTabActive : {}) }}>{c}</button>
          ))}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
          <div style={ba.card}>
            <div style={ba.cardH}><span>Parsed OCG Rules ({rules.length})</span></div>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead><tr><TH>Rule</TH><TH>Detail</TH><TH align="center">Severity</TH><TH align="center">Auto-block</TH></tr></thead>
              <tbody>
                {rules.map(r => (
                  <tr key={r.id}>
                    <TD bold>{r.rule}<div style={{ fontSize: '10px', color: T.color.text.tertiary, fontWeight: 400 }}>{activeClient === 'All' ? r.client : ''}</div></TD>
                    <TD color={T.color.text.secondary}>{r.detail}</TD>
                    <TD align="center"><Pill bg={sevColor[r.severity] + '10'} color={sevColor[r.severity]}>{r.severity.toUpperCase()}</Pill></TD>
                    <TD align="center">{r.autoBlock ? <Pill bg={bl.emerald + '10'} color={bl.emerald}>ON</Pill> : <Pill bg={T.color.bg.secondary} color={T.color.text.tertiary}>OFF</Pill>}</TD>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <div style={ba.card}>
            <div style={ba.cardH}><span style={{ color: bl.crimson }}>Open Violations ({violations.filter(v => v.status === 'flagged').length})</span></div>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead><tr><TH>Entry</TH><TH>Timekeeper</TH><TH>Violation</TH><TH align="right">Value</TH><TH align="right">Action</TH></tr></thead>
              <tbody>
                {violations.map(v => {
                  const rule = S.state.ocgRules.find(r => r.id === v.rule);
                  return (
                    <tr key={v.id}>
                      <TD mono>{v.entryId}</TD>
                      <TD>{v.timekeeper}</TD>
                      <TD color={T.color.text.secondary}><span style={{ fontSize: '11px' }}>{v.detail}</span><div style={{ fontSize: '9px', color: T.color.text.tertiary }}>{rule ? rule.rule : v.rule}</div></TD>
                      <TD align="right" mono bold color={bl.crimson}>{bl.money(v.value)}</TD>
                      <TD align="right">{v.status === 'resolved' ? <Pill bg={bl.emerald + '10'} color={bl.emerald}>RESOLVED</Pill> : <button style={{ ...ba.btn, fontSize: '10px', padding: '3px 8px' }} onClick={() => { S.resolveOcgViolation(v.id, 'write-down', 'M. Kirkland'); f(`Resolved ${v.entryId}`); }}>Write-down</button>}</TD>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    );
  }

  // ════════════════════════════════════════════════════════
  // 3. NARRATIVE INTELLIGENCE
  // ════════════════════════════════════════════════════════
  function Ba3Narrative() {
    useCrossRender(['narrative.rewritten']);
    const S = window.BillingAnalyticsStore;
    const [flash, setFlash] = useState(null);
    const f = (m) => { setFlash(m); setTimeout(() => setFlash(null), 2000); };
    const sevColor = { critical: bl.crimson, high: bl.amber, medium: bl.slate };

    return (
      <div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: '12px', marginBottom: '16px' }}>
          <div style={bl.stat}><span style={bl.statLabel}>Flagged Narratives</span><span style={{ ...bl.statValue, color: bl.amber }}>{S.state.narrativeFlags.length}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>AI Rewrites Accepted</span><span style={{ ...bl.statValue, color: bl.emerald }}>{S.state.narrativeFlags.filter(n => n.accepted).length}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Projected Save (vs eBilling cuts)</span><span style={{ ...bl.statValue, color: bl.emerald }}>{bl.money(S.state.narrativeFlags.length * 1800)}</span></div>
        </div>

        <Flash msg={flash} />

        <div style={ba.card}>
          <div style={ba.cardH}><span>Narrative Rewrite Queue</span></div>
          {S.state.narrativeFlags.map(n => (
            <div key={n.id} style={{ padding: '14px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'grid', gridTemplateColumns: '80px 1fr 1fr 100px 90px', gap: '12px', alignItems: 'center' }}>
              <div><span style={{ fontFamily: T.font.mono, fontSize: '11px', fontWeight: 700 }}>{n.entryId}</span><div><Pill bg={sevColor[n.severity] + '10'} color={sevColor[n.severity]}>{n.severity.toUpperCase()}</Pill></div></div>
              <div>
                <div style={{ fontSize: '10px', fontWeight: 700, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '2px' }}>Original</div>
                <div style={{ fontSize: '11px', color: T.color.text.secondary, fontStyle: 'italic', lineHeight: 1.4, padding: '6px 10px', background: bl.crimsonBg, borderRadius: '4px' }}>"{n.original}"</div>
              </div>
              <div>
                <div style={{ fontSize: '10px', fontWeight: 700, color: bl.emerald, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '2px' }}>AI Rewrite</div>
                <div style={{ fontSize: '11px', color: T.color.text.primary, lineHeight: 1.4, padding: '6px 10px', background: bl.emeraldBg, borderRadius: '4px', border: `1px solid ${bl.emeraldBorder}` }}>"{n.suggestion}"</div>
              </div>
              <div><span style={{ fontSize: '11px', fontWeight: 700 }}>{n.issue}</span></div>
              <div>{n.accepted ? <Pill bg={bl.emerald + '10'} color={bl.emerald}>APPLIED</Pill> : <button style={{ ...ba.btnPrimary, background: bl.emerald }} onClick={() => { S.acceptNarrativeRewrite(n.id, 'M. Kirkland'); f(`Rewrite applied to ${n.entryId}`); }}>Apply</button>}</div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // ════════════════════════════════════════════════════════
  // 4. RATE CARD ARCHITECT
  // ════════════════════════════════════════════════════════
  function Ba4RateCardArchitect() {
    const S = window.BillingAnalyticsStore;
    const [active, setActive] = useState('RC-STD-2026');
    const [compare, setCompare] = useState('');
    const card = S.state.rateCards.find(c => c.id === active);
    const cmp = compare ? S.state.rateCards.find(c => c.id === compare) : null;

    return (
      <div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: '12px', marginBottom: '16px' }}>
          <div style={bl.stat}><span style={bl.statLabel}>Active Rate Cards</span><span style={bl.statValue}>{S.state.rateCards.length}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Pending Changes</span><span style={{ ...bl.statValue, color: bl.amber }}>{S.state.rateChangeRequests.filter(r => r.status !== 'approved').length}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Impact if Approved</span><span style={{ ...bl.statValue, color: bl.emerald }}>{bl.money(S.state.rateChangeRequests.reduce((s, r) => s + r.impact, 0))}</span></div>
        </div>

        <div style={{ display: 'flex', gap: '6px', marginBottom: '12px', flexWrap: 'wrap' }}>
          {S.state.rateCards.map(c => (
            <button key={c.id} onClick={() => { setActive(c.id); setCompare(''); }} style={{ ...ba.subTab, ...(active === c.id ? ba.subTabActive : {}) }}>{c.name}</button>
          ))}
          <select value={compare} onChange={e => setCompare(e.target.value)} style={{ ...ba.subTab, padding: '8px 10px' }}>
            <option value="">Compare with…</option>
            {S.state.rateCards.filter(c => c.id !== active).map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: compare ? '1fr 1fr' : '1fr', gap: '16px' }}>
          <div style={ba.card}>
            <div style={ba.cardH}>
              <span>{card.name}</span>
              <span style={{ fontSize: '10px', color: T.color.text.tertiary }}>Effective {card.effective} · {card.discount ? `${(card.discount * 100).toFixed(0)}% discount` : 'Standard'}</span>
            </div>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead><tr><TH>Role</TH><TH align="right">Rate</TH><TH align="right">vs Standard</TH></tr></thead>
              <tbody>
                {card.tiers.map(tier => {
                  const std = S.state.rateCards.find(c => c.id === 'RC-STD-2026').tiers.find(t => t.role === tier.role);
                  const diff = std ? ((tier.rate - std.rate) / std.rate) * 100 : 0;
                  return (
                    <tr key={tier.role}>
                      <TD bold>{tier.role}</TD>
                      <TD align="right" mono bold>${tier.rate.toLocaleString()}/hr</TD>
                      <TD align="right" mono color={diff === 0 ? T.color.text.tertiary : diff < 0 ? bl.crimson : bl.emerald}>{diff === 0 ? '—' : (diff > 0 ? '+' : '') + diff.toFixed(1) + '%'}</TD>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
          {cmp && (
            <div style={ba.card}>
              <div style={ba.cardH}><span>{cmp.name}</span><span style={{ fontSize: '10px', color: T.color.text.tertiary }}>Effective {cmp.effective}</span></div>
              <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                <thead><tr><TH>Role</TH><TH align="right">Rate</TH><TH align="right">Δ vs {card.name.split(' ')[0]}</TH></tr></thead>
                <tbody>
                  {cmp.tiers.map(tier => {
                    const other = card.tiers.find(t => t.role === tier.role);
                    const diff = other ? ((tier.rate - other.rate) / other.rate) * 100 : 0;
                    return (
                      <tr key={tier.role}>
                        <TD bold>{tier.role}</TD>
                        <TD align="right" mono bold>${tier.rate.toLocaleString()}/hr</TD>
                        <TD align="right" mono color={diff === 0 ? T.color.text.tertiary : diff < 0 ? bl.crimson : bl.emerald}>{diff === 0 ? '—' : (diff > 0 ? '+' : '') + diff.toFixed(1) + '%'}</TD>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>

        <div style={{ ...ba.card, marginTop: '16px' }}>
          <div style={ba.cardH}><span>Pending Rate Change Requests</span></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><TH>Proposal</TH><TH>Rate Card</TH><TH>Effective</TH><TH align="right">Revenue Impact</TH><TH align="right">Clients</TH><TH align="right">Status</TH></tr></thead>
            <tbody>
              {S.state.rateChangeRequests.map(r => (
                <tr key={r.id}>
                  <TD bold>{r.proposal}<div style={{ fontSize: '10px', color: T.color.text.tertiary, fontWeight: 400 }}>{r.proposedBy}</div></TD>
                  <TD mono>{r.rateCard}</TD>
                  <TD mono>{r.effective}</TD>
                  <TD align="right" mono bold color={bl.emerald}>{bl.money(r.impact)}</TD>
                  <TD align="right" mono>{r.clientsAffected}</TD>
                  <TD align="right"><Pill bg={r.status === 'approved' ? bl.emerald + '10' : bl.amber + '10'} color={r.status === 'approved' ? bl.emerald : bl.amber}>{r.status.toUpperCase()}</Pill></TD>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    );
  }

  // ════════════════════════════════════════════════════════
  // 5. RATE RAISE SIMULATOR
  // ════════════════════════════════════════════════════════
  function Ba5RateRaiseSim() {
    const D = window.BILLING_ANALYTICS_DATA;
    const [selected, setSelected] = useState(D.rateRaiseScenarios[1].label);
    const sc = D.rateRaiseScenarios.find(s => s.label === selected);

    return (
      <div>
        <div style={{ display: 'flex', gap: '6px', marginBottom: '16px', flexWrap: 'wrap' }}>
          {D.rateRaiseScenarios.map(s => (
            <button key={s.label} onClick={() => setSelected(s.label)} style={{ ...ba.subTab, ...(selected === s.label ? ba.subTabActive : {}) }}>
              {s.label} (+{s.raisePct}%)
            </button>
          ))}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: '12px', marginBottom: '16px' }}>
          <div style={bl.stat}><span style={bl.statLabel}>Proposed Raise</span><span style={bl.statValue}>+{sc.raisePct}%</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Pushback Probability</span><span style={{ ...bl.statValue, color: sc.pushbackProb > 0.3 ? bl.crimson : bl.amber }}>{(sc.pushbackProb * 100).toFixed(0)}%</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Expected Realization</span><span style={{ ...bl.statValue, color: bl.realColor(sc.expectedRealization) }}>{sc.expectedRealization}%</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Net Revenue Δ (12mo)</span><span style={{ ...bl.statValue, color: bl.emerald }}>{bl.money(sc.netRevenueDelta)}</span></div>
        </div>

        <div style={ba.card}>
          <div style={ba.cardH}><span>Scenario Comparison</span></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><TH>Scenario</TH><TH align="right">Raise</TH><TH align="right">Pushback</TH><TH align="right">Realization</TH><TH align="right">Collection Lag</TH><TH align="right">Net Revenue Δ</TH></tr></thead>
            <tbody>
              {D.rateRaiseScenarios.map(s => {
                const isSelected = s.label === selected;
                return (
                  <tr key={s.label} style={{ background: isSelected ? ba.violetBg : 'transparent' }}>
                    <TD bold color={isSelected ? ba.violet : T.color.text.primary}>{s.label}</TD>
                    <TD align="right" mono bold>+{s.raisePct}%</TD>
                    <TD align="right" mono color={s.pushbackProb > 0.3 ? bl.crimson : s.pushbackProb > 0.15 ? bl.amber : bl.emerald}>{(s.pushbackProb * 100).toFixed(0)}%</TD>
                    <TD align="right" mono color={bl.realColor(s.expectedRealization)}>{s.expectedRealization}%</TD>
                    <TD align="right" mono>{s.collectionLagDays}d</TD>
                    <TD align="right" mono bold color={bl.emerald}>{bl.money(s.netRevenueDelta)}</TD>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        <div style={{ padding: '12px 16px', background: ba.violetBg, borderRadius: '8px', marginTop: '12px', fontSize: '11px', color: T.color.text.secondary, lineHeight: 1.5, border: `1px solid ${ba.violetBorder}` }}>
          <span style={{ fontWeight: 700, color: ba.violet, textTransform: 'uppercase', fontSize: '10px', letterSpacing: '0.08em' }}>Monte Carlo · 10,000 runs</span><br />
          {sc.label} scenario with {sc.raisePct}% raise: 95% confidence interval for net revenue delta is {bl.money(sc.netRevenueDelta * 0.74)} to {bl.money(sc.netRevenueDelta * 1.18)}. Collection lag increases DSO by {sc.collectionLagDays} days. {Math.round(sc.pushbackProb * 100)}% of top-20 clients expected to push back; typical outcome is {Math.round(sc.pushbackProb * 30)}% of affected revenue re-negotiated to {sc.raisePct - 1}%.
        </div>
      </div>
    );
  }

  // ════════════════════════════════════════════════════════
  // 6. MATTER PRICING ENGINE
  // ════════════════════════════════════════════════════════
  function Ba6MatterPricing() {
    const D = window.BILLING_ANALYTICS_DATA;
    const [selected, setSelected] = useState(D.pricingBenchmarks[0].matterType);
    const [priceIndex, setPriceIndex] = useState(1.0);
    const bench = D.pricingBenchmarks.find(b => b.matterType === selected);
    const priceOptions = [0.7, 0.9, 1.0, 1.15, 1.3];
    const winProb = bench.winRateByPrice.find(w => w.priceIndex === priceIndex)?.winProb || 0.5;
    const priceEst = bench.medianFee * priceIndex;
    const expectedValue = priceEst * winProb;

    return (
      <div>
        <div style={{ display: 'flex', gap: '6px', marginBottom: '16px', flexWrap: 'wrap' }}>
          {D.pricingBenchmarks.map(b => (
            <button key={b.matterType} onClick={() => setSelected(b.matterType)} style={{ ...ba.subTab, ...(selected === b.matterType ? ba.subTabActive : {}) }}>{b.matterType}</button>
          ))}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: '12px', marginBottom: '16px' }}>
          <div style={bl.stat}><span style={bl.statLabel}>Median Fee (P50)</span><span style={bl.statValue}>{bl.money(bench.medianFee)}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>P25 — P75 Range</span><span style={{ ...bl.statValue, fontSize: '14px' }}>{bl.money(bench.p25)}—{bl.money(bench.p75)}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Avg Duration</span><span style={bl.statValue}>{bench.avgDurationMos} mo</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Recommended Staffing</span><span style={{ ...bl.statValue, fontSize: '11px', lineHeight: 1.4 }}>{bench.recommendedStaffing}</span></div>
        </div>

        <div style={ba.card}>
          <div style={ba.cardH}><span>Price vs Win-Probability Curve</span></div>
          <div style={{ padding: '16px' }}>
            <div style={{ display: 'flex', gap: '4px', marginBottom: '12px', flexWrap: 'wrap' }}>
              {priceOptions.map(p => (
                <button key={p} onClick={() => setPriceIndex(p)} style={{ ...ba.subTab, ...(priceIndex === p ? ba.subTabActive : {}) }}>
                  {p === 1.0 ? 'Median' : p < 1 ? `P${Math.round(p * 100)} (-${Math.round((1 - p) * 100)}%)` : `P${Math.round(p * 100)} (+${Math.round((p - 1) * 100)}%)`}
                </button>
              ))}
            </div>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead><tr><TH>Price Point</TH><TH align="right">Fee</TH><TH align="right">Win Probability</TH><TH align="right">Expected Value</TH><TH>Bar</TH></tr></thead>
              <tbody>
                {bench.winRateByPrice.map(w => {
                  const fee = bench.medianFee * w.priceIndex;
                  const ev = fee * w.winProb;
                  const isSelected = w.priceIndex === priceIndex;
                  return (
                    <tr key={w.priceIndex} style={{ background: isSelected ? ba.violetBg : 'transparent' }}>
                      <TD bold color={isSelected ? ba.violet : T.color.text.primary}>{w.priceIndex === 1.0 ? 'Median' : w.priceIndex < 1 ? 'Below' : 'Above'} ({(w.priceIndex * 100).toFixed(0)}%)</TD>
                      <TD align="right" mono bold>{bl.money(fee)}</TD>
                      <TD align="right" mono color={w.winProb > 0.7 ? bl.emerald : w.winProb > 0.5 ? bl.amber : bl.crimson}>{(w.winProb * 100).toFixed(0)}%</TD>
                      <TD align="right" mono bold>{bl.money(ev)}</TD>
                      <TD><ProgressBar pct={w.winProb * 100} color={w.winProb > 0.7 ? bl.emerald : w.winProb > 0.5 ? bl.amber : bl.crimson} /></TD>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>

        <div style={{ padding: '14px 18px', background: ba.violetBg, borderRadius: '8px', marginTop: '12px', border: `1px solid ${ba.violetBorder}` }}>
          <div style={{ fontSize: '10px', fontWeight: 700, color: ba.violet, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '6px' }}>Pricing Recommendation · {selected}</div>
          <div style={{ fontSize: '13px', color: T.color.text.primary, lineHeight: 1.5 }}>
            At <span style={{ fontWeight: 700, color: ba.violet }}>{bl.money(priceEst)}</span>, win probability is <span style={{ fontWeight: 700 }}>{(winProb * 100).toFixed(0)}%</span> · Expected value <span style={{ fontWeight: 700, color: bl.emerald }}>{bl.money(expectedValue)}</span>. Based on {bench.winRateByPrice.length}-point historical curve from {bench.avgDurationMos}-month matters.
          </div>
        </div>
      </div>
    );
  }

  // ════════════════════════════════════════════════════════
  // 7. PRE-BILL COMMAND CENTER
  // ════════════════════════════════════════════════════════
  function Ba7PreBill() {
    useCrossRender(['prebill.resolved', 'prebill.bulk-resolved']);
    const S = window.BillingAnalyticsStore;
    const [selected, setSelected] = useState([]);
    const [flash, setFlash] = useState(null);
    const f = (m) => { setFlash(m); setTimeout(() => setFlash(null), 2000); };
    const open = S.state.preBillIssues.filter(i => i.status !== 'resolved');
    const toggle = (id) => setSelected(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
    const selectAll = () => setSelected(open.map(i => i.id));
    const sevColor = { critical: bl.crimson, high: bl.amber, medium: bl.slate };

    const byType = open.reduce((acc, i) => { acc[i.type] = (acc[i.type] || 0) + 1; return acc; }, {});

    return (
      <div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: '12px', marginBottom: '16px' }}>
          <div style={bl.stat}><span style={bl.statLabel}>Open Issues</span><span style={{ ...bl.statValue, color: bl.amber }}>{open.length}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Value at Risk</span><span style={{ ...bl.statValue, color: bl.crimson }}>{bl.money(S.preBillOpenValue())}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Critical</span><span style={{ ...bl.statValue, color: bl.crimson }}>{open.filter(i => i.severity === 'critical').length}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Selected</span><span style={bl.statValue}>{selected.length}</span></div>
        </div>

        <Flash msg={flash} />

        <div style={{ display: 'flex', gap: '6px', marginBottom: '12px', flexWrap: 'wrap' }}>
          {Object.entries(byType).map(([t, n]) => (
            <span key={t} style={{ padding: '4px 10px', borderRadius: '12px', background: T.color.bg.secondary, border: `1px solid ${T.color.border.light}`, fontSize: '10px', fontWeight: 600, color: T.color.text.secondary }}>
              {t}: <span style={{ color: bl.crimson, fontWeight: 700 }}>{n}</span>
            </span>
          ))}
        </div>

        <div style={{ display: 'flex', gap: '6px', marginBottom: '12px' }}>
          <button style={ba.btn} onClick={selectAll}>Select All</button>
          <button style={ba.btn} onClick={() => setSelected([])}>Clear</button>
          {selected.length > 0 && (
            <>
              <button style={{ ...ba.btnPrimary, background: bl.emerald }} onClick={() => { const n = S.bulkResolvePreBill(selected, 'approved', 'M. Kirkland'); f(`${n} issues resolved`); setSelected([]); }}>Bulk Approve ({selected.length})</button>
              <button style={{ ...ba.btnPrimary, background: bl.crimson }} onClick={() => { const n = S.bulkResolvePreBill(selected, 'written-down', 'M. Kirkland'); f(`${n} issues written down`); setSelected([]); }}>Bulk Write-down</button>
            </>
          )}
        </div>

        <div style={ba.card}>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><TH></TH><TH>Invoice</TH><TH>Client / Matter</TH><TH>Issue</TH><TH align="center">Sev</TH><TH align="right">Entries</TH><TH align="right">Value</TH><TH>Suggested Action</TH><TH align="right"></TH></tr></thead>
            <tbody>
              {open.map(i => (
                <tr key={i.id} style={{ background: selected.includes(i.id) ? ba.violetBg : 'transparent' }}>
                  <TD><input type="checkbox" checked={selected.includes(i.id)} onChange={() => toggle(i.id)} /></TD>
                  <TD mono>{i.invoice}</TD>
                  <TD><span style={{ fontWeight: 600 }}>{i.client}</span><div style={{ fontSize: '10px', color: T.color.text.tertiary }}>{i.matter}</div></TD>
                  <TD bold>{i.type}</TD>
                  <TD align="center"><Pill bg={sevColor[i.severity] + '10'} color={sevColor[i.severity]}>{i.severity.toUpperCase()}</Pill></TD>
                  <TD align="right" mono>{i.entries}</TD>
                  <TD align="right" mono bold color={bl.crimson}>{bl.money(i.value)}</TD>
                  <TD color={T.color.text.secondary}>{i.action}</TD>
                  <TD align="right"><button style={{ ...ba.btn, fontSize: '10px', padding: '3px 8px' }} onClick={() => { S.resolvePreBillIssue(i.id, 'approved', 'M. Kirkland'); f(`${i.id} resolved`); }}>Resolve</button></TD>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    );
  }

  // ════════════════════════════════════════════════════════
  // 8. EBILLING SUPER-CONNECTOR
  // ════════════════════════════════════════════════════════
  function Ba8Ebilling() {
    useCrossRender(['ebilling.appealed']);
    const S = window.BillingAnalyticsStore;
    const [flash, setFlash] = useState(null);
    const f = (m) => { setFlash(m); setTimeout(() => setFlash(null), 2000); };
    const statusColor = { Paid: bl.emerald, Pending: bl.slate, Reduced: bl.amber, Rejected: bl.crimson, Appealed: ba.violet };
    const totalReduction = S.state.ebillingSubmissions.reduce((s, x) => s + (x.reduction || 0), 0);
    const totalSubmitted = S.state.ebillingSubmissions.reduce((s, x) => s + x.amount, 0);

    return (
      <div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: '12px', marginBottom: '16px' }}>
          <div style={bl.stat}><span style={bl.statLabel}>Connected Vendors</span><span style={bl.statValue}>{S.state.ebillingVendors.filter(v => v.connected).length}/{S.state.ebillingVendors.length}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Submitted (QTD)</span><span style={bl.statValue}>{bl.money(totalSubmitted)}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Reductions</span><span style={{ ...bl.statValue, color: bl.crimson }}>{bl.money(totalReduction)}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Reduction Rate</span><span style={{ ...bl.statValue, color: bl.realColor(100 - (totalReduction / totalSubmitted * 100)) }}>{((totalReduction / totalSubmitted) * 100).toFixed(1)}%</span></div>
        </div>

        <Flash msg={flash} />

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
          <div style={ba.card}>
            <div style={ba.cardH}><span>Vendor Connections</span></div>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead><tr><TH>Vendor</TH><TH>Client</TH><TH>Format</TH><TH align="center">Status</TH></tr></thead>
              <tbody>
                {S.state.ebillingVendors.map(v => (
                  <tr key={v.id}>
                    <TD bold>{v.name}</TD>
                    <TD color={T.color.text.secondary}>{v.client}</TD>
                    <TD mono color={T.color.text.tertiary}>{v.format}</TD>
                    <TD align="center">{v.connected ? <Pill bg={bl.emerald + '10'} color={bl.emerald}>CONNECTED</Pill> : <Pill bg={bl.crimsonBg} color={bl.crimson}>OFFLINE</Pill>}</TD>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <div style={ba.card}>
            <div style={ba.cardH}><span>Recent Submissions</span></div>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead><tr><TH>Invoice</TH><TH>Vendor</TH><TH align="right">Amount</TH><TH align="right">Reduced</TH><TH align="center">Status</TH><TH align="right"></TH></tr></thead>
              <tbody>
                {S.state.ebillingSubmissions.map(s => (
                  <tr key={s.id}>
                    <TD mono>{s.invoice}</TD>
                    <TD color={T.color.text.secondary}><span style={{ fontSize: '11px' }}>{s.vendor}</span></TD>
                    <TD align="right" mono bold>{bl.money(s.amount)}</TD>
                    <TD align="right" mono color={s.reduction > 0 ? bl.crimson : T.color.text.tertiary}>{s.reduction > 0 ? bl.money(s.reduction) : '—'}</TD>
                    <TD align="center"><Pill bg={statusColor[s.status] + '10'} color={statusColor[s.status]}>{s.status.toUpperCase()}</Pill></TD>
                    <TD align="right">{(s.status === 'Reduced' || s.status === 'Rejected') && <button style={{ ...ba.btn, fontSize: '10px', padding: '3px 8px' }} onClick={() => { S.appealEbillingReduction(s.id, 'M. Kirkland'); f(`Appeal filed · ${s.invoice}`); }}>Appeal</button>}</TD>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        <div style={{ ...ba.card, marginTop: '16px' }}>
          <div style={ba.cardH}><span>Reduction Reason Analysis</span></div>
          <div style={{ padding: '12px 16px' }}>
            {S.state.ebillingSubmissions.filter(s => s.reductionReason).map(s => (
              <div key={s.id} style={{ padding: '8px 0', borderBottom: `1px solid ${T.color.border.light}`, display: 'grid', gridTemplateColumns: '100px 1fr 120px', gap: '12px', alignItems: 'center' }}>
                <span style={{ fontFamily: T.font.mono, fontSize: '11px', fontWeight: 700 }}>{s.invoice}</span>
                <span style={{ fontSize: '11px', color: T.color.text.secondary }}>{s.reductionReason}</span>
                <span style={{ fontFamily: T.font.mono, fontSize: '11px', fontWeight: 700, color: bl.crimson, textAlign: 'right' }}>{bl.money(s.reduction)}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  // ════════════════════════════════════════════════════════
  // 9. JOINT-REP / MULTI-ENTITY
  // ════════════════════════════════════════════════════════
  function Ba9JointRep() {
    const S = window.BillingAnalyticsStore;

    return (
      <div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: '12px', marginBottom: '16px' }}>
          <div style={bl.stat}><span style={bl.statLabel}>Joint-Rep Matters</span><span style={bl.statValue}>{S.state.jointMatters.length}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Total Entities</span><span style={bl.statValue}>{S.state.jointMatters.reduce((s, m) => s + m.parties.length, 0)}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>YTD Joint Fees</span><span style={{ ...bl.statValue, color: bl.emerald }}>{bl.money(S.state.jointMatters.reduce((s, m) => s + m.ytdFees, 0))}</span></div>
        </div>

        {S.state.jointMatters.map(m => (
          <div key={m.id} style={ba.card}>
            <div style={ba.cardH}>
              <span>{m.matter}</span>
              <span style={{ fontSize: '10px', color: T.color.text.tertiary }}>YTD fees {bl.money(m.ytdFees)} · costs {bl.money(m.ytdCosts)}</span>
            </div>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead><tr><TH>Entity</TH><TH align="center">Alloc Basis</TH><TH align="right">Alloc %</TH><TH align="right">Allocated Fees</TH><TH align="right">Allocated Costs</TH><TH align="center">Currency</TH></tr></thead>
              <tbody>
                {m.parties.map((p, i) => (
                  <tr key={i}>
                    <TD bold>{p.entity}</TD>
                    <TD align="center"><Pill bg={T.color.bg.secondary} color={T.color.text.secondary}>{p.allocBasis.toUpperCase()}</Pill></TD>
                    <TD align="right" mono bold>{p.allocPct}%</TD>
                    <TD align="right" mono bold color={bl.emerald}>{bl.money(m.ytdFees * p.allocPct / 100)}</TD>
                    <TD align="right" mono>{bl.money(m.ytdCosts * p.allocPct / 100)}</TD>
                    <TD align="center" mono>{p.currency || 'USD'}</TD>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ))}
      </div>
    );
  }

  // ════════════════════════════════════════════════════════
  // 10. AR INTELLIGENCE
  // ════════════════════════════════════════════════════════
  function Ba10ArIntel() {
    useCrossRender(['collection.triggered']);
    const S = window.BillingAnalyticsStore;
    const [flash, setFlash] = useState(null);
    const f = (m) => { setFlash(m); setTimeout(() => setFlash(null), 2000); };
    const riskColor = { Low: bl.emerald, Moderate: bl.amber, Elevated: bl.orange, High: bl.crimson };
    const total = S.state.arPredictions.reduce((s, a) => s + a.outstanding, 0);
    const highRisk = S.state.arPredictions.filter(a => a.riskScore === 'High' || a.riskScore === 'Elevated').reduce((s, a) => s + a.outstanding, 0);

    return (
      <div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: '12px', marginBottom: '16px' }}>
          <div style={bl.stat}><span style={bl.statLabel}>Total Outstanding</span><span style={bl.statValue}>{bl.money(total)}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Avg Predicted DSO</span><span style={bl.statValue}>{Math.round(S.state.arPredictions.reduce((s, a) => s + a.predictedDaysToPay, 0) / S.state.arPredictions.length)}d</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>High/Elevated Risk</span><span style={{ ...bl.statValue, color: bl.crimson }}>{bl.money(highRisk)}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>% of AR at Risk</span><span style={{ ...bl.statValue, color: bl.crimson }}>{((highRisk / total) * 100).toFixed(1)}%</span></div>
        </div>

        <Flash msg={flash} />

        <div style={ba.card}>
          <div style={ba.cardH}><span>Client-Level AR Prediction · ML-scored</span></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><TH>Client</TH><TH align="right">Outstanding</TH><TH align="right">Predicted DTP</TH><TH align="right">Historical Avg</TH><TH align="center">Risk</TH><TH>Trend</TH><TH>Recommended Action</TH><TH align="right"></TH></tr></thead>
            <tbody>
              {S.state.arPredictions.map(a => (
                <tr key={a.client}>
                  <TD bold>{a.client}</TD>
                  <TD align="right" mono bold>{bl.money(a.outstanding)}</TD>
                  <TD align="right" mono color={a.predictedDaysToPay > a.historicalAvg + 10 ? bl.crimson : a.predictedDaysToPay > a.historicalAvg ? bl.amber : bl.emerald}>{a.predictedDaysToPay}d</TD>
                  <TD align="right" mono color={T.color.text.tertiary}>{a.historicalAvg}d</TD>
                  <TD align="center"><Pill bg={riskColor[a.riskScore] + '10'} color={riskColor[a.riskScore]}>{a.riskScore.toUpperCase()}</Pill></TD>
                  <TD color={a.trend === 'deteriorating' || a.trend === 'late-stage' ? bl.crimson : a.trend === 'slowing' ? bl.amber : bl.emerald}>{a.trend}</TD>
                  <TD color={T.color.text.secondary}><span style={{ fontSize: '11px' }}>{a.collectionAction}</span></TD>
                  <TD align="right"><button style={{ ...ba.btn, fontSize: '10px', padding: '3px 8px' }} onClick={() => { S.triggerCollectionAction(a.client, a.collectionAction, 'M. Kirkland'); const dueDate = new Date(); dueDate.setDate(dueDate.getDate() + 7); S.pushCollectionToCalendar({ client: a.client, dueDate: dueDate.toISOString().slice(0, 10), priority: a.riskScore === 'High' ? 'critical' : 'high', notes: a.collectionAction }); f(`Action triggered for ${a.client} · Calendar notified`); }}>Act</button></TD>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    );
  }

  // ════════════════════════════════════════════════════════
  // 11. WIP RISK MAP
  // ════════════════════════════════════════════════════════
  function Ba11WipRisk() {
    const S = window.BillingAnalyticsStore;
    const total = S.state.wipRisk.reduce((s, w) => s + w.wipValue, 0);
    const atRisk = S.state.wipRisk.reduce((s, w) => s + (w.wipValue * w.writeDownProb), 0);
    const opportunity = S.state.wipRisk.reduce((s, w) => s + w.cashAccelOpportunity, 0);

    return (
      <div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: '12px', marginBottom: '16px' }}>
          <div style={bl.stat}><span style={bl.statLabel}>Total WIP</span><span style={bl.statValue}>{bl.money(total)}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Probable Write-Down</span><span style={{ ...bl.statValue, color: bl.crimson }}>{bl.money(atRisk)}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Cash Accel Opportunity</span><span style={{ ...bl.statValue, color: bl.emerald }}>{bl.money(opportunity)}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Stale Matters (&gt;90d)</span><span style={{ ...bl.statValue, color: bl.amber }}>{S.state.wipRisk.filter(w => w.daysAged > 90).length}</span></div>
        </div>

        <div style={ba.card}>
          <div style={ba.cardH}><span>WIP Risk Matrix · bill-now vs write-down</span></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><TH>Matter</TH><TH>Client</TH><TH align="right">WIP Value</TH><TH align="right">Days Aged</TH><TH align="right">Write-Down Prob</TH><TH align="right">Cash Opp.</TH><TH>Recommended</TH></tr></thead>
            <tbody>
              {S.state.wipRisk.sort((a, b) => b.writeDownProb - a.writeDownProb).map(w => (
                <tr key={w.matter}>
                  <TD bold>{w.matter}</TD>
                  <TD color={T.color.text.secondary}>{w.client}</TD>
                  <TD align="right" mono bold>{bl.money(w.wipValue)}</TD>
                  <TD align="right" mono color={w.daysAged > 90 ? bl.crimson : w.daysAged > 60 ? bl.amber : bl.emerald}>{w.daysAged}d</TD>
                  <TD align="right" mono color={w.writeDownProb > 0.3 ? bl.crimson : w.writeDownProb > 0.15 ? bl.amber : bl.emerald}>{(w.writeDownProb * 100).toFixed(0)}%</TD>
                  <TD align="right" mono bold color={bl.emerald}>{bl.money(w.cashAccelOpportunity)}</TD>
                  <TD color={w.recommendedAction.includes('imminent') ? bl.crimson : w.recommendedAction.includes('now') ? bl.emerald : bl.amber}><span style={{ fontSize: '11px', fontWeight: 600 }}>{w.recommendedAction}</span></TD>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    );
  }

  // ════════════════════════════════════════════════════════
  // 12. MATTER BUDGET PACING
  // ════════════════════════════════════════════════════════
  function Ba12BudgetPacing() {
    useCrossRender(['budget.escalated']);
    const S = window.BillingAnalyticsStore;
    const [flash, setFlash] = useState(null);
    const f = (m) => { setFlash(m); setTimeout(() => setFlash(null), 2000); };
    const alertColor = { emerald: bl.emerald, amber: bl.amber, crimson: bl.crimson };

    return (
      <div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: '12px', marginBottom: '16px' }}>
          <div style={bl.stat}><span style={bl.statLabel}>Tracked Matters</span><span style={bl.statValue}>{S.state.budgetPacing.length}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Major Overruns</span><span style={{ ...bl.statValue, color: bl.crimson }}>{S.state.budgetPacing.filter(b => b.alertLevel === 'crimson').length}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Minor Overruns</span><span style={{ ...bl.statValue, color: bl.amber }}>{S.state.budgetPacing.filter(b => b.alertLevel === 'amber').length}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Total Variance $</span><span style={{ ...bl.statValue, color: bl.crimson }}>{bl.money(S.state.budgetPacing.reduce((s, b) => s + Math.max(0, b.variance), 0))}</span></div>
        </div>

        <Flash msg={flash} />

        <div style={ba.card}>
          <div style={ba.cardH}><span>Matter Budget Pacing · projected burn vs cap</span></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><TH>Matter</TH><TH align="right">Budget</TH><TH align="right">Spent</TH><TH align="right">% Used</TH><TH>Pace</TH><TH align="right">Projected</TH><TH align="right">Variance</TH><TH>Status</TH><TH align="right"></TH></tr></thead>
            <tbody>
              {S.state.budgetPacing.map(b => (
                <tr key={b.matter}>
                  <TD bold>{b.matter}<div style={{ fontSize: '10px', color: T.color.text.tertiary, fontWeight: 400 }}>{b.client} · {b.monthsRemaining}mo remaining</div></TD>
                  <TD align="right" mono>{bl.money(b.budget)}</TD>
                  <TD align="right" mono bold>{bl.money(b.spent)}</TD>
                  <TD align="right" mono bold color={b.pctUsed > 85 ? bl.crimson : b.pctUsed > 70 ? bl.amber : bl.emerald}>{b.pctUsed.toFixed(1)}%</TD>
                  <TD><div style={{ width: '100px' }}><ProgressBar pct={b.pctUsed} color={b.pctUsed > 85 ? bl.crimson : b.pctUsed > 70 ? bl.amber : bl.emerald} /></div></TD>
                  <TD align="right" mono>{bl.money(b.projectedFinal)}</TD>
                  <TD align="right" mono bold color={b.variance > 0 ? bl.crimson : bl.emerald}>{b.variance > 0 ? '+' : ''}{bl.money(b.variance)}<div style={{ fontSize: '9px', color: T.color.text.tertiary, fontWeight: 400 }}>({b.varPct > 0 ? '+' : ''}{b.varPct.toFixed(1)}%)</div></TD>
                  <TD><Pill bg={alertColor[b.alertLevel] + '10'} color={alertColor[b.alertLevel]}>{b.status.toUpperCase()}</Pill></TD>
                  <TD align="right">{b.alertLevel === 'crimson' && !b.escalated && <button style={{ ...ba.btn, fontSize: '10px', padding: '3px 8px', background: bl.crimson, color: '#fff', borderColor: bl.crimson }} onClick={() => { S.escalateBudgetAlert(b.matter, 'M. Kirkland'); f(`Escalated ${b.matter} to originating partner`); }}>Escalate</button>}{b.escalated && <Pill bg={bl.amber + '10'} color={bl.amber}>ESCALATED</Pill>}</TD>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    );
  }

  // ════════════════════════════════════════════════════════
  // 13. REALIZATION WATERFALL
  // ════════════════════════════════════════════════════════
  function Ba13Realization() {
    const S = window.BillingAnalyticsStore;
    const w = S.state.realizationWaterfall;
    const max = Math.max(...w.map(s => Math.abs(s.amount)));

    return (
      <div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: '12px', marginBottom: '16px' }}>
          <div style={bl.stat}><span style={bl.statLabel}>Standard Value</span><span style={bl.statValue}>{bl.money(w[0].amount)}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Collected Value</span><span style={{ ...bl.statValue, color: bl.emerald }}>{bl.money(w[w.length - 1].amount)}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Collected Realization</span><span style={{ ...bl.statValue, color: bl.realColor(w[w.length - 1].pct) }}>{w[w.length - 1].pct.toFixed(1)}%</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Total Leakage</span><span style={{ ...bl.statValue, color: bl.crimson }}>{bl.money(w[0].amount - w[w.length - 1].amount)}</span></div>
        </div>

        <div style={ba.card}>
          <div style={ba.cardH}><span>Realization Waterfall · standard → collected</span></div>
          <div style={{ padding: '16px' }}>
            {w.map((s, i) => {
              const isFinal = i === 0 || i === w.length - 1 || s.stage.includes('Worked') || s.stage.includes('Billed');
              const isNeg = s.amount < 0;
              const barWidth = (Math.abs(s.amount) / max) * 100;
              return (
                <div key={i} style={{ marginBottom: '10px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: '3px' }}>
                    <span style={{ fontSize: '12px', fontWeight: isFinal ? 700 : 500, color: isFinal ? T.color.text.primary : T.color.text.secondary }}>{s.stage}</span>
                    <span style={{ fontFamily: T.font.mono, fontSize: '12px', fontWeight: 700, color: isFinal ? T.color.text.primary : isNeg ? bl.crimson : bl.emerald }}>{isNeg ? '' : ''}{bl.money(s.amount)} <span style={{ fontSize: '10px', color: T.color.text.tertiary, fontWeight: 400, marginLeft: '8px' }}>({s.pct > 0 ? '+' : ''}{s.pct.toFixed(1)}%)</span></span>
                  </div>
                  <div style={{ height: isFinal ? '12px' : '8px', background: T.color.bg.secondary, borderRadius: '4px', overflow: 'hidden' }}>
                    <div style={{ width: `${barWidth}%`, height: '100%', background: isFinal ? bl.emerald : isNeg ? bl.crimson : bl.emeraldLight }} />
                  </div>
                  {s.reason && <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginTop: '2px', fontStyle: 'italic' }}>{s.reason}</div>}
                </div>
              );
            })}
          </div>
        </div>
      </div>
    );
  }

  // ════════════════════════════════════════════════════════
  // 14. MATTER PROFITABILITY (fully-loaded)
  // ════════════════════════════════════════════════════════
  function Ba14Profitability() {
    const S = window.BillingAnalyticsStore;
    const matters = [...S.state.matterProfitability].sort((a, b) => b.margin - a.margin);
    const totalRev = matters.reduce((s, m) => s + m.revenue, 0);
    const totalMargin = matters.reduce((s, m) => s + m.margin, 0);

    return (
      <div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: '12px', marginBottom: '16px' }}>
          <div style={bl.stat}><span style={bl.statLabel}>Revenue (sample)</span><span style={bl.statValue}>{bl.money(totalRev)}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Gross Margin</span><span style={{ ...bl.statValue, color: bl.emerald }}>{bl.money(totalMargin)}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Avg Margin %</span><span style={{ ...bl.statValue, color: bl.emerald }}>{((totalMargin / totalRev) * 100).toFixed(1)}%</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Avg Partner ROI</span><span style={{ ...bl.statValue, color: bl.emerald }}>{(matters.reduce((s, m) => s + m.partnerROI, 0) / matters.length).toFixed(1)}x</span></div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
          <div style={ba.card}>
            <div style={ba.cardH}><span>Matter P&L · fully-loaded cost</span></div>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead><tr><TH>Matter</TH><TH align="right">Revenue</TH><TH align="right">Direct</TH><TH align="right">Overhead</TH><TH align="right">Margin</TH><TH align="right">%</TH></tr></thead>
              <tbody>
                {matters.map(m => (
                  <tr key={m.matter}>
                    <TD bold>{m.matter}<div style={{ fontSize: '10px', color: T.color.text.tertiary, fontWeight: 400 }}>{m.client}</div></TD>
                    <TD align="right" mono>{bl.money(m.revenue)}</TD>
                    <TD align="right" mono color={T.color.text.tertiary}>{bl.money(m.directCost)}</TD>
                    <TD align="right" mono color={T.color.text.tertiary}>{bl.money(m.allocatedOverhead)}</TD>
                    <TD align="right" mono bold color={m.marginPct > 30 ? bl.emerald : m.marginPct > 20 ? bl.amber : bl.crimson}>{bl.money(m.margin)}</TD>
                    <TD align="right" mono bold color={m.marginPct > 30 ? bl.emerald : m.marginPct > 20 ? bl.amber : bl.crimson}>{m.marginPct.toFixed(1)}%</TD>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <div style={ba.card}>
            <div style={ba.cardH}><span>Client Profitability Decile</span></div>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead><tr><TH>Client</TH><TH align="right">Revenue</TH><TH align="right">Margin</TH><TH align="right">Margin %</TH><TH align="center">Decile</TH></tr></thead>
              <tbody>
                {[...S.state.clientProfitabilityDecile].sort((a, b) => a.decile - b.decile).map(c => (
                  <tr key={c.client}>
                    <TD bold>{c.client}</TD>
                    <TD align="right" mono>{bl.money(c.revenue)}</TD>
                    <TD align="right" mono bold color={c.marginPct > 30 ? bl.emerald : c.marginPct > 20 ? bl.amber : bl.crimson}>{bl.money(c.margin)}</TD>
                    <TD align="right" mono color={c.marginPct > 30 ? bl.emerald : c.marginPct > 20 ? bl.amber : bl.crimson}>{c.marginPct.toFixed(1)}%</TD>
                    <TD align="center"><Pill bg={c.decile <= 2 ? bl.emerald + '10' : c.decile <= 5 ? bl.amber + '10' : bl.crimsonBg} color={c.decile <= 2 ? bl.emerald : c.decile <= 5 ? bl.amber : bl.crimson}>D{c.decile}</Pill></TD>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    );
  }

  // ════════════════════════════════════════════════════════
  // 15. LATERAL & PARTNER BOOK
  // ════════════════════════════════════════════════════════
  function Ba15LateralBook() {
    useCrossRender(['retention.flagged']);
    const S = window.BillingAnalyticsStore;
    const [flash, setFlash] = useState(null);
    const f = (m) => { setFlash(m); setTimeout(() => setFlash(null), 2000); };

    return (
      <div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: '12px', marginBottom: '16px' }}>
          <div style={bl.stat}><span style={bl.statLabel}>Tracked Partners</span><span style={bl.statValue}>{S.state.partnerBook.length}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Combined Book</span><span style={bl.statValue}>{bl.money(S.state.partnerBook.reduce((s, p) => s + p.bookValue, 0))}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>High Flight Risk</span><span style={{ ...bl.statValue, color: bl.crimson }}>{S.state.partnerBook.filter(p => p.flightRisk > 0.3).length}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Revenue at Risk</span><span style={{ ...bl.statValue, color: bl.crimson }}>{bl.money(S.state.partnerBook.filter(p => p.flightRisk > 0.3).reduce((s, p) => s + p.bookValue, 0))}</span></div>
        </div>

        <Flash msg={flash} />

        <div style={ba.card}>
          <div style={ba.cardH}><span>Partner Book Analytics · flight-risk scoring</span></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><TH>Partner</TH><TH>Practice</TH><TH align="right">Book Value</TH><TH>12-mo Trend</TH><TH align="right">Client Conc.</TH><TH align="right">Origination Decay</TH><TH align="right">Flight Risk</TH><TH align="center">Comp Band</TH><TH align="right"></TH></tr></thead>
            <tbody>
              {S.state.partnerBook.map(p => {
                const trend = p.bookTrend12mo;
                const min = Math.min(...trend);
                const max = Math.max(...trend);
                const range = max - min || 1;
                const growth = ((trend[trend.length - 1] - trend[0]) / trend[0]) * 100;
                return (
                  <tr key={p.partner} style={{ background: p.alert ? bl.crimsonBg : 'transparent' }}>
                    <TD bold>{p.partner}{p.alert && <div style={{ fontSize: '10px', color: bl.crimson, fontWeight: 600, marginTop: '2px' }}>{p.alert}</div>}</TD>
                    <TD color={T.color.text.secondary}>{p.practice}</TD>
                    <TD align="right" mono bold>{bl.money(p.bookValue)}<div style={{ fontSize: '9px', color: growth >= 0 ? bl.emerald : bl.crimson, fontWeight: 600 }}>{growth >= 0 ? '+' : ''}{growth.toFixed(1)}% YoY</div></TD>
                    <TD>
                      <svg width="100" height="24" viewBox="0 0 100 24">
                        <polyline fill="none" stroke={growth >= 0 ? bl.emerald : bl.crimson} strokeWidth="1.5"
                          points={trend.map((v, i) => `${(i / (trend.length - 1)) * 100},${24 - ((v - min) / range) * 22 - 1}`).join(' ')} />
                      </svg>
                    </TD>
                    <TD align="right" mono color={p.clientConcentration > 0.45 ? bl.crimson : p.clientConcentration > 0.35 ? bl.amber : bl.emerald}>{(p.clientConcentration * 100).toFixed(0)}%</TD>
                    <TD align="right" mono color={p.originationDecay > 0.15 ? bl.crimson : p.originationDecay > 0.08 ? bl.amber : bl.emerald}>{(p.originationDecay * 100).toFixed(0)}%</TD>
                    <TD align="right" mono bold color={p.flightRisk > 0.3 ? bl.crimson : p.flightRisk > 0.15 ? bl.amber : bl.emerald}>{(p.flightRisk * 100).toFixed(0)}%</TD>
                    <TD align="center"><Pill bg={T.color.bg.secondary} color={T.color.text.secondary}>{p.compVsPeer}</Pill></TD>
                    <TD align="right">{p.flightRisk > 0.3 && !p.retentionFlag && <button style={{ ...ba.btn, fontSize: '10px', padding: '3px 8px', background: bl.crimson, color: '#fff', borderColor: bl.crimson }} onClick={() => { S.flagPartnerRetention(p.partner, 'High flight risk · schedule retention conversation', 'EC Chair'); f(`${p.partner} flagged for retention review`); }}>Flag</button>}{p.retentionFlag && <Pill bg={bl.amber + '10'} color={bl.amber}>FLAGGED</Pill>}</TD>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    );
  }

  // ════════════════════════════════════════════════════════
  // 16. INDUSTRY BENCHMARK OVERLAY
  // ════════════════════════════════════════════════════════
  function Ba16Benchmark() {
    const S = window.BillingAnalyticsStore;

    return (
      <div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: '12px', marginBottom: '16px' }}>
          <div style={bl.stat}><span style={bl.statLabel}>Metrics Tracked</span><span style={bl.statValue}>{S.state.industryBenchmarks.length}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Above Peer</span><span style={{ ...bl.statValue, color: bl.emerald }}>{S.state.industryBenchmarks.filter(m => m.assessment === 'Above peer').length}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Below Peer</span><span style={{ ...bl.statValue, color: bl.crimson }}>{S.state.industryBenchmarks.filter(m => m.assessment.includes('Below')).length}</span></div>
        </div>

        <div style={ba.card}>
          <div style={ba.cardH}><span>Peer Benchmark · Citi / Wells Fargo / PeerMonitor</span></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><TH>Metric</TH><TH align="right">Firm</TH><TH align="right">Citi</TH><TH align="right">Wells Fargo</TH><TH align="right">PeerMonitor</TH><TH>Peer Band</TH><TH align="center">Assessment</TH></tr></thead>
            <tbody>
              {S.state.industryBenchmarks.map(m => {
                const fmt = (v) => m.metric.includes('PPP') ? bl.money(v) : m.metric.includes('Productivity') || m.metric.includes('Days') ? v.toLocaleString() : m.metric.includes('Margin') || m.metric.includes('Realization') ? `${(v * 100).toFixed(1)}%` : `${v.toFixed(1)}%`;
                const [low, high] = m.peerBand;
                const isAbove = m.firm > high;
                const isBelow = m.firm < low;
                const range = high - low || 1;
                const firmPos = Math.max(0, Math.min(100, ((m.firm - low) / range) * 100));
                return (
                  <tr key={m.metric}>
                    <TD bold>{m.metric}</TD>
                    <TD align="right" mono bold color={isAbove ? bl.emerald : isBelow ? bl.crimson : T.color.text.primary}>{fmt(m.firm)}</TD>
                    <TD align="right" mono color={T.color.text.tertiary}>{fmt(m.citigroup)}</TD>
                    <TD align="right" mono color={T.color.text.tertiary}>{fmt(m.wellsFargo)}</TD>
                    <TD align="right" mono color={T.color.text.tertiary}>{fmt(m.peerMonitor)}</TD>
                    <TD>
                      <div style={{ position: 'relative', height: '18px', background: T.color.bg.secondary, borderRadius: '3px', width: '140px' }}>
                        <div style={{ position: 'absolute', left: '20%', right: '20%', top: 0, bottom: 0, background: bl.emeraldBg, borderRadius: '3px' }} />
                        <div style={{ position: 'absolute', left: `${firmPos * 0.6 + 20}%`, top: '2px', bottom: '2px', width: '3px', background: isAbove ? bl.emerald : isBelow ? bl.crimson : bl.slate }} />
                      </div>
                    </TD>
                    <TD align="center"><Pill bg={isAbove ? bl.emerald + '10' : isBelow ? bl.crimsonBg : T.color.bg.secondary} color={isAbove ? bl.emerald : isBelow ? bl.crimson : T.color.text.secondary}>{m.assessment.toUpperCase()}</Pill></TD>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    );
  }

  // ════════════════════════════════════════════════════════
  // 17. CLIENT CHURN RISK
  // ════════════════════════════════════════════════════════
  function Ba17ChurnRisk() {
    useCrossRender(['churn.response']);
    const S = window.BillingAnalyticsStore;
    const [flash, setFlash] = useState(null);
    const f = (m) => { setFlash(m); setTimeout(() => setFlash(null), 2000); };
    const statusColor = { Healthy: bl.emerald, Watch: bl.amber, 'At Risk': bl.orange, 'High Risk': bl.crimson };

    return (
      <div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: '12px', marginBottom: '16px' }}>
          <div style={bl.stat}><span style={bl.statLabel}>Clients Scored</span><span style={bl.statValue}>{S.state.churnRisk.length}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>At/High Risk</span><span style={{ ...bl.statValue, color: bl.crimson }}>{S.state.churnRisk.filter(c => c.status === 'At Risk' || c.status === 'High Risk').length}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Total Revenue at Risk</span><span style={{ ...bl.statValue, color: bl.crimson }}>{bl.money(S.totalRevenueAtRisk())}</span></div>
          <div style={bl.stat}><span style={bl.statLabel}>Top-5 Concentration</span><span style={bl.statValue}>{[...S.state.churnRisk].sort((a, b) => b.revenue - a.revenue).slice(0, 5).reduce((s, c) => s + c.pctOfBook, 0).toFixed(1)}%</span></div>
        </div>

        <Flash msg={flash} />

        <div style={ba.card}>
          <div style={ba.cardH}><span>Client Churn & Concentration Risk</span></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><TH>Client</TH><TH align="right">Revenue</TH><TH align="right">% of Book</TH><TH align="right">Churn Prob</TH><TH align="right">Revenue at Risk</TH><TH>Signals</TH><TH align="center">Status</TH><TH align="right"></TH></tr></thead>
            <tbody>
              {[...S.state.churnRisk].sort((a, b) => b.churnProb - a.churnProb).map(c => (
                <tr key={c.client}>
                  <TD bold>{c.client}</TD>
                  <TD align="right" mono>{bl.money(c.revenue)}</TD>
                  <TD align="right" mono>{c.pctOfBook.toFixed(1)}%</TD>
                  <TD align="right" mono bold color={c.churnProb > 0.3 ? bl.crimson : c.churnProb > 0.15 ? bl.amber : bl.emerald}>{(c.churnProb * 100).toFixed(0)}%</TD>
                  <TD align="right" mono bold color={bl.crimson}>{bl.money(c.revenueAtRisk)}</TD>
                  <TD><ul style={{ margin: 0, paddingLeft: '14px', fontSize: '10px', color: T.color.text.secondary }}>{c.signals.slice(0, 3).map((s, i) => <li key={i}>{s}</li>)}</ul></TD>
                  <TD align="center"><Pill bg={statusColor[c.status] + '10'} color={statusColor[c.status]}>{c.status.toUpperCase()}</Pill></TD>
                  <TD align="right">{(c.status === 'At Risk' || c.status === 'High Risk') && !c.response && <button style={{ ...ba.btn, fontSize: '10px', padding: '3px 8px', background: bl.crimson, color: '#fff', borderColor: bl.crimson }} onClick={() => { S.triggerChurnResponse(c.client, 'EC retention plan initiated', 'EC Chair'); f(`Retention plan initiated for ${c.client}`); }}>Retain</button>}{c.response && <Pill bg={bl.emerald + '10'} color={bl.emerald}>PLAN ACTIVE</Pill>}</TD>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    );
  }

  // ════════════════════════════════════════════════════════
  // 18. EXECUTIVE WAR ROOM COCKPIT
  // ════════════════════════════════════════════════════════
  function Ba18WarRoom() {
    const S = window.BillingAnalyticsStore;
    const K = S.state.warRoomKPIs;
    const mk = (key, label, fmt, inverse) => {
      const k = K[key];
      if (!k) return null;
      const vsBudget = ((k.value - k.budget) / k.budget) * 100;
      const vsYr = ((k.value - k.priorYr) / k.priorYr) * 100;
      const good = inverse ? k.value < k.budget : k.value >= k.budget;
      const [lo, hi] = k.peerBand;
      const range = hi - lo || 1;
      const firmPos = Math.max(0, Math.min(100, ((k.value - lo) / range) * 100));
      return (
        <div key={key} style={{ padding: '16px', background: T.color.bg.card, border: `1px solid ${T.color.border.light}`, borderRadius: '8px' }}>
          <div style={{ fontSize: '10px', fontWeight: 700, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '4px' }}>{label}</div>
          <div style={{ fontSize: '26px', fontWeight: 700, color: T.color.text.primary, letterSpacing: '-0.02em' }}>{fmt(k.value)}</div>
          <div style={{ display: 'flex', gap: '8px', marginTop: '4px', fontSize: '10px' }}>
            <span style={{ color: good ? bl.emerald : bl.crimson, fontWeight: 600 }}>{vsBudget >= 0 ? '+' : ''}{vsBudget.toFixed(1)}% vs budget</span>
            <span style={{ color: vsYr >= 0 ? bl.emerald : bl.crimson, fontWeight: 600 }}>{vsYr >= 0 ? '+' : ''}{vsYr.toFixed(1)}% vs LY</span>
          </div>
          <div style={{ position: 'relative', height: '14px', background: T.color.bg.secondary, borderRadius: '3px', marginTop: '10px' }}>
            <div style={{ position: 'absolute', left: '20%', right: '20%', top: 0, bottom: 0, background: bl.emeraldBg, borderRadius: '3px' }} />
            <div style={{ position: 'absolute', left: `${firmPos * 0.6 + 20}%`, top: '1px', bottom: '1px', width: '3px', background: ba.violet }} />
          </div>
          <div style={{ fontSize: '9px', color: T.color.text.tertiary, marginTop: '2px', display: 'flex', justifyContent: 'space-between' }}>
            <span>{fmt(lo)}</span><span style={{ color: ba.violet, fontWeight: 700 }}>Firm</span><span>{fmt(hi)}</span>
          </div>
        </div>
      );
    };

    return (
      <div>
        <div style={{ padding: '16px 20px', background: 'linear-gradient(135deg, #0A1628 0%, #1E3A5F 100%)', borderRadius: '12px', marginBottom: '16px' }}>
          <div style={{ fontSize: '10px', fontWeight: 700, color: 'rgba(255,255,255,0.7)', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: '4px' }}>Firm-Level KPI Cockpit · Q2 2026</div>
          <div style={{ fontSize: '22px', fontWeight: 700, color: '#fff', letterSpacing: '-0.02em' }}>Executive War Room</div>
          <div style={{ fontSize: '12px', color: 'rgba(255,255,255,0.7)', marginTop: '2px' }}>Firm vs Budget · vs Prior Year · vs Peer Band (Citi / Wells Fargo / PeerMonitor)</div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: '12px', marginBottom: '16px' }}>
          {mk('realization', 'Collected Realization', v => `${v.toFixed(1)}%`, false)}
          {mk('ube', 'UBE (Util. Billable Eqv.)', v => v.toLocaleString(), false)}
          {mk('arDays', 'AR Days (DSO)', v => `${v}d`, true)}
          {mk('pipeline', 'Pipeline', v => bl.money(v), false)}
          {mk('productivity', 'Productivity', v => `${v.toFixed(1)}%`, false)}
          {mk('utilization', 'Utilization', v => `${v.toFixed(1)}%`, false)}
          {mk('lateralROI', 'Lateral Hire ROI', v => `${v.toFixed(1)}x`, false)}
          {mk('pppGrowth', 'PPP Growth YoY', v => `${v.toFixed(1)}%`, false)}
        </div>

        <div style={{ padding: '14px 18px', background: ba.violetBg, borderRadius: '8px', border: `1px solid ${ba.violetBorder}` }}>
          <div style={{ fontSize: '10px', fontWeight: 700, color: ba.violet, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '6px' }}>Narrative · AI Synthesis</div>
          <div style={{ fontSize: '12px', color: T.color.text.primary, lineHeight: 1.6 }}>
            Firm is tracking <span style={{ fontWeight: 700, color: bl.emerald }}>above peer band</span> on PPP growth (+{K.pppGrowth.value.toFixed(1)}% vs peer median +5.2%) and productivity. Realization of {K.realization.value.toFixed(1)}% is <span style={{ fontWeight: 700 }}>short of {K.realization.budget.toFixed(1)}% budget</span> — driven by {bl.money(8700000)} in pre-bill write-downs (narrative + OCG) and $3.1M in eBilling reductions. AR at {K.arDays.value}d exceeds {K.arDays.budget}d budget; top opportunity is 4 at-risk clients representing {bl.money(S.totalRevenueAtRisk() * 0.6)} in revenue-at-risk. Pipeline is <span style={{ fontWeight: 700, color: bl.emerald }}>+{(((K.pipeline.value - K.pipeline.priorYr) / K.pipeline.priorYr) * 100).toFixed(0)}% vs LY</span>.
          </div>
        </div>
      </div>
    );
  }

  // ════════════════════════════════════════════════════════
  // HUBS — 5 hubs grouping the 18 opportunities
  // ════════════════════════════════════════════════════════

  function BillingCaptureHub() {
    const [tab, setTab] = useState('passive');
    return (
      <div>
        <BaSubTabs active={tab} onChange={setTab} tabs={[
          { id: 'passive', label: 'Passive Time Capture' },
          { id: 'ocg', label: 'OCG Compliance' },
          { id: 'narrative', label: 'Narrative Intelligence' },
        ]} />
        {tab === 'passive' && <Ba1Passive />}
        {tab === 'ocg' && <Ba2OcgCompliance />}
        {tab === 'narrative' && <Ba3Narrative />}
      </div>
    );
  }

  function BillingRateOpsHub() {
    const [tab, setTab] = useState('architect');
    return (
      <div>
        <BaSubTabs active={tab} onChange={setTab} tabs={[
          { id: 'architect', label: 'Rate Card Architect' },
          { id: 'simulator', label: 'Rate Raise Simulator' },
          { id: 'pricing', label: 'Matter Pricing Engine' },
        ]} />
        {tab === 'architect' && <Ba4RateCardArchitect />}
        {tab === 'simulator' && <Ba5RateRaiseSim />}
        {tab === 'pricing' && <Ba6MatterPricing />}
      </div>
    );
  }

  function BillingPreBillHub() {
    const [tab, setTab] = useState('prebill');
    return (
      <div>
        <BaSubTabs active={tab} onChange={setTab} tabs={[
          { id: 'prebill', label: 'Pre-Bill Command Center' },
          { id: 'ebilling', label: 'eBilling Super-Connector' },
          { id: 'joint', label: 'Joint-Rep / Multi-Entity' },
        ]} />
        {tab === 'prebill' && <Ba7PreBill />}
        {tab === 'ebilling' && <Ba8Ebilling />}
        {tab === 'joint' && <Ba9JointRep />}
      </div>
    );
  }

  function BillingCashOpsHub() {
    const [tab, setTab] = useState('ar');
    return (
      <div>
        <BaSubTabs active={tab} onChange={setTab} tabs={[
          { id: 'ar', label: 'AR Intelligence' },
          { id: 'wip', label: 'WIP Risk Map' },
          { id: 'budget', label: 'Budget Pacing' },
        ]} />
        {tab === 'ar' && <Ba10ArIntel />}
        {tab === 'wip' && <Ba11WipRisk />}
        {tab === 'budget' && <Ba12BudgetPacing />}
      </div>
    );
  }

  function BillingExecBIHub() {
    const [tab, setTab] = useState('realization');
    return (
      <div>
        <BaSubTabs active={tab} onChange={setTab} tabs={[
          { id: 'realization', label: 'Realization Waterfall' },
          { id: 'profit', label: 'Matter Profitability' },
          { id: 'lateral', label: 'Lateral & Partner Book' },
          { id: 'benchmark', label: 'Industry Benchmark' },
          { id: 'churn', label: 'Client Churn Risk' },
          { id: 'warroom', label: 'Executive War Room' },
        ]} />
        {tab === 'realization' && <Ba13Realization />}
        {tab === 'profit' && <Ba14Profitability />}
        {tab === 'lateral' && <Ba15LateralBook />}
        {tab === 'benchmark' && <Ba16Benchmark />}
        {tab === 'churn' && <Ba17ChurnRisk />}
        {tab === 'warroom' && <Ba18WarRoom />}
      </div>
    );
  }

  Object.assign(window, {
    BillingCaptureHub, BillingRateOpsHub, BillingPreBillHub, BillingCashOpsHub, BillingExecBIHub,
    Ba1Passive, Ba2OcgCompliance, Ba3Narrative,
    Ba4RateCardArchitect, Ba5RateRaiseSim, Ba6MatterPricing,
    Ba7PreBill, Ba8Ebilling, Ba9JointRep,
    Ba10ArIntel, Ba11WipRisk, Ba12BudgetPacing,
    Ba13Realization, Ba14Profitability, Ba15LateralBook, Ba16Benchmark, Ba17ChurnRisk, Ba18WarRoom,
  });
})();
