// CRIMINAL JUSTICE — PLEA ANALYSIS sub-platform (5 tabs: Dashboard · Offers · Calculator · Comparison · History)
const { useState: useCjPleaState } = React;
const Tpla = window.ArbiterTokens;

function fmtMo(n) { return n == null ? '—' : `${n} mo`; }
function recColor(cj, rec) {
  const v = (rec || '').toLowerCase();
  if (v.startsWith('accept')) return cj.emerald;
  if (v.startsWith('hold') || v.startsWith('contest')) return cj.amber;
  if (v.startsWith('trial')) return cj.burgundy;
  if (v.startsWith('pre-indictment')) return cj.violet;
  return cj.slate;
}

// ── Dashboard ────────────────────────────────────────────────────────────
function CjPleaDashboard({ data }) {
  const cj = window.__cj;
  const offers = data.pleaAnalysis || [];
  const activeOffers = offers.filter(o => o.pleaOffer && !o.pleaOffer.toLowerCase().startsWith('no offer'));
  const withCooperation = offers.filter(o => o.cooperation && !o.cooperation.startsWith('N/A') && !o.cooperation.startsWith('None')).length;
  const totalSavings = offers.reduce((s, o) => s + (o.pleaExpected && o.trialExpected ? o.trialExpected - o.pleaExpected : 0), 0);
  const avgSavingsPct = offers.filter(o => o.pleaExpected && o.trialExpected).reduce((s, o) => s + ((o.trialExpected - o.pleaExpected) / o.trialExpected), 0) / offers.filter(o => o.pleaExpected && o.trialExpected).length * 100;

  const byRec = {};
  offers.forEach(o => {
    const key = (o.ourRecommendation || '').split(' ')[0].replace(/[—:]/g, '');
    byRec[key] = (byRec[key] || 0) + 1;
  });

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={cj.stat}><span style={cj.statLabel}>Active analyses</span><span style={cj.statValue}>{offers.length}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Live offers</span><span style={{ ...cj.statValue, color: cj.burgundy }}>{activeOffers.length}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>W/ cooperation</span><span style={{ ...cj.statValue, color: cj.violet }}>{withCooperation}</span><span style={{ ...cj.statDelta, color: Tpla.color.text.tertiary }}>5K1.1 / Rule 35</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Trial posture</span><span style={{ ...cj.statValue, color: cj.amber }}>{offers.filter(o => (o.ourRecommendation || '').toLowerCase().startsWith('trial')).length}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Total savings</span><span style={{ ...cj.statValue, color: cj.emerald }}>{totalSavings} <span style={{ fontSize: '12px', color: Tpla.color.text.tertiary, fontWeight: 500 }}>mo</span></span><span style={{ ...cj.statDelta, color: Tpla.color.text.tertiary }}>plea vs trial expected</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Avg reduction</span><span style={{ ...cj.statValue, color: cj.emerald }}>{isFinite(avgSavingsPct) ? Math.round(avgSavingsPct) : 0}%</span></div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: '14px', marginBottom: '14px' }}>
        <div style={cj.card}>
          <div style={cj.cardH}>Recommendation breakdown</div>
          <div style={{ padding: '14px 16px' }}>
            {Object.entries(byRec).map(([r, n]) => {
              const color = recColor(cj, r);
              const max = Math.max(...Object.values(byRec), 1);
              return (
                <div key={r} style={{ marginBottom: '10px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
                    <span style={{ fontSize: '11px', fontWeight: 600, color: Tpla.color.text.primary }}>{r}</span>
                    <span style={{ fontSize: '11px', fontFamily: Tpla.font.mono, fontWeight: 700, color }}>{n}</span>
                  </div>
                  <div style={{ height: '6px', background: Tpla.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                    <div style={{ width: `${(n / max) * 100}%`, height: '100%', background: color }} />
                  </div>
                </div>
              );
            })}
            <div style={{ marginTop: '14px', padding: '8px', background: Tpla.color.bg.secondary, borderRadius: '5px', fontSize: '10px', color: Tpla.color.text.tertiary, textAlign: 'center' }}>
              Recommendations based on probability-weighted expected sentences.
            </div>
          </div>
        </div>

        <div style={cj.card}>
          <div style={cj.cardH}>Trial vs plea — expected sentences</div>
          <div style={{ padding: '14px 16px' }}>
            {offers.filter(o => o.pleaExpected != null).map(o => {
              const savingsMo = o.trialExpected - o.pleaExpected;
              const savingsPct = Math.round((savingsMo / o.trialExpected) * 100);
              return (
                <div key={o.defendantId} style={{ marginBottom: '14px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '5px' }}>
                    <span style={{ fontSize: '11px', fontWeight: 600, color: Tpla.color.text.primary }}>{o.defendant}</span>
                    <span style={{ fontSize: '10px', fontFamily: Tpla.font.mono, color: cj.emerald, fontWeight: 700 }}>–{savingsMo} mo · {savingsPct}%</span>
                  </div>
                  <div style={{ display: 'flex', gap: '4px', alignItems: 'center', marginBottom: '3px' }}>
                    <span style={{ fontSize: '10px', width: '46px', color: Tpla.color.text.tertiary, fontFamily: Tpla.font.mono }}>Trial</span>
                    <div style={{ flex: 1, height: '8px', background: Tpla.color.border.light, borderRadius: '4px', overflow: 'hidden' }}>
                      <div style={{ width: '100%', height: '100%', background: cj.burgundy }} />
                    </div>
                    <span style={{ fontSize: '10px', width: '44px', textAlign: 'right', fontFamily: Tpla.font.mono, color: cj.burgundy, fontWeight: 700 }}>{o.trialExpected} mo</span>
                  </div>
                  <div style={{ display: 'flex', gap: '4px', alignItems: 'center' }}>
                    <span style={{ fontSize: '10px', width: '46px', color: Tpla.color.text.tertiary, fontFamily: Tpla.font.mono }}>Plea</span>
                    <div style={{ flex: 1, height: '8px', background: Tpla.color.border.light, borderRadius: '4px', overflow: 'hidden' }}>
                      <div style={{ width: `${(o.pleaExpected / o.trialExpected) * 100}%`, height: '100%', background: cj.emerald }} />
                    </div>
                    <span style={{ fontSize: '10px', width: '44px', textAlign: 'right', fontFamily: Tpla.font.mono, color: cj.emerald, fontWeight: 700 }}>{o.pleaExpected} mo</span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Offers (full table) ─────────────────────────────────────────────────
function CjPleaOffers({ data }) {
  const cj = window.__cj;
  const offers = data.pleaAnalysis || [];
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={cj.stat}><span style={cj.statLabel}>Offers on table</span><span style={{ ...cj.statValue, color: cj.burgundy }}>{offers.filter(o => !o.pleaOffer.toLowerCase().startsWith('no offer')).length}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Decision pending</span><span style={{ ...cj.statValue, color: cj.amber }}>{offers.filter(o => o.daysToDecide && o.daysToDecide > 0).length}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Urgent (&lt;14d)</span><span style={{ ...cj.statValue, color: cj.orange }}>{offers.filter(o => o.daysToDecide && o.daysToDecide <= 14 && o.daysToDecide > 0).length}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Total restitution</span><span style={cj.statValue}>${(offers.reduce((s, o) => s + (o.restitution || 0), 0) / 1_000_000).toFixed(1)}M</span></div>
      </div>

      <div style={cj.card}>
        <div style={cj.cardH}>Plea offers & analysis — {offers.length}</div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={cj.th}>Defendant</th>
              <th style={cj.th}>Trial prob.</th>
              <th style={cj.th}>Trial range / expected</th>
              <th style={cj.th}>Plea offer</th>
              <th style={cj.th}>Plea range / expected</th>
              <th style={cj.th}>Restitution</th>
              <th style={cj.th}>Cooperation</th>
              <th style={{ ...cj.th, textAlign: 'right' }}>Days</th>
              <th style={cj.th}>Recommendation</th>
            </tr>
          </thead>
          <tbody>
            {offers.map(o => {
              const rc = recColor(cj, o.ourRecommendation);
              return (
                <tr key={o.defendantId}>
                  <td style={{ ...cj.td, fontWeight: 600 }}>{o.defendant}<div style={{ fontSize: '10px', color: Tpla.color.text.tertiary, fontFamily: Tpla.font.mono }}>{o.defendantId}</div></td>
                  <td style={cj.td}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                      <div style={{ width: '60px', height: '6px', background: Tpla.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                        <div style={{ width: `${o.trialConvictionProb}%`, height: '100%', background: o.trialConvictionProb > 60 ? cj.burgundy : o.trialConvictionProb > 40 ? cj.amber : cj.emerald }} />
                      </div>
                      <span style={{ fontFamily: Tpla.font.mono, fontSize: '11px', fontWeight: 700 }}>{o.trialConvictionProb}%</span>
                    </div>
                  </td>
                  <td style={{ ...cj.td, fontFamily: Tpla.font.mono, fontSize: '11px' }}>
                    <div style={{ color: Tpla.color.text.secondary }}>{o.trialGuideRange}</div>
                    <div style={{ color: cj.burgundy, fontWeight: 700 }}>Exp: {fmtMo(o.trialExpected)}</div>
                  </td>
                  <td style={{ ...cj.td, fontSize: '11px', color: Tpla.color.text.primary, maxWidth: '260px' }}>{o.pleaOffer}</td>
                  <td style={{ ...cj.td, fontFamily: Tpla.font.mono, fontSize: '11px' }}>
                    <div style={{ color: Tpla.color.text.secondary }}>{o.pleaGuideRange}</div>
                    <div style={{ color: cj.emerald, fontWeight: 700 }}>Exp: {fmtMo(o.pleaExpected)}</div>
                  </td>
                  <td style={{ ...cj.td, fontFamily: Tpla.font.mono, fontSize: '11px', color: o.restitution ? Tpla.color.text.primary : Tpla.color.text.tertiary }}>{o.restitution ? '$' + (o.restitution / 1_000_000).toFixed(1) + 'M' : '—'}</td>
                  <td style={{ ...cj.td, fontSize: '10px', color: Tpla.color.text.secondary, maxWidth: '180px' }}>{o.cooperation}</td>
                  <td style={{ ...cj.td, textAlign: 'right', fontFamily: Tpla.font.mono, color: o.daysToDecide && o.daysToDecide <= 14 ? cj.burgundy : cj.amber, fontWeight: 700 }}>{o.daysToDecide == null ? '—' : o.daysToDecide + 'd'}</td>
                  <td style={{ ...cj.td, fontSize: '11px', color: rc, fontWeight: 600, maxWidth: '260px' }}>{o.ourRecommendation}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ── Calculator (probabilistic scenarios per defendant) ──────────────────
function CjPleaCalculator({ data }) {
  const cj = window.__cj;
  const calcs = data.pleaCalculator || [];
  const [selected, setSelected] = useCjPleaState(calcs[0]?.id || null);
  const current = calcs.find(c => c.id === selected) || calcs[0];
  if (!current) {
    return <div style={{ padding: '40px', textAlign: 'center', color: Tpla.color.text.tertiary, fontSize: '12px' }}>No plea calculator scenarios loaded.</div>;
  }

  const trialScenarios = current.scenarios.filter(s => s.path === 'Trial');
  const pleaScenarios = current.scenarios.filter(s => s.path !== 'Trial');
  const trialProbTotal = trialScenarios.reduce((s, x) => s + x.prob, 0);
  const maxExpected = Math.max(...current.scenarios.map(s => s.expected), 1);

  return (
    <div>
      <div style={cj.card}>
        <div style={cj.cardH}>
          <span>What-if calculator — {current.defendant}</span>
          <select value={selected} onChange={e => setSelected(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tpla.color.border.light}`, borderRadius: '5px', background: Tpla.color.bg.card, color: Tpla.color.text.secondary }}>
            {calcs.map(c => <option key={c.id} value={c.id}>{c.defendant}</option>)}
          </select>
        </div>
        <div style={{ padding: '16px', borderBottom: `1px solid ${Tpla.color.border.light}`, background: Tpla.color.bg.secondary, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px' }}>
          <div><div style={{ fontSize: '9px', fontWeight: 700, color: Tpla.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Expected trial</div><div style={{ fontSize: '20px', fontWeight: 700, color: cj.burgundy, fontFamily: Tpla.font.mono }}>{current.expectedTrial} mo</div></div>
          <div><div style={{ fontSize: '9px', fontWeight: 700, color: Tpla.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Expected plea</div><div style={{ fontSize: '20px', fontWeight: 700, color: cj.emerald, fontFamily: Tpla.font.mono }}>{current.expectedPlea} mo</div></div>
          <div><div style={{ fontSize: '9px', fontWeight: 700, color: Tpla.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Savings</div><div style={{ fontSize: '20px', fontWeight: 700, color: cj.emerald, fontFamily: Tpla.font.mono }}>{current.savings}%</div></div>
          <div><div style={{ fontSize: '9px', fontWeight: 700, color: Tpla.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Decision deadline</div><div style={{ fontSize: '20px', fontWeight: 700, color: cj.amber, fontFamily: Tpla.font.mono }}>{current.decisionDeadline}</div></div>
        </div>
        <div style={{ padding: '14px 16px' }}>
          <div style={{ fontSize: '11px', fontWeight: 700, color: Tpla.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '10px' }}>Trial path scenarios <span style={{ color: cj.burgundy, fontWeight: 700 }}>({trialProbTotal}% cumulative)</span></div>
          <table style={{ width: '100%', borderCollapse: 'collapse', marginBottom: '20px' }}>
            <thead>
              <tr>
                <th style={cj.th}>Outcome</th>
                <th style={{ ...cj.th, textAlign: 'right' }}>Probability</th>
                <th style={{ ...cj.th, textAlign: 'right' }}>Offense lvl</th>
                <th style={cj.th}>Guide range</th>
                <th style={{ ...cj.th, textAlign: 'right' }}>Expected</th>
                <th style={cj.th}>Relative magnitude</th>
              </tr>
            </thead>
            <tbody>
              {trialScenarios.map((s, i) => (
                <tr key={i}>
                  <td style={{ ...cj.td, fontWeight: 600, maxWidth: '320px' }}>{s.label}</td>
                  <td style={{ ...cj.td, textAlign: 'right', fontFamily: Tpla.font.mono, color: cj.burgundy, fontWeight: 700 }}>{s.prob}%</td>
                  <td style={{ ...cj.td, textAlign: 'right', fontFamily: Tpla.font.mono }}>{s.offenseLevel || '—'}</td>
                  <td style={{ ...cj.td, fontFamily: Tpla.font.mono, fontSize: '11px', color: Tpla.color.text.secondary }}>{s.guideRange}</td>
                  <td style={{ ...cj.td, textAlign: 'right', fontFamily: Tpla.font.mono, fontWeight: 700, color: cj.burgundy }}>{fmtMo(s.expected)}</td>
                  <td style={cj.td}>
                    <div style={{ width: '140px', height: '6px', background: Tpla.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                      <div style={{ width: `${(s.expected / maxExpected) * 100}%`, height: '100%', background: cj.burgundy }} />
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>

          <div style={{ fontSize: '11px', fontWeight: 700, color: Tpla.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '10px' }}>Plea path scenarios</div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={cj.th}>Outcome</th>
                <th style={cj.th}>Path</th>
                <th style={{ ...cj.th, textAlign: 'right' }}>Offense lvl</th>
                <th style={cj.th}>Guide range</th>
                <th style={{ ...cj.th, textAlign: 'right' }}>Expected</th>
                <th style={cj.th}>Relative magnitude</th>
              </tr>
            </thead>
            <tbody>
              {pleaScenarios.map((s, i) => (
                <tr key={i}>
                  <td style={{ ...cj.td, fontWeight: 600, maxWidth: '320px' }}>{s.label}</td>
                  <td style={cj.td}><span style={{ ...cj.tag, background: s.path.includes('coop') ? cj.violetBg : cj.emeraldBg, color: s.path.includes('coop') ? cj.violet : cj.emerald }}>{s.path}</span></td>
                  <td style={{ ...cj.td, textAlign: 'right', fontFamily: Tpla.font.mono }}>{s.offenseLevel}</td>
                  <td style={{ ...cj.td, fontFamily: Tpla.font.mono, fontSize: '11px', color: Tpla.color.text.secondary }}>{s.guideRange}</td>
                  <td style={{ ...cj.td, textAlign: 'right', fontFamily: Tpla.font.mono, fontWeight: 700, color: cj.emerald }}>{fmtMo(s.expected)}</td>
                  <td style={cj.td}>
                    <div style={{ width: '140px', height: '6px', background: Tpla.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                      <div style={{ width: `${(s.expected / maxExpected) * 100}%`, height: '100%', background: cj.emerald }} />
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ── Comparison (side-by-side trial vs plea across defendants) ───────────
function CjPleaComparison({ data }) {
  const cj = window.__cj;
  const offers = (data.pleaAnalysis || []).filter(o => o.pleaExpected != null);
  const maxMo = Math.max(...offers.map(o => Math.max(o.trialExpected || 0, o.pleaExpected || 0)), 1);

  return (
    <div style={cj.card}>
      <div style={cj.cardH}>Plea vs trial — probability-adjusted</div>
      <div style={{ padding: '14px 16px' }}>
        {offers.map(o => {
          const savingsMo = o.trialExpected - o.pleaExpected;
          const savingsPct = Math.round((savingsMo / o.trialExpected) * 100);
          return (
            <div key={o.defendantId} style={{ marginBottom: '20px', paddingBottom: '14px', borderBottom: `1px solid ${Tpla.color.border.light}` }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '8px' }}>
                <div>
                  <div style={{ fontSize: '13px', fontWeight: 700, color: Tpla.color.text.primary }}>{o.defendant}</div>
                  <div style={{ fontSize: '10px', color: Tpla.color.text.tertiary, fontFamily: Tpla.font.mono, marginTop: '2px' }}>{o.defendantId} · trial prob {o.trialConvictionProb}%</div>
                </div>
                <div style={{ display: 'flex', gap: '10px' }}>
                  <div style={{ padding: '4px 10px', borderRadius: '5px', background: cj.emeraldBg, border: `1px solid ${cj.emerald}22` }}>
                    <span style={{ fontSize: '9px', fontWeight: 700, color: cj.emerald, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Savings </span>
                    <span style={{ fontSize: '12px', fontWeight: 700, color: cj.emerald, fontFamily: Tpla.font.mono }}>{savingsMo} mo · {savingsPct}%</span>
                  </div>
                  <div style={{ padding: '4px 10px', borderRadius: '5px', background: Tpla.color.bg.secondary, border: `1px solid ${Tpla.color.border.light}` }}>
                    <span style={{ fontSize: '9px', fontWeight: 700, color: Tpla.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Deadline </span>
                    <span style={{ fontSize: '11px', fontWeight: 700, color: cj.amber, fontFamily: Tpla.font.mono }}>{o.daysToDecide == null ? 'N/A' : o.daysToDecide + ' days'}</span>
                  </div>
                </div>
              </div>
              <div style={{ display: 'flex', gap: '6px', alignItems: 'center', marginBottom: '5px' }}>
                <span style={{ fontSize: '10px', width: '60px', color: Tpla.color.text.tertiary, fontFamily: Tpla.font.mono }}>Trial</span>
                <div style={{ flex: 1, height: '16px', background: Tpla.color.border.light, borderRadius: '4px', overflow: 'hidden', display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
                  <div style={{ width: `${(o.trialExpected / maxMo) * 100}%`, height: '100%', background: cj.burgundy, display: 'flex', alignItems: 'center', justifyContent: 'flex-end', paddingRight: '6px' }}>
                    <span style={{ fontSize: '10px', fontFamily: Tpla.font.mono, color: '#fff', fontWeight: 700 }}>{o.trialExpected} mo</span>
                  </div>
                </div>
              </div>
              <div style={{ display: 'flex', gap: '6px', alignItems: 'center' }}>
                <span style={{ fontSize: '10px', width: '60px', color: Tpla.color.text.tertiary, fontFamily: Tpla.font.mono }}>Plea</span>
                <div style={{ flex: 1, height: '16px', background: Tpla.color.border.light, borderRadius: '4px', overflow: 'hidden', display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
                  <div style={{ width: `${(o.pleaExpected / maxMo) * 100}%`, height: '100%', background: cj.emerald, display: 'flex', alignItems: 'center', justifyContent: 'flex-end', paddingRight: '6px' }}>
                    <span style={{ fontSize: '10px', fontFamily: Tpla.font.mono, color: '#fff', fontWeight: 700 }}>{o.pleaExpected} mo</span>
                  </div>
                </div>
              </div>
              <div style={{ marginTop: '6px', fontSize: '11px', color: recColor(cj, o.ourRecommendation), fontStyle: 'italic', fontWeight: 600 }}>→ {o.ourRecommendation}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ── History (firm batting average) ──────────────────────────────────────
function CjPleaHistory({ data }) {
  const cj = window.__cj;
  const history = data.pleaHistory || [];
  const maxOffers = Math.max(...history.map(h => h.offers), 1);
  const totalOffers = history.reduce((s, h) => s + h.offers, 0);
  const totalAccepted = history.reduce((s, h) => s + h.accepted, 0);
  const acceptRate = totalOffers > 0 ? Math.round((totalAccepted / totalOffers) * 100) : 0;
  const avgSavingsMo = Math.round(history.reduce((s, h) => s + h.avgSavingsMo * h.offers, 0) / (totalOffers || 1));

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={cj.stat}><span style={cj.statLabel}>Offers negotiated</span><span style={cj.statValue}>{totalOffers}</span><span style={{ ...cj.statDelta, color: Tpla.color.text.tertiary }}>last 4 years</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Accepted</span><span style={{ ...cj.statValue, color: cj.emerald }}>{totalAccepted}</span><span style={{ ...cj.statDelta, color: Tpla.color.text.tertiary }}>{acceptRate}% rate</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Rejected / trial</span><span style={{ ...cj.statValue, color: cj.burgundy }}>{history.reduce((s, h) => s + h.rejected, 0)}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Avg sentencing savings</span><span style={{ ...cj.statValue, color: cj.emerald }}>{avgSavingsMo} <span style={{ fontSize: '12px', color: Tpla.color.text.tertiary, fontWeight: 500 }}>mo</span></span></div>
      </div>

      <div style={cj.card}>
        <div style={cj.cardH}>Year-over-year plea negotiations</div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={cj.th}>Year</th>
              <th style={{ ...cj.th, textAlign: 'right' }}>Offers</th>
              <th style={{ ...cj.th, textAlign: 'right' }}>Accepted</th>
              <th style={{ ...cj.th, textAlign: 'right' }}>Rejected</th>
              <th style={{ ...cj.th, textAlign: 'right' }}>Pending</th>
              <th style={cj.th}>Accept rate</th>
              <th style={{ ...cj.th, textAlign: 'right' }}>Avg savings</th>
            </tr>
          </thead>
          <tbody>
            {history.map(h => {
              const rate = Math.round((h.accepted / h.offers) * 100);
              return (
                <tr key={h.year}>
                  <td style={{ ...cj.td, fontWeight: 700 }}>{h.year}</td>
                  <td style={{ ...cj.td, textAlign: 'right', fontFamily: Tpla.font.mono, fontWeight: 700 }}>{h.offers}</td>
                  <td style={{ ...cj.td, textAlign: 'right', fontFamily: Tpla.font.mono, color: cj.emerald, fontWeight: 700 }}>{h.accepted}</td>
                  <td style={{ ...cj.td, textAlign: 'right', fontFamily: Tpla.font.mono, color: cj.burgundy, fontWeight: 700 }}>{h.rejected}</td>
                  <td style={{ ...cj.td, textAlign: 'right', fontFamily: Tpla.font.mono, color: cj.amber }}>{h.pending}</td>
                  <td style={cj.td}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                      <div style={{ width: '80px', height: '6px', background: Tpla.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                        <div style={{ width: `${rate}%`, height: '100%', background: cj.emerald }} />
                      </div>
                      <span style={{ fontFamily: Tpla.font.mono, fontSize: '11px', fontWeight: 700, color: cj.emerald }}>{rate}%</span>
                    </div>
                  </td>
                  <td style={{ ...cj.td, textAlign: 'right', fontFamily: Tpla.font.mono, color: cj.emerald, fontWeight: 700 }}>{h.avgSavingsMo} mo</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <div style={cj.card}>
        <div style={cj.cardH}>Offer volume — year over year</div>
        <div style={{ padding: '20px 16px 14px', display: 'flex', gap: '14px', alignItems: 'flex-end', height: '180px' }}>
          {history.map(h => (
            <div key={h.year} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '6px' }}>
              <span style={{ fontSize: '11px', fontFamily: Tpla.font.mono, fontWeight: 700, color: cj.burgundy }}>{h.offers}</span>
              <div style={{ width: '100%', height: '120px', display: 'flex', alignItems: 'flex-end', justifyContent: 'center', gap: '4px' }}>
                <div title={`Accepted: ${h.accepted}`} style={{ width: '35%', height: `${(h.accepted / maxOffers) * 100}%`, background: cj.emerald, borderRadius: '2px 2px 0 0' }} />
                <div title={`Rejected: ${h.rejected}`} style={{ width: '35%', height: `${(h.rejected / maxOffers) * 100}%`, background: cj.burgundy, borderRadius: '2px 2px 0 0' }} />
                <div title={`Pending: ${h.pending}`} style={{ width: '35%', height: `${(h.pending / maxOffers) * 100}%`, background: cj.amber, borderRadius: '2px 2px 0 0' }} />
              </div>
              <span style={{ fontSize: '10px', color: Tpla.color.text.tertiary, fontFamily: Tpla.font.mono }}>{h.year}</span>
            </div>
          ))}
        </div>
        <div style={{ padding: '10px 16px', display: 'flex', gap: '16px', justifyContent: 'center', fontSize: '10px', borderTop: `1px solid ${Tpla.color.border.light}` }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: '5px' }}><span style={{ width: '8px', height: '8px', background: cj.emerald, borderRadius: '2px' }} /> Accepted</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: '5px' }}><span style={{ width: '8px', height: '8px', background: cj.burgundy, borderRadius: '2px' }} /> Rejected / trial</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: '5px' }}><span style={{ width: '8px', height: '8px', background: cj.amber, borderRadius: '2px' }} /> Pending</span>
        </div>
      </div>
    </div>
  );
}

// ── Platform entry ──────────────────────────────────────────────────────
function CriminalPleaPlatform({ data }) {
  const [subTab, setSubTab] = useCjPleaState('dashboard');
  const cj = window.__cj;

  const subTabs = [
    { id: 'dashboard',  label: 'Dashboard' },
    { id: 'offers',     label: 'Offers' },
    { id: 'calculator', label: 'Calculator' },
    { id: 'comparison', label: 'Comparison' },
    { id: 'history',    label: 'History' },
  ];

  const renderSub = () => {
    switch (subTab) {
      case 'dashboard':  return <CjPleaDashboard  data={data} />;
      case 'offers':     return <CjPleaOffers     data={data} />;
      case 'calculator': return <CjPleaCalculator data={data} />;
      case 'comparison': return <CjPleaComparison data={data} />;
      case 'history':    return <CjPleaHistory    data={data} />;
      default:           return <CjPleaDashboard  data={data} />;
    }
  };

  return (
    <div>
      <div style={{ display: 'flex', gap: '0', borderBottom: `1px solid ${Tpla.color.border.light}`, marginBottom: '16px' }}>
        {subTabs.map(t => {
          const active = subTab === t.id;
          return (
            <button key={t.id} onClick={() => setSubTab(t.id)}
              style={{
                padding: '8px 14px', fontSize: '11px', fontWeight: active ? 600 : 500,
                color: active ? cj.burgundy : Tpla.color.text.tertiary,
                background: 'none',
                borderTop: 'none', borderLeft: 'none', borderRight: 'none',
                borderBottom: `2px solid ${active ? cj.burgundy : 'transparent'}`,
                cursor: 'pointer', fontFamily: Tpla.font.family,
                marginBottom: '-1px', transition: 'color 0.15s',
              }}>
              {t.label}
            </button>
          );
        })}
      </div>
      {renderSub()}
    </div>
  );
}

window.CriminalPleaPlatform = CriminalPleaPlatform;
