// CRIMINAL CHARGES PLATFORM — Views + Entry
const { useState: useCCState } = React;
const Tcc = window.ArbiterTokens;

function ChargesOverview({ data }) {
  const cj = window.__cj;
  const charges = data.charges;
  const byClass = charges.reduce((a, c) => { a[c.class] = (a[c.class]||0)+1; return a; }, {});
  const mandMin = charges.filter(c => c.mandMin > 0);
  const statMaxNums = charges.map(c => c.statMax === 'life' ? 999 : Number(c.statMax));
  const totalMaxExposure = statMaxNums.reduce((s, v) => s + v, 0);
  const byDef = charges.reduce((a, c) => { a[c.defendant] = (a[c.defendant]||0)+1; return a; }, {});

  return (
    <div>
      <div style={{ ...cj.card, borderLeft: `3px solid ${cj.burgundy}`, background: cj.burgundyBg, marginBottom: '14px' }}>
        <div style={{ padding: '14px 16px' }}>
          <div style={{ fontSize: '13px', fontWeight: 700, color: cj.burgundy, textTransform: 'uppercase', letterSpacing: '0.08em' }}> Charges Registry — 18 U.S.C. § 3559 · USSG Chapter 2</div>
          <div style={{ fontSize: '12px', color: Tcc.color.text.secondary, marginTop: '6px', lineHeight: 1.55 }}>
            <b style={{ color: Tcc.color.text.primary }}>{charges.length} counts</b> across <b>{Object.keys(byDef).length} defendants</b>.{' '}
            <b style={{ color: cj.burgundy }}>{mandMin.length} counts carry mandatory minimums.</b>{' '}
            Aggregate statutory maximum exposure: <b style={{ color: Tcc.color.text.primary }}>{(totalMaxExposure/12).toFixed(0)} years</b> (excluding life).
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: '10px', marginBottom: '14px' }}>
        {[
          { l: 'Total counts', v: charges.length, c: null },
          { l: 'Active', v: charges.filter(c=>c.status==='Active').length, c: cj.cobalt },
          { l: 'Convicted', v: charges.filter(c=>c.status.startsWith('Convicted')).length, c: cj.burgundy },
          { l: 'Mandatory mins', v: mandMin.length, c: cj.burgundy },
          { l: 'Life eligible', v: charges.filter(c=>c.statMax==='life').length, c: cj.burgundy },
          { l: 'Defendants charged', v: Object.keys(byDef).length, c: null },
        ].map(s => (
          <div key={s.l} style={cj.stat}>
            <span style={cj.statLabel}>{s.l}</span>
            <span style={{ ...cj.statValue, color: s.c || Tcc.color.text.primary }}>{s.v}</span>
          </div>
        ))}
      </div>

      {/* By defendant exposure bars */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px', marginBottom: '14px' }}>
        <div style={cj.card}>
          <div style={cj.cardH}>Counts by defendant</div>
          <div style={{ padding: '14px 16px' }}>
            {Object.entries(byDef).map(([def, cnt]) => {
              const def_ = data.defendants.find(d => d.name === def);
              const maxExp = charges.filter(c=>c.defendant===def).reduce((s,c) => s + (c.statMax==='life'?999:Number(c.statMax)), 0);
              return (
                <div key={def} style={{ marginBottom: '10px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', marginBottom: '3px' }}>
                    <span style={{ color: Tcc.color.text.primary, fontWeight: 500 }}>{def}</span>
                    <span style={{ fontFamily: Tcc.font.mono, color: cj.burgundy, fontWeight: 700 }}>{cnt} count{cnt>1?'s':''} · {maxExp===999?'life':maxExp+'mo'} max</span>
                  </div>
                  <div style={{ height: '8px', background: Tcc.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                    <div style={{ width: `${Math.min(100,(maxExp/300)*100)}%`, height: '100%', background: `linear-gradient(90deg, ${cj.burgundy}, ${cj.orange})` }} />
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        <div style={cj.card}>
          <div style={cj.cardH}>Felony class breakdown — 18 U.S.C. § 3559</div>
          <div style={{ padding: '14px 16px' }}>
            {['A','B','C','D','E'].map(cls => {
              const cc = cj.classColor(cls);
              const cnt = byClass[cls] || 0;
              return cnt > 0 ? (
                <div key={cls} style={{ marginBottom: '10px', display: 'flex', alignItems: 'center', gap: '10px' }}>
                  <span style={{ ...cj.tag, background: cc.bg, color: cc.color, minWidth: '28px', textAlign: 'center', fontWeight: 700 }}>{cls}</span>
                  <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', marginBottom: '3px' }}>
                      <span style={{ color: Tcc.color.text.secondary }}>{cc.label}</span>
                      <span style={{ fontFamily: Tcc.font.mono, fontWeight: 700, color: cc.color }}>{cnt}</span>
                    </div>
                    <div style={{ height: '6px', background: Tcc.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                      <div style={{ width: `${(cnt / charges.length)*100}%`, height: '100%', background: cc.color }} />
                    </div>
                  </div>
                </div>
              ) : null;
            })}
          </div>
        </div>
      </div>

      {/* Mandatory minimums alert */}
      {mandMin.length > 0 && (
        <div style={{ ...cj.card, borderLeft: `3px solid ${cj.burgundy}` }}>
          <div style={cj.cardH}>flag Mandatory minimum counts — safety-valve eligibility tracker</div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr>
              <th style={cj.th}>Count</th><th style={cj.th}>Defendant</th><th style={cj.th}>Statute</th>
              <th style={cj.th}>Offense</th><th style={{ ...cj.th, textAlign: 'right' }}>Mand. Min</th><th style={cj.th}>Safety-valve?</th><th style={cj.th}>Note</th>
            </tr></thead>
            <tbody>
              {mandMin.map(c => (
                <tr key={c.id}>
                  <td style={{ ...cj.td, fontFamily: Tcc.font.mono, color: cj.burgundy, fontWeight: 700 }}>#{c.count}</td>
                  <td style={{ ...cj.td, fontWeight: 500 }}>{c.defendant}</td>
                  <td style={{ ...cj.td, fontFamily: Tcc.font.mono, fontSize: '11px', color: cj.burgundy }}>{c.statute}</td>
                  <td style={{ ...cj.td, fontSize: '11px' }}>{c.title}</td>
                  <td style={{ ...cj.td, textAlign: 'right', fontFamily: Tcc.font.mono, fontWeight: 700, color: cj.burgundy }}>{c.mandMin} mo</td>
                  <td style={cj.td}><span style={{ ...cj.tag, background: c.statute.includes('841') ? cj.amberBg : cj.orangeBg, color: c.statute.includes('841') ? cj.amber : cj.orange }}>{c.statute.includes('841') ? 'Possible' : 'No'}</span></td>
                  <td style={{ ...cj.td, fontSize: '11px', color: Tcc.color.text.secondary }}>{c.note || '—'}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

function ChargesRegistry({ data }) {
  const cj = window.__cj;
  const [defFilter, setDefFilter] = useCCState('All');
  const [statusFilter, setStatusFilter] = useCCState('All');
  const [selected, setSelected] = useCCState(null);
  const defs = ['All', ...new Set(data.charges.map(c => c.defendant))];
  const statuses = ['All', 'Active', 'Convicted', 'Convicted (plea)'];
  const rows = data.charges.filter(c =>
    (defFilter === 'All' || c.defendant === defFilter) &&
    (statusFilter === 'All' || c.status === statusFilter)
  );

  return (
    <div>
      <div style={cj.card}>
        <div style={cj.cardH}>
          <span>Per-count registry — {rows.length} counts</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <select value={defFilter} onChange={e=>setDefFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tcc.color.border.light}`, borderRadius: '5px', background: Tcc.color.bg.card, color: Tcc.color.text.secondary }}>
              {defs.map(d => <option key={d} value={d}>Defendant: {d==='All'?'All':d.split(' ')[1]}</option>)}
            </select>
            <select value={statusFilter} onChange={e=>setStatusFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tcc.color.border.light}`, borderRadius: '5px', background: Tcc.color.bg.card, color: Tcc.color.text.secondary }}>
              {statuses.map(s => <option key={s} value={s}>Status: {s}</option>)}
            </select>
            <button style={cj.btnSecondary}>Export to sentencing</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr>
            <th style={cj.th}>Count</th><th style={cj.th}>Defendant</th><th style={cj.th}>Statute</th>
            <th style={cj.th}>Title</th><th style={cj.th}>Class</th>
            <th style={{ ...cj.th, textAlign: 'right' }}>Mand Min</th>
            <th style={{ ...cj.th, textAlign: 'right' }}>Stat Max</th>
            <th style={{ ...cj.th, textAlign: 'right' }}>Max Fine</th>
            <th style={{ ...cj.th, textAlign: 'center' }}>USSG Lvl</th>
            <th style={cj.th}>Status</th><th style={cj.th}></th>
          </tr></thead>
          <tbody>
            {rows.map(c => {
              const cc = cj.classColor(c.class);
              const sc = c.status==='Active' ? { bg: cj.cobaltBg, color: cj.cobalt }
                : c.status.startsWith('Convicted') ? { bg: cj.burgundyBg, color: cj.burgundy }
                : { bg: Tcc.color.bg.secondary, color: Tcc.color.text.secondary };
              const isSel = selected === c.id;
              return (
                <React.Fragment key={c.id}>
                  <tr onClick={() => setSelected(isSel ? null : c.id)} style={{ cursor: 'pointer', background: isSel ? cj.burgundyBg : 'transparent' }}>
                    <td style={{ ...cj.td, fontFamily: Tcc.font.mono, color: cj.burgundy, fontWeight: 700 }}>#{c.count}</td>
                    <td style={{ ...cj.td, fontWeight: 500, color: Tcc.color.text.primary }}>{c.defendant}</td>
                    <td style={{ ...cj.td, fontFamily: Tcc.font.mono, fontSize: '11px', color: cj.burgundy, fontWeight: 700 }}>{c.statute}</td>
                    <td style={{ ...cj.td, fontWeight: 500, color: Tcc.color.text.primary, maxWidth: '240px' }}>
                      {c.title}
                      {c.note && <div style={{ fontSize: '10px', color: cj.amber, marginTop: '2px' }}>flag {c.note}</div>}
                    </td>
                    <td style={cj.td}><span style={{ ...cj.tag, background: cc.bg, color: cc.color, fontWeight: 700 }}>{c.class}</span></td>
                    <td style={{ ...cj.td, textAlign: 'right', fontFamily: Tcc.font.mono, fontWeight: 700, color: c.mandMin > 0 ? cj.burgundy : Tcc.color.text.tertiary }}>{c.mandMin > 0 ? `${c.mandMin} mo` : '—'}</td>
                    <td style={{ ...cj.td, textAlign: 'right', fontFamily: Tcc.font.mono, fontWeight: 700 }}>{c.statMax === 'life' ? <span style={{ color: cj.burgundy }}>life</span> : `${c.statMax} mo`}</td>
                    <td style={{ ...cj.td, textAlign: 'right', fontFamily: Tcc.font.mono, fontSize: '11px', color: Tcc.color.text.secondary }}>${(c.fineMax/1000).toFixed(0)}K</td>
                    <td style={{ ...cj.td, textAlign: 'center', fontFamily: Tcc.font.mono, color: cj.cobalt, fontWeight: 700 }}>{c.trackedOffenseLevel != null ? `${c.trackedOffenseLevel}` : '—'}</td>
                    <td style={cj.td}><span style={{ ...cj.tag, background: sc.bg, color: sc.color }}>{c.status}</span></td>
                    <td style={{ ...cj.td, fontSize: '11px', color: cj.burgundy, fontWeight: 600 }}>{isSel ? '−' : '+'}</td>
                  </tr>
                  {isSel && (
                    <tr><td colSpan={11} style={{ padding: 0, background: cj.burgundyBg }}>
                      <div style={{ padding: '12px 20px', borderTop: `1px solid ${cj.burgundy}33` }}>
                        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '14px' }}>
                          <div><div style={{ fontSize: '10px', fontWeight: 700, color: Tcc.color.text.tertiary, textTransform: 'uppercase', marginBottom: '4px' }}>Statute</div><div style={{ fontFamily: Tcc.font.mono, fontSize: '12px', color: cj.burgundy, fontWeight: 700 }}>{c.statute}</div></div>
                          <div><div style={{ fontSize: '10px', fontWeight: 700, color: Tcc.color.text.tertiary, textTransform: 'uppercase', marginBottom: '4px' }}>USSG Offense Level</div><div style={{ fontFamily: Tcc.font.mono, fontSize: '20px', fontWeight: 700, color: cj.cobalt }}>{c.trackedOffenseLevel ?? 'N/A'}</div></div>
                          <div><div style={{ fontSize: '10px', fontWeight: 700, color: Tcc.color.text.tertiary, textTransform: 'uppercase', marginBottom: '4px' }}>Statutory Range</div><div style={{ fontFamily: Tcc.font.mono, fontSize: '12px', fontWeight: 700 }}>{c.mandMin > 0 ? `${c.mandMin} mo min` : 'No mandatory min'} → {c.statMax === 'life' ? 'life' : `${c.statMax} mo`}</div></div>
                          <div><div style={{ fontSize: '10px', fontWeight: 700, color: Tcc.color.text.tertiary, textTransform: 'uppercase', marginBottom: '4px' }}>Max Fine</div><div style={{ fontFamily: Tcc.font.mono, fontSize: '14px', fontWeight: 700 }}>${(c.fineMax/1_000_000).toFixed(2)}M</div></div>
                        </div>
                      </div>
                    </td></tr>
                  )}
                </React.Fragment>
              );
            })}
          </tbody>
        </table>
        <div style={{ padding: '10px 16px', borderTop: `1px solid ${Tcc.color.border.light}` }}>
          <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
            {['A','B','C','D','E'].map(cls => { const cc = cj.classColor(cls); return <span key={cls} style={{ ...cj.tag, background: cc.bg, color: cc.color }}><b>{cls}</b> — {cc.label}</span>; })}
          </div>
        </div>
      </div>
    </div>
  );
}

function ChargesExposure({ data }) {
  const cj = window.__cj;
  const defData = data.defendants.filter(d => d.stage !== 'Post-Conviction');
  return (
    <div>
      <div style={{ ...cj.card, borderLeft: `3px solid ${cj.cobalt}`, background: cj.cobaltBg, marginBottom: '14px' }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: cj.cobalt, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Statutory vs. Guideline Exposure — per-defendant probability-adjusted analysis</div>
          <div style={{ fontSize: '11px', color: Tcc.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>Each bar shows statutory max (outer) vs. USSG guideline range (inner). Guideline range controls in most cases under Booker advisory framework.</div>
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
        {defData.map(d => {
          const defCharges = data.charges.filter(c => c.defendantId === d.id);
          if (!defCharges.length) return null;
          const guide = d.guideRange.split(' ')[0].split('-');
          const guideLow = guide[0] ? parseInt(guide[0]) : 0;
          const guideHigh = guide[1] ? parseInt(guide[1]) : guideLow;
          const statMax = defCharges.reduce((s,c) => {
            if (c.statMax === 'life') return s + 999;
            return s + Number(c.statMax);
          }, 0);
          const maxDisplay = Math.min(statMax, 360);
          const stageC = d.stage === 'Trial' ? cj.burgundy : d.stage === 'Sentencing' ? cj.orange : d.stage === 'Plea Negotiations' ? cj.amber : cj.cobalt;
          return (
            <div key={d.id} style={{ ...cj.card, marginBottom: 0 }}>
              <div style={{ padding: '12px 16px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '10px' }}>
                  <div>
                    <div style={{ fontSize: '13px', fontWeight: 700, color: Tcc.color.text.primary }}>{d.name}</div>
                    <div style={{ fontSize: '11px', color: Tcc.color.text.tertiary }}>{d.leadCount}</div>
                  </div>
                  <div style={{ display: 'flex', gap: '6px', alignItems: 'center' }}>
                    <span style={{ ...cj.tag, background: `${stageC}14`, color: stageC }}>{d.stage}</span>
                    <span style={{ ...cj.tag, background: cj.cobaltBg, color: cj.cobalt }}>USSG {d.guideRange}</span>
                    {d.guideRange !== 'Pre-charge' && <span style={{ ...cj.tag, background: cj.burgundyBg, color: cj.burgundy }}>Stat max {statMax >= 999 ? 'life' : statMax + 'mo'}</span>}
                  </div>
                </div>
                {d.guideRange !== 'Pre-charge' && (
                  <div style={{ position: 'relative', height: '28px', background: Tcc.color.border.light, borderRadius: '4px', overflow: 'hidden' }}>
                    {/* Stat max bar */}
                    <div style={{ position: 'absolute', top: 0, left: 0, height: '100%', width: `${Math.min(100,(maxDisplay/360)*100)}%`, background: `${cj.burgundy}22`, borderRadius: '4px' }} />
                    {/* Guideline range */}
                    <div style={{ position: 'absolute', top: '6px', left: `${(guideLow/360)*100}%`, height: '16px', width: `${((guideHigh-guideLow)/360)*100}%`, background: cj.cobalt, borderRadius: '3px', minWidth: '4px' }} />
                    <div style={{ position: 'absolute', top: '7px', left: '8px', fontSize: '10px', color: Tcc.color.text.tertiary, fontFamily: Tcc.font.mono }}>0</div>
                    <div style={{ position: 'absolute', top: '7px', right: '8px', fontSize: '10px', color: cj.burgundy, fontFamily: Tcc.font.mono, fontWeight: 700 }}>{statMax >= 999 ? 'life' : `${statMax}mo`}</div>
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function CriminalChargesPlatform({ data }) {
  const cj = window.__cj;
  const [activeView, setActiveView] = useCCState('overview');
  const views = [
    { id: 'overview',  label: 'Overview' },
    { id: 'registry',  label: 'Count Registry' },
    { id: 'exposure',  label: 'Exposure Analysis' },
  ];
  const render = () => {
    switch (activeView) {
      case 'overview': return <ChargesOverview data={data} />;
      case 'registry': return <ChargesRegistry data={data} />;
      case 'exposure': return <ChargesExposure data={data} />;
      default:         return <ChargesOverview data={data} />;
    }
  };
  return (
    <div>
      <div style={{ display: 'flex', gap: '4px', padding: '5px', background: Tcc.color.bg.secondary, border: `1px solid ${Tcc.color.border.light}`, borderRadius: '8px', marginBottom: '16px' }}>
        {views.map(v => (
          <button key={v.id} onClick={() => setActiveView(v.id)} style={{
            padding: '6px 14px', fontSize: '11px', fontWeight: activeView===v.id ? 700 : 500,
            borderRadius: '6px', border: 'none', cursor: 'pointer',
            background: activeView===v.id ? cj.burgundy : 'transparent',
            color: activeView===v.id ? '#fff' : Tcc.color.text.secondary,
            fontFamily: Tcc.font.family, transition: 'all .15s',
          }}>{v.label}</button>
        ))}
      </div>
      {render()}
    </div>
  );
}

window.CriminalChargesPlatform = CriminalChargesPlatform;
