// CRIMINAL JUSTICE PLATFORM — Dashboard + Defendants
const { useState: useCjDashState, useMemo: useCjDashMemo } = React;
const Tcjd = window.ArbiterTokens;

function CriminalDashboard({ data }) {
  const cj = window.__cj;
  const k = data.kpis;

  // Stage distribution
  const stageCounts = {};
  data.defendants.forEach(d => { stageCounts[d.stage] = (stageCounts[d.stage] || 0) + 1; });
  const stageOrder = ['Investigation','Pretrial','Plea Negotiations','Trial','Sentencing','Post-Conviction'];

  // Upcoming hearings in next 30 days
  const upcoming = [...data.hearings].sort((a, b) => a.date.localeCompare(b.date)).slice(0, 6);

  // Exposure summary — total potential months if convicted on top counts
  const totalExposure = data.defendants.filter(d => d.guideRange !== 'Pre-charge').length;

  const urgencyColor = (u) => u === 'critical' ? cj.burgundy : u === 'high' ? cj.orange : u === 'medium' ? cj.amber : Tcjd.color.text.tertiary;

  return (
    <div>
      {/* KPI strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={cj.stat}><span style={cj.statLabel}>Active defendants</span><span style={cj.statValue}>{k.activeDefendants}</span><span style={{ ...cj.statDelta, color: Tcjd.color.text.tertiary }}>{k.pleaNegotiating} in plea talks</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Detained</span><span style={{ ...cj.statValue, color: cj.burgundy }}>{k.detained}</span><span style={{ ...cj.statDelta, color: Tcjd.color.text.tertiary }}>{k.onBail} on bail</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Trials this quarter</span><span style={{ ...cj.statValue, color: cj.burgundy }}>{k.trialsThisQuarter}</span><span style={{ ...cj.statDelta, color: Tcjd.color.text.tertiary }}>+ {k.sentencingsThisQuarter} sentencings</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Motions pending</span><span style={{ ...cj.statValue, color: cj.amber }}>{k.motionsPending}</span><span style={{ ...cj.statDelta, color: cj.emerald }}>{k.motionsGranted} granted YTD</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Hearings · 30 days</span><span style={cj.statValue}>{k.hearingsNext30}</span><span style={{ ...cj.statDelta, color: Tcjd.color.text.tertiary }}>across all matters</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Avg plea savings</span><span style={{ ...cj.statValue, color: cj.emerald }}>−{k.avgSavingsVsStat}%</span><span style={{ ...cj.statDelta, color: Tcjd.color.text.tertiary }}>vs statutory max</span></div>
      </div>

      {/* Stage pipeline + Exposure summary */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: '14px', marginBottom: '16px' }}>
        <div style={cj.card}>
          <div style={cj.cardH}>Case stage pipeline</div>
          <div style={{ padding: '14px 16px', display: 'flex', gap: '6px' }}>
            {stageOrder.map((s, i) => {
              const n = stageCounts[s] || 0;
              const sc = cj.stageColor(s);
              return (
                <div key={s} style={{ flex: 1, position: 'relative' }}>
                  <div style={{ padding: '10px 8px', background: sc.bg, border: `1px solid ${sc.color}22`, borderRadius: '6px', textAlign: 'center' }}>
                    <div style={{ fontSize: '9px', fontWeight: 700, color: sc.color, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '3px' }}>{s}</div>
                    <div style={{ fontSize: '22px', fontWeight: 700, color: sc.color, fontFamily: Tcjd.font.mono }}>{n}</div>
                  </div>
                  {i < stageOrder.length - 1 && (
                    <div style={{ position: 'absolute', right: '-4px', top: '50%', transform: 'translateY(-50%)', color: Tcjd.color.text.tertiary, fontSize: '10px' }}>›</div>
                  )}
                </div>
              );
            })}
          </div>
        </div>

        <div style={{ ...cj.card, borderLeft: `3px solid ${cj.burgundy}` }}>
          <div style={{ ...cj.cardH, color: cj.burgundy }}>flag Exposure summary</div>
          <div style={{ padding: '10px 16px' }}>
            <div style={{ fontSize: '11px', color: Tcjd.color.text.secondary, marginBottom: '8px', lineHeight: 1.55 }}>
              <b>{totalExposure}</b> active defendants with calculated USSG ranges · avg. range <b style={{ color: cj.burgundy }}>{k.avgGuidelineRange}</b>.
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
              <div><div style={{ fontSize: '9px', color: Tcjd.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Cooperators</div><div style={{ fontSize: '16px', fontWeight: 700, color: cj.teal, fontFamily: Tcjd.font.mono }}>{k.cooperators}</div></div>
              <div><div style={{ fontSize: '9px', color: Tcjd.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Witnesses indexed</div><div style={{ fontSize: '16px', fontWeight: 700, color: cj.violet, fontFamily: Tcjd.font.mono }}>{k.witnessesIdentified}</div></div>
              <div><div style={{ fontSize: '9px', color: Tcjd.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Brady pending</div><div style={{ fontSize: '16px', fontWeight: 700, color: cj.amber, fontFamily: Tcjd.font.mono }}>{k.bradyProductionPending}</div></div>
              <div><div style={{ fontSize: '9px', color: Tcjd.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>§ 2255 pending</div><div style={{ fontSize: '16px', fontWeight: 700, color: cj.cobalt, fontFamily: Tcjd.font.mono }}>{k.post2255Pending}</div></div>
            </div>
          </div>
        </div>
      </div>

      {/* Upcoming hearings */}
      <div style={cj.card}>
        <div style={cj.cardH}>
          <span>Upcoming hearings — next 6</span>
          <button style={cj.btnSecondary}>View all ({k.hearingsNext30}) →</button>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={cj.th}>Date</th>
              <th style={cj.th}>Time</th>
              <th style={cj.th}>Defendant</th>
              <th style={cj.th}>Type</th>
              <th style={cj.th}>Court</th>
              <th style={cj.th}>Judge</th>
              <th style={cj.th}>Purpose</th>
              <th style={cj.th}>Urgency</th>
            </tr>
          </thead>
          <tbody>
            {upcoming.map(h => {
              const c = urgencyColor(h.urgency);
              return (
                <tr key={h.id}>
                  <td style={{ ...cj.td, fontFamily: Tcjd.font.mono, fontSize: '11px', color: c, fontWeight: 700 }}>{h.date}</td>
                  <td style={{ ...cj.td, fontFamily: Tcjd.font.mono, fontSize: '11px', color: Tcjd.color.text.secondary }}>{h.time}</td>
                  <td style={{ ...cj.td, fontWeight: 600, color: Tcjd.color.text.primary, maxWidth: '200px' }}>{h.defendant}</td>
                  <td style={{ ...cj.td, color: Tcjd.color.text.secondary, maxWidth: '200px' }}>{h.type}</td>
                  <td style={{ ...cj.td, fontFamily: Tcjd.font.mono, fontSize: '11px', color: Tcjd.color.text.secondary }}>{h.court}</td>
                  <td style={{ ...cj.td, color: Tcjd.color.text.secondary, fontSize: '11px' }}>{h.judge}</td>
                  <td style={{ ...cj.td, color: Tcjd.color.text.secondary, fontSize: '11px', maxWidth: '300px' }}>{h.purpose}</td>
                  <td style={cj.td}><span style={{ ...cj.tag, background: `${c}18`, color: c }}>{h.urgency}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function CriminalDefendants({ data }) {
  const cj = window.__cj;
  const [stageFilter, setStageFilter] = useCjDashState('All');
  const [search, setSearch] = useCjDashState('');

  const stages = useCjDashMemo(() => ['All', ...new Set(data.defendants.map(d => d.stage))], [data]);
  const filtered = data.defendants.filter(d =>
    (stageFilter === 'All' || d.stage === stageFilter) &&
    (!search || d.name.toLowerCase().includes(search.toLowerCase()) || d.matter.toLowerCase().includes(search.toLowerCase()) || d.docket.toLowerCase().includes(search.toLowerCase()))
  );

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={cj.stat}><span style={cj.statLabel}>Total defendants</span><span style={cj.statValue}>{data.defendants.length}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>With cooperation</span><span style={{ ...cj.statValue, color: cj.teal }}>{data.defendants.filter(d => d.coop).length}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Detained</span><span style={{ ...cj.statValue, color: cj.burgundy }}>{data.defendants.filter(d => d.bail === 'Detained').length}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>At sentencing</span><span style={{ ...cj.statValue, color: cj.orange }}>{data.defendants.filter(d => d.stage === 'Sentencing').length}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Avg charges</span><span style={cj.statValue}>{Math.round(data.defendants.reduce((s, d) => s + d.charges, 0) / data.defendants.length)}</span></div>
      </div>

      <div style={cj.card}>
        <div style={cj.cardH}>
          <span>Defendant roster — {filtered.length} of {data.defendants.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search name, matter, docket…"
              style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tcjd.color.border.light}`, borderRadius: '5px', background: Tcjd.color.bg.card, color: Tcjd.color.text.primary, minWidth: '240px', fontFamily: Tcjd.font.family }} />
            <select value={stageFilter} onChange={e => setStageFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tcjd.color.border.light}`, borderRadius: '5px', background: Tcjd.color.bg.card, color: Tcjd.color.text.secondary }}>
              {stages.map(s => <option key={s} value={s}>Stage: {s}</option>)}
            </select>
            <button style={cj.btnPrimary}>+ New defendant</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={cj.th}>ID / Docket</th>
              <th style={cj.th}>Defendant</th>
              <th style={cj.th}>Matter</th>
              <th style={cj.th}>Court · Judge</th>
              <th style={cj.th}>Stage</th>
              <th style={cj.th}>Bail</th>
              <th style={{ ...cj.th, textAlign: 'right' }}>Counts</th>
              <th style={cj.th}>Guide range</th>
              <th style={cj.th}>Lead counsel</th>
              <th style={cj.th}>Next hearing</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(d => {
              const sc = cj.stageColor(d.stage);
              const bc = cj.bailColor(d.bail);
              return (
                <tr key={d.id}>
                  <td style={{ ...cj.td, fontFamily: Tcjd.font.mono, fontSize: '10px', color: Tcjd.color.text.tertiary }}>
                    <div style={{ color: cj.burgundy, fontWeight: 700 }}>{d.id}</div>
                    <div>{d.docket}</div>
                  </td>
                  <td style={{ ...cj.td, maxWidth: '200px' }}>
                    <div style={{ fontSize: '12px', fontWeight: 600, color: Tcjd.color.text.primary }}>{d.name}</div>
                    <div style={{ fontSize: '10px', color: Tcjd.color.text.tertiary }}>{d.aka} · age {d.age}{d.coop ? ' ·  coop' : ''}</div>
                  </td>
                  <td style={{ ...cj.td, color: Tcjd.color.text.secondary, fontSize: '11px', maxWidth: '220px' }}>
                    {d.matter}
                    <div style={{ fontSize: '10px', color: Tcjd.color.text.tertiary, marginTop: '2px' }}>{d.leadCount}</div>
                  </td>
                  <td style={{ ...cj.td, color: Tcjd.color.text.secondary, fontSize: '11px' }}>
                    {d.court}
                    <div style={{ fontSize: '10px', color: Tcjd.color.text.tertiary }}>{d.judge}</div>
                  </td>
                  <td style={cj.td}><span style={{ ...cj.tag, background: sc.bg, color: sc.color }}>{d.stage}</span></td>
                  <td style={cj.td}>
                    <span style={{ ...cj.tag, background: bc.bg, color: bc.color }}>{d.bail}</span>
                    {d.custody && d.custody !== 'Not in custody' && <div style={{ fontSize: '10px', color: cj.burgundy, marginTop: '2px', fontFamily: Tcjd.font.mono }}>{d.custody}</div>}
                  </td>
                  <td style={{ ...cj.td, textAlign: 'right', fontFamily: Tcjd.font.mono, color: Tcjd.color.text.primary, fontWeight: 700 }}>{d.charges}</td>
                  <td style={{ ...cj.td, fontFamily: Tcjd.font.mono, fontSize: '11px', color: cj.burgundy, fontWeight: 700 }}>{d.guideRange}</td>
                  <td style={{ ...cj.td, color: Tcjd.color.text.secondary }}>{d.leadCounsel}</td>
                  <td style={{ ...cj.td, fontFamily: Tcjd.font.mono, fontSize: '11px', color: Tcjd.color.text.secondary }}>{d.nextHearing || '—'}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.CriminalDashboard = CriminalDashboard;
window.CriminalDefendants = CriminalDefendants;
