// CRIMINAL BRADY — Views Part 1: Overview + Requests + Cooperators
const { useState: useBV1State } = React;
const Tbv1 = window.ArbiterTokens;

const docColor = (doctrine, cj) => ({
  'Brady':  { bg: cj.burgundyBg, color: cj.burgundy },
  'Giglio': { bg: cj.violetBg,   color: cj.violet },
  'Jencks': { bg: cj.cobaltBg,   color: cj.cobalt },
}[doctrine] || { bg: Tbv1.color.bg.secondary, color: Tbv1.color.text.secondary });

const statusColor = (s, cj) => ({
  'Produced':   { bg: cj.emeraldBg, color: cj.emerald },
  'Partial':    { bg: cj.amberBg,   color: cj.amber },
  'Pending':    { bg: cj.orangeBg,  color: cj.orange },
  'In Camera':  { bg: cj.violetBg,  color: cj.violet },
  'Withheld':   { bg: cj.burgundyBg,color: cj.burgundy },
}[s] || { bg: Tbv1.color.bg.secondary, color: Tbv1.color.text.secondary });

const riskColor = (r, cj) => ({
  'Critical': { bg: cj.burgundyBg, color: cj.burgundy },
  'High':     { bg: cj.amberBg,    color: cj.amber },
  'Medium':   { bg: cj.cobaltBg,   color: cj.cobalt },
  'Low':      { bg: cj.emeraldBg,  color: cj.emerald },
}[r] || { bg: Tbv1.color.bg.secondary, color: Tbv1.color.text.secondary });

