// CRIMINAL JUSTICE PLATFORM — Charges + Bail
const Tcjc = window.ArbiterTokens;

function CriminalCharges({ data }) {
  const cj = window.__cj;
  // Count by class
  const byClass = {};
  data.charges.forEach(c => { byClass[c.class] = (byClass[c.class] || 0) + 1; });
  const mandMinCount = data.charges.filter(c => c.mandMin > 0).length;
  const convicted = data.charges.filter(c => c.status.startsWith('Convicted')).length;

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={cj.stat}><span style={cj.statLabel}>Total counts</span><span style={cj.statValue}>{data.charges.length}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Class B felonies</span><span style={{ ...cj.statValue, color: cj.burgundy }}>{byClass['B'] || 0}</span><span style={{ ...cj.statDelta, color: Tcjc.color.text.tertiary }}>25y-life range</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Class C felonies</span><span style={{ ...cj.statValue, color: cj.orange }}>{byClass['C'] || 0}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>With mandatory min</span><span style={{ ...cj.statValue, color: cj.burgundy }}>{mandMinCount}</span><span style={{ ...cj.statDelta, color: Tcjc.color.text.tertiary }}>safety-valve eligible?</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Active counts</span><span style={cj.statValue}>{data.charges.filter(c => c.status === 'Active').length}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Convicted</span><span style={{ ...cj.statValue, color: cj.emerald }}>{convicted}</span><span style={{ ...cj.statDelta, color: Tcjc.color.text.tertiary }}>resolved</span></div>
      </div>

      <div style={cj.card}>
        <div style={cj.cardH}>
          <span>Charges · per-count detail</span>
          <button style={cj.btnSecondary}>Export to sentencing prep</button>
        </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}>USSG level</th>
              <th style={cj.th}>Status</th>
            </tr>
          </thead>
          <tbody>
            {data.charges.map(c => {
              const cc = cj.classColor(c.class);
              const statusColor = c.status === 'Active' ? { bg: cj.cobaltBg, color: cj.cobalt }
                : c.status.startsWith('Convicted') ? { bg: cj.burgundyBg, color: cj.burgundy }
                : { bg: Tcjc.color.bg.secondary, color: Tcjc.color.text.secondary };
              return (
                <tr key={c.id}>
                  <td style={{ ...cj.td, fontFamily: Tcjc.font.mono, color: cj.burgundy, fontWeight: 700 }}>#{c.count}</td>
                  <td style={{ ...cj.td, color: Tcjc.color.text.primary, fontWeight: 500, maxWidth: '180px' }}>{c.defendant}</td>
                  <td style={{ ...cj.td, fontFamily: Tcjc.font.mono, fontSize: '11px', color: cj.burgundy, fontWeight: 700 }}>{c.statute}</td>
                  <td style={{ ...cj.td, fontWeight: 500, color: Tcjc.color.text.primary, maxWidth: '260px' }}>
                    {c.title}
                    {c.note && <div style={{ fontSize: '10px', color: cj.amber, marginTop: '3px', fontStyle: 'italic' }}>flag {c.note}</div>}
                  </td>
                  <td style={cj.td}><span style={{ ...cj.tag, background: cc.bg, color: cc.color }}>{c.class}</span></td>
                  <td style={{ ...cj.td, textAlign: 'right', fontFamily: Tcjc.font.mono, fontWeight: 700, color: c.mandMin > 0 ? cj.burgundy : Tcjc.color.text.tertiary }}>{c.mandMin > 0 ? `${c.mandMin} mo` : '—'}</td>
                  <td style={{ ...cj.td, textAlign: 'right', fontFamily: Tcjc.font.mono, color: Tcjc.color.text.primary, fontWeight: 700 }}>{c.statMax === 'life' ? 'life' : `${c.statMax} mo`}</td>
                  <td style={{ ...cj.td, textAlign: 'right', fontFamily: Tcjc.font.mono, color: Tcjc.color.text.secondary, fontSize: '11px' }}>${(c.fineMax / 1000).toFixed(0)}K</td>
                  <td style={{ ...cj.td, textAlign: 'center', fontFamily: Tcjc.font.mono, color: cj.cobalt, fontWeight: 700 }}>{c.trackedOffenseLevel != null ? `Lvl ${c.trackedOffenseLevel}` : '—'}</td>
                  <td style={cj.td}><span style={{ ...cj.tag, background: statusColor.bg, color: statusColor.color }}>{c.status}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {/* Class legend */}
      <div style={{ ...cj.card, padding: '10px 16px' }}>
        <div style={{ fontSize: '10px', fontWeight: 700, color: Tcjc.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '8px' }}>Felony class reference — 18 U.S.C. § 3559</div>
        <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
          {['A','B','C','D','E','Misd'].map(cls => {
            const cc = cj.classColor(cls);
            return <span key={cls} style={{ ...cj.pill, background: cc.bg, color: cc.color, padding: '3px 10px' }}><b>{cls}</b> — {cc.label}</span>;
          })}
        </div>
      </div>
    </div>
  );
}

function CriminalBail({ data }) {
  const cj = window.__cj;
  const totalBond = data.bail.reduce((s, b) => s + (b.amount || 0), 0);
  const detained = data.bail.filter(b => b.status === 'Detained').length;
  const appealing = data.bail.filter(b => b.appealed).length;

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={cj.stat}><span style={cj.statLabel}>Defendants tracked</span><span style={cj.statValue}>{data.bail.length}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Detained</span><span style={{ ...cj.statValue, color: cj.burgundy }}>{detained}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Total bond aggregate</span><span style={{ ...cj.statValue, color: cj.emerald }}>${(totalBond / 1_000_000).toFixed(1)}M</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Avg bond</span><span style={cj.statValue}>${Math.round(totalBond / data.bail.filter(b => b.amount).length / 1_000_000 * 10) / 10}M</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Appeals pending</span><span style={{ ...cj.statValue, color: cj.amber }}>{appealing}</span></div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(440px, 1fr))', gap: '14px' }}>
        {data.bail.map(b => {
          const def = data.defendants.find(d => d.id === b.defendantId);
          const bc = cj.bailColor(b.status);
          return (
            <div key={b.defendantId} style={{ ...cj.card, marginBottom: 0 }}>
              <div style={{ padding: '12px 14px', borderBottom: `1px solid ${Tcjc.color.border.light}`, background: `linear-gradient(135deg, ${bc.bg} 0%, transparent 100%)` }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
                  <span style={{ fontSize: '13px', fontWeight: 700, color: Tcjc.color.text.primary }}>{def?.name}</span>
                  <span style={{ ...cj.tag, background: bc.bg, color: bc.color, fontSize: '11px', padding: '3px 10px' }}>{b.status}</span>
                </div>
                <div style={{ fontSize: '10px', color: Tcjc.color.text.tertiary, fontFamily: Tcjc.font.mono }}>{def?.docket}</div>
              </div>
              <div style={{ padding: '12px 14px' }}>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '10px', marginBottom: '12px' }}>
                  <div>
                    <div style={{ fontSize: '9px', color: Tcjc.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Bond</div>
                    <div style={{ fontSize: '14px', fontWeight: 700, color: b.amount ? cj.emerald : Tcjc.color.text.tertiary, fontFamily: Tcjc.font.mono }}>{b.amount ? `$${(b.amount / 1_000_000).toFixed(2)}M` : '—'}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: '9px', color: Tcjc.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Cosigners</div>
                    <div style={{ fontSize: '14px', fontWeight: 700, color: Tcjc.color.text.primary, fontFamily: Tcjc.font.mono }}>{b.cosigners}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: '9px', color: Tcjc.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Appeal</div>
                    <div style={{ fontSize: '14px', fontWeight: 700, color: b.appealed ? cj.amber : Tcjc.color.text.tertiary, fontFamily: Tcjc.font.mono }}>{b.appealed ? 'Yes' : 'No'}</div>
                  </div>
                </div>
                <div style={{ fontSize: '9px', color: Tcjc.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>Conditions</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px', marginBottom: '10px' }}>
                  {b.conditions.map(c => <span key={c} style={{ ...cj.tag, background: Tcjc.color.bg.secondary, color: Tcjc.color.text.secondary }}>{c}</span>)}
                </div>
                <div style={{ fontSize: '10px', color: Tcjc.color.text.tertiary, paddingTop: '8px', borderTop: `1px solid ${Tcjc.color.border.light}`, display: 'flex', justifyContent: 'space-between' }}>
                  <span>{b.setBy} · heard {b.heardOn}</span>
                  {b.appealOutcome && <span style={{ color: cj.amber, fontWeight: 600 }}>{b.appealOutcome}</span>}
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

window.CriminalCharges = CriminalCharges;
window.CriminalBail = CriminalBail;