function BradyOverview({ data }) {
  const cj = window.__cj;
  const b = data.brady;
  const ext = data.bradyExt;
  const requests = ext.requests;
  const s = b.summary;
  const critical = requests.filter(r => r.materialityRisk === 'Critical').length;
  const pending = requests.filter(r => r.status === 'Pending' || r.status === 'In Camera').length;

  // Deadline urgency
  const today = new Date('2026-04-21');
  const urgent = requests.filter(r => {
    if (!r.deadline) return false;
    const d = new Date(r.deadline);
    return (d - today) / 86400000 <= 14 && r.status !== 'Produced';
  });

  return (
    <div>
      <div style={{ ...cj.card, borderLeft: `3px solid ${cj.burgundy}`, background: cj.burgundyBg, marginBottom: '14px' }}>
        <div style={{ padding: '14px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <div style={{ fontSize: '13px', fontWeight: 700, color: cj.burgundy, textTransform: 'uppercase', letterSpacing: '0.08em' }}> Brady · Giglio · Jencks — Constitutional Disclosure Obligations</div>
            <div style={{ fontSize: '12px', color: Tbv1.color.text.secondary, marginTop: '6px', lineHeight: 1.55 }}>
              <b style={{ color: Tbv1.color.text.primary }}>{requests.length} requests</b> tracked across {new Set(requests.map(r=>r.defendantId)).size} defendants.{' '}
              <b style={{ color: cj.emerald }}>{s.produced} fully produced.</b>{' '}
              <b style={{ color: cj.burgundy }}>{critical} critical-materiality items</b> outstanding.{' '}
              {urgent.length > 0 && <b style={{ color: cj.orange }}>{urgent.length} deadlines within 14 days.</b>}
            </div>
          </div>
          <button style={cj.btnPrimary}>+ New request</button>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: '10px', marginBottom: '14px' }}>
        {[
          { l: 'Total requests', v: s.totalRequests, c: null },
          { l: 'Produced',       v: s.produced,       c: cj.emerald },
          { l: 'Partial',        v: s.partialProduced, c: cj.amber },
          { l: 'Pending',        v: s.pending,         c: cj.orange },
          { l: 'In camera',      v: s.inCameraReviewsPending, c: cj.violet },
          { l: 'Compel motions', v: s.compelMotions,   c: cj.orange },
          { l: 'Critical risk',  v: critical,          c: cj.burgundy },
        ].map(s => (
          <div key={s.l} style={cj.stat}>
            <span style={cj.statLabel}>{s.l}</span>
            <span style={{ ...cj.statValue, color: s.c || Tbv1.color.text.primary }}>{s.v}</span>
          </div>
        ))}
      </div>

      {/* Doctrine breakdown */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '14px', marginBottom: '14px' }}>
        {[
          { doctrine: 'Brady',  title: 'Brady — Exculpatory', subtitle: 'United States v. Brady (1963) · Kyles v. Whitley', desc: 'Material exculpatory evidence must be disclosed regardless of good or bad faith. Materiality: reasonable probability of different result.', color: cj.burgundy, bg: cj.burgundyBg },
          { doctrine: 'Giglio', title: 'Giglio — Impeachment', subtitle: 'Giglio v. United States (1972) · United States v. Bagley', desc: 'Cooperation agreements, witness benefits, prior inconsistent statements, and any deal that could affect credibility.', color: cj.violet, bg: cj.violetBg },
          { doctrine: 'Jencks', title: 'Jencks — § 3500', subtitle: '18 U.S.C. § 3500 · Jencks Act', desc: 'Prior statements of testifying government witnesses. Due no later than direct examination begins at trial. Grand jury testimony protected until witness testifies.', color: cj.cobalt, bg: cj.cobaltBg },
        ].map(d => {
          const mine = requests.filter(r => r.doctrine === d.doctrine);
          const produced = mine.filter(r => r.status === 'Produced').length;
          return (
            <div key={d.doctrine} style={{ ...cj.card, borderTop: `3px solid ${d.color}`, marginBottom: 0 }}>
              <div style={{ padding: '12px 14px', background: d.bg }}>
                <div style={{ fontSize: '13px', fontWeight: 700, color: d.color }}>{d.title}</div>
                <div style={{ fontSize: '10px', color: Tbv1.color.text.tertiary, marginTop: '2px' }}>{d.subtitle}</div>
              </div>
              <div style={{ padding: '12px 14px' }}>
                <div style={{ fontSize: '11px', color: Tbv1.color.text.secondary, lineHeight: 1.6, marginBottom: '10px' }}>{d.desc}</div>
                <div style={{ display: 'flex', gap: '6px' }}>
                  <span style={{ ...cj.tag, background: d.bg, color: d.color }}>{mine.length} requests</span>
                  <span style={{ ...cj.tag, background: cj.emeraldBg, color: cj.emerald }}>{produced} produced</span>
                  <span style={{ ...cj.tag, background: cj.amberBg, color: cj.amber }}>{mine.length - produced} outstanding</span>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Urgent deadlines */}
      {urgent.length > 0 && (
        <div style={{ ...cj.card, borderLeft: `3px solid ${cj.orange}`, background: cj.orangeBg, marginBottom: '14px' }}>
          <div style={{ padding: '10px 14px' }}>
            <div style={{ fontSize: '12px', fontWeight: 700, color: cj.orange, marginBottom: '6px' }}>! {urgent.length} deadline{urgent.length > 1 ? 's' : ''} within 14 days</div>
            {urgent.map(r => {
              const days = Math.round((new Date(r.deadline) - today) / 86400000);
              return (
                <div key={r.id} style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', padding: '4px 0', borderTop: `1px solid ${cj.orange}22` }}>
                  <span><b style={{ fontFamily: Tbv1.font.mono, color: cj.burgundy }}>{r.id}</b> {r.defendant} — {r.description.slice(0, 60)}…</span>
                  <span style={{ fontFamily: Tbv1.font.mono, color: days <= 7 ? cj.burgundy : cj.orange, fontWeight: 700, whiteSpace: 'nowrap', marginLeft: '12px' }}>{days}d</span>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Production status by defendant */}
      <div style={cj.card}>
        <div style={cj.cardH}>Production status — by defendant</div>
        <div style={{ padding: '14px 16px' }}>
          {Object.entries(
            requests.reduce((acc, r) => { acc[r.defendant] = acc[r.defendant] || []; acc[r.defendant].push(r); return acc; }, {})
          ).map(([def, reqs]) => {
            const pct = Math.round(reqs.filter(r => r.status === 'Produced').length / reqs.length * 100);
            const hasCritical = reqs.some(r => r.materialityRisk === 'Critical' && r.status !== 'Produced');
            return (
              <div key={def} style={{ marginBottom: '10px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', marginBottom: '4px' }}>
                  <span style={{ color: Tbv1.color.text.primary, fontWeight: 500, display: 'flex', alignItems: 'center', gap: '6px' }}>
                    {def}
                    {hasCritical && <span style={{ ...cj.tag, background: cj.burgundyBg, color: cj.burgundy, fontSize: '9px' }}>CRITICAL</span>}
                  </span>
                  <span style={{ fontFamily: Tbv1.font.mono, color: pct === 100 ? cj.emerald : cj.amber, fontWeight: 700 }}>{pct}%</span>
                </div>
                <div style={{ height: '8px', background: Tbv1.color.border.light, borderRadius: '4px', overflow: 'hidden' }}>
                  <div style={{ width: `${pct}%`, height: '100%', background: pct === 100 ? cj.emerald : `linear-gradient(90deg, ${cj.burgundy}, ${cj.amber})` }} />
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function BradyRequests({ data }) {
  const cj = window.__cj;
  const ext = data.bradyExt;
  const [docFilter, setDocFilter] = useBV1State('All');
  const [statusFilter, setStatusFilter] = useBV1State('All');
  const [selected, setSelected] = useBV1State(null);
  const requests = ext.requests;
  const doctrines = ['All', 'Brady', 'Giglio', 'Jencks'];
  const statuses = ['All', 'Produced', 'Partial', 'Pending', 'In Camera'];
  const rows = requests.filter(r => (docFilter === 'All' || r.doctrine === docFilter) && (statusFilter === 'All' || r.status === statusFilter));

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={cj.stat}><span style={cj.statLabel}>Shown</span><span style={cj.statValue}>{rows.length}</span><span style={{ ...cj.statDelta, color: Tbv1.color.text.tertiary }}>of {requests.length}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Critical risk</span><span style={{ ...cj.statValue, color: cj.burgundy }}>{rows.filter(r=>r.materialityRisk==='Critical').length}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Compel filed</span><span style={{ ...cj.statValue, color: cj.orange }}>{rows.filter(r=>r.compelFiled).length}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>In camera</span><span style={{ ...cj.statValue, color: cj.violet }}>{rows.filter(r=>r.inCamera).length}</span></div>
      </div>

      <div style={cj.card}>
        <div style={cj.cardH}>
          <span>Brady / Giglio / Jencks registry — {rows.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            {[doctrines, statuses].map((opts, i) => (
              <select key={i} value={i===0 ? docFilter : statusFilter} onChange={e => i===0 ? setDocFilter(e.target.value) : setStatusFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tbv1.color.border.light}`, borderRadius: '5px', background: Tbv1.color.bg.card, color: Tbv1.color.text.secondary }}>
                {opts.map(o => <option key={o} value={o}>{i===0?'Doctrine':'Status'}: {o}</option>)}
              </select>
            ))}
            <button style={cj.btnPrimary}>+ New request</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr>
            <th style={cj.th}>ID</th><th style={cj.th}>Defendant</th><th style={cj.th}>Doctrine</th>
            <th style={cj.th}>Subtype</th><th style={cj.th}>Filed</th><th style={cj.th}>Deadline</th>
            <th style={cj.th}>Risk</th><th style={cj.th}>Status</th><th style={cj.th}>Compel</th><th style={cj.th}></th>
          </tr></thead>
          <tbody>
            {rows.map(r => {
              const dc = docColor(r.doctrine, cj);
              const sc = statusColor(r.status, cj);
              const rc = riskColor(r.materialityRisk, cj);
              const isSel = selected === r.id;
              const today = new Date('2026-04-21');
              const daysLeft = r.deadline ? Math.round((new Date(r.deadline) - today) / 86400000) : null;
              return (
                <React.Fragment key={r.id}>
                  <tr onClick={() => setSelected(isSel ? null : r.id)} style={{ cursor: 'pointer', background: isSel ? cj.burgundyBg : 'transparent' }}>
                    <td style={{ ...cj.td, fontFamily: Tbv1.font.mono, fontWeight: 700, color: cj.burgundy }}>{r.id}</td>
                    <td style={{ ...cj.td, fontWeight: 500, color: Tbv1.color.text.primary }}>{r.defendant}</td>
                    <td style={cj.td}><span style={{ ...cj.tag, background: dc.bg, color: dc.color }}>{r.doctrine}</span></td>
                    <td style={{ ...cj.td, fontSize: '11px', color: Tbv1.color.text.secondary }}>{r.subtype}</td>
                    <td style={{ ...cj.td, fontFamily: Tbv1.font.mono, fontSize: '11px', color: Tbv1.color.text.tertiary }}>{r.filed}</td>
                    <td style={{ ...cj.td, fontFamily: Tbv1.font.mono, fontSize: '11px', color: daysLeft != null && daysLeft <= 7 && r.status !== 'Produced' ? cj.burgundy : daysLeft != null && daysLeft <= 14 && r.status !== 'Produced' ? cj.orange : Tbv1.color.text.tertiary, fontWeight: daysLeft != null && daysLeft <= 14 && r.status !== 'Produced' ? 700 : 400 }}>{r.deadline || '—'}{daysLeft != null && r.status !== 'Produced' ? ` (${daysLeft}d)` : ''}</td>
                    <td style={cj.td}><span style={{ ...cj.tag, background: rc.bg, color: rc.color }}>{r.materialityRisk}</span></td>
                    <td style={cj.td}><span style={{ ...cj.tag, background: sc.bg, color: sc.color }}>{r.status}</span></td>
                    <td style={cj.td}>{r.compelFiled ? <span style={{ ...cj.tag, background: cj.orangeBg, color: cj.orange }}>ok {r.compelId}</span> : <span style={{ fontSize: '10px', color: Tbv1.color.text.tertiary }}>—</span>}</td>
                    <td style={{ ...cj.td, textAlign: 'right', fontSize: '11px', color: cj.burgundy, fontWeight: 600 }}>{isSel ? '−' : '+'}</td>
                  </tr>
                  {isSel && (
                    <tr>
                      <td colSpan={10} style={{ padding: 0, background: cj.burgundyBg }}>
                        <div style={{ padding: '12px 20px', borderTop: `1px solid ${cj.burgundy}33` }}>
                          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '10px' }}>
                            <div>
                              <div style={{ fontSize: '10px', fontWeight: 700, color: Tbv1.color.text.tertiary, textTransform: 'uppercase', marginBottom: '4px' }}>Description</div>
                              <div style={{ fontSize: '12px', color: Tbv1.color.text.primary, lineHeight: 1.6 }}>{r.description}</div>
                            </div>
                            <div>
                              <div style={{ fontSize: '10px', fontWeight: 700, color: Tbv1.color.text.tertiary, textTransform: 'uppercase', marginBottom: '4px' }}>Government position</div>
                              <div style={{ fontSize: '12px', color: Tbv1.color.text.secondary, lineHeight: 1.6 }}>{r.govtPosition}</div>
                            </div>
                          </div>
                          <div style={{ fontSize: '11px', color: Tbv1.color.text.secondary, paddingTop: '8px', borderTop: `1px solid ${cj.burgundy}22` }}>
                            <b style={{ color: cj.burgundy }}>Analysis:</b> {r.notes}
                          </div>
                          {r.inCamera && <div style={{ marginTop: '6px', fontSize: '11px', color: cj.violet }}><b>In camera:</b> {r.inCameraDate}</div>}
                        </div>
                      </td>
                    </tr>
                  )}
                </React.Fragment>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function BradyCooperators({ data }) {
  const cj = window.__cj;
  const matrix = data.brady.coopMatrix;
  const ext = data.bradyExt;

  const credScore = (cw) => {
    let score = 100;
    const pi = parseInt(cw.priorInconsistent);
    if (!isNaN(pi)) score -= pi * 15;
    if (cw.deportationStake.startsWith('Yes')) score -= 20;
    if (cw.agreement.includes('5K1.1')) score -= 10;
    if (cw.agreement === 'Non-prosecution letter') score -= 5;
    return Math.max(0, score);
  };

  return (
    <div>
      <div style={{ ...cj.card, borderLeft: `3px solid ${cj.violet}`, background: cj.violetBg, marginBottom: '14px' }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: cj.violet, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Giglio Cooperator Matrix — Impeachment inventory for all government witnesses under cooperation agreements</div>
          <div style={{ fontSize: '11px', color: Tbv1.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            {matrix.length} cooperators/informants tracked. Credibility score derived from prior inconsistencies, deportation leverage, and agreement type. Lower score = stronger impeachment opportunity.
          </div>
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
        {matrix.map(cw => {
          const score = credScore(cw);
          const scoreColor = score >= 80 ? cj.emerald : score >= 60 ? cj.amber : cj.burgundy;
          const jencksEntry = ext.jencks.find(j => j.name.includes(cw.cooperator.replace('CW-', 'CW-').split(' ')[0]));
          return (
            <div key={cw.cooperator} style={{ ...cj.card, marginBottom: 0, borderLeft: `3px solid ${scoreColor}` }}>
              <div style={{ padding: '12px 16px', display: 'grid', gridTemplateColumns: '200px 1fr', gap: '20px', alignItems: 'start' }}>
                <div>
                  <div style={{ fontSize: '14px', fontWeight: 700, color: cj.violet, marginBottom: '4px' }}>{cw.cooperator}</div>
                  <div style={{ fontSize: '11px', color: Tbv1.color.text.tertiary, marginBottom: '8px' }}>Matter: {cw.matter}</div>
                  <span style={{ ...cj.tag, background: cj.violetBg, color: cj.violet }}>{cw.agreement}</span>
                  <div style={{ marginTop: '10px' }}>
                    <div style={{ fontSize: '10px', color: Tbv1.color.text.tertiary, textTransform: 'uppercase', marginBottom: '3px' }}>Credibility score</div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                      <span style={{ fontFamily: Tbv1.font.mono, fontSize: '20px', fontWeight: 700, color: scoreColor }}>{score}</span>
                      <div style={{ flex: 1, height: '8px', background: Tbv1.color.border.light, borderRadius: '4px', overflow: 'hidden' }}>
                        <div style={{ width: `${score}%`, height: '100%', background: scoreColor }} />
                      </div>
                    </div>
                    <div style={{ fontSize: '10px', color: Tbv1.color.text.tertiary, marginTop: '2px' }}>{score >= 80 ? 'Difficult to impeach' : score >= 60 ? 'Significant vulnerabilities' : 'Highly impeachable'}</div>
                  </div>
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px' }}>
                  <div>
                    <div style={{ fontSize: '10px', fontWeight: 700, color: Tbv1.color.text.tertiary, textTransform: 'uppercase', marginBottom: '4px' }}>Benefit sought</div>
                    <div style={{ fontSize: '12px', color: Tbv1.color.text.primary, lineHeight: 1.5 }}>{cw.benefitSought}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: '10px', fontWeight: 700, color: Tbv1.color.text.tertiary, textTransform: 'uppercase', marginBottom: '4px' }}>Prior inconsistencies</div>
                    <div style={{ fontSize: '12px', color: parseInt(cw.priorInconsistent) > 0 ? cj.amber : Tbv1.color.text.tertiary, fontWeight: parseInt(cw.priorInconsistent) > 0 ? 700 : 400 }}>{cw.priorInconsistent}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: '10px', fontWeight: 700, color: Tbv1.color.text.tertiary, textTransform: 'uppercase', marginBottom: '4px' }}>Deportation leverage</div>
                    <span style={{ ...cj.tag, background: cw.deportationStake.startsWith('Yes') ? cj.burgundyBg : cj.emeraldBg, color: cw.deportationStake.startsWith('Yes') ? cj.burgundy : cj.emerald }}>{cw.deportationStake}</span>
                  </div>
                  <div>
                    <div style={{ fontSize: '10px', fontWeight: 700, color: Tbv1.color.text.tertiary, textTransform: 'uppercase', marginBottom: '4px' }}>Giglio produced</div>
                    {cw.compelProduced ? <span style={{ ...cj.tag, background: cj.emeraldBg, color: cj.emerald }}>ok Produced</span> : <span style={{ ...cj.tag, background: cj.burgundyBg, color: cj.burgundy }}>Pending</span>}
                  </div>
                  <div>
                    <div style={{ fontSize: '10px', fontWeight: 700, color: Tbv1.color.text.tertiary, textTransform: 'uppercase', marginBottom: '4px' }}>Jencks status</div>
                    {jencksEntry ? <span style={{ ...cj.tag, background: cj.cobaltBg, color: cj.cobalt }}>{jencksEntry.status}</span> : <span style={{ fontSize: '11px', color: Tbv1.color.text.tertiary }}>—</span>}
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

window.BradyOverview = BradyOverview;
window.BradyRequests = BradyRequests;
window.BradyCooperators = BradyCooperators;
