// CRIMINAL BRADY — Views Part 2: Jencks + In Camera + Compel + Platform Entry
const { useState: useBV2State } = React;
const Tbv2 = window.ArbiterTokens;

function BradyJencks({ data }) {
  const cj = window.__cj;
  const jencks = data.bradyExt.jencks;

  const statusColor = (s) => ({
    'Produced':  { bg: cj.emeraldBg, color: cj.emerald },
    'Partial':   { bg: cj.amberBg,   color: cj.amber },
    'Pending':   { bg: cj.orangeBg,  color: cj.orange },
    'Scheduled': { bg: cj.cobaltBg,  color: cj.cobalt },
  }[s] || { bg: Tbv2.color.bg.secondary, color: Tbv2.color.text.secondary });

  const totalPages = jencks.reduce((s, j) => s + (j.pagesEst || 0), 0);
  const producedPages = jencks.reduce((s, j) => s + (j.pagesProduced || 0), 0);
  const today = new Date('2026-04-21');

  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' }}>◆ Jencks Act § 3500 — Prior Statements of Testifying Government Witnesses</div>
          <div style={{ fontSize: '11px', color: Tbv2.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            Due no later than the start of direct examination. Grand jury transcripts produced under § 3500(e)(3).{' '}
            <b>{producedPages.toLocaleString()}</b> of est. <b>{totalPages.toLocaleString()}</b> pages produced across {jencks.length} witnesses.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={cj.stat}><span style={cj.statLabel}>Witnesses tracked</span><span style={cj.statValue}>{jencks.length}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Pages estimated</span><span style={{ ...cj.statValue, color: cj.cobalt }}>{totalPages.toLocaleString()}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Pages produced</span><span style={{ ...cj.statValue, color: cj.emerald }}>{producedPages.toLocaleString()}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Pages outstanding</span><span style={{ ...cj.statValue, color: cj.orange }}>{(totalPages - producedPages).toLocaleString()}</span></div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
        {jencks.map(j => {
          const sc = statusColor(j.status);
          const pct = j.pagesEst > 0 ? Math.round(j.pagesProduced / j.pagesEst * 100) : 100;
          const daysToDeadline = j.jencksDeadline ? Math.round((new Date(j.jencksDeadline) - today) / 86400000) : null;
          return (
            <div key={j.witnessId} style={{ ...cj.card, marginBottom: 0 }}>
              <div style={{ padding: '12px 16px' }}>
                <div style={{ display: 'grid', gridTemplateColumns: '220px 1fr 180px', gap: '16px', alignItems: 'start' }}>
                  <div>
                    <div style={{ fontSize: '13px', fontWeight: 700, color: Tbv2.color.text.primary, marginBottom: '2px' }}>{j.name}</div>
                    <div style={{ fontSize: '11px', color: Tbv2.color.text.tertiary, marginBottom: '6px' }}>Matter: {j.matter}</div>
                    <span style={{ ...cj.tag, background: sc.bg, color: sc.color }}>{j.status}</span>
                    {daysToDeadline != null && (
                      <span style={{ ...cj.tag, background: daysToDeadline <= 14 ? cj.orangeBg : cj.cobaltBg, color: daysToDeadline <= 14 ? cj.orange : cj.cobalt, marginLeft: '4px' }}>
                        Deadline {j.jencksDeadline} ({daysToDeadline}d)
                      </span>
                    )}
                    {!j.jencksDeadline && <div style={{ fontSize: '10px', color: Tbv2.color.text.tertiary, marginTop: '4px' }}>No trial date set</div>}
                  </div>
                  <div>
                    <div style={{ fontSize: '10px', fontWeight: 700, color: Tbv2.color.text.tertiary, textTransform: 'uppercase', marginBottom: '6px' }}>Material types</div>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px', marginBottom: '10px' }}>
                      {j.materialTypes.map(m => (
                        <span key={m} style={{ ...cj.tag, background: cj.cobaltBg, color: cj.cobalt, fontSize: '10px' }}>{m}</span>
                      ))}
                    </div>
                    <div style={{ fontSize: '11px', color: Tbv2.color.text.secondary, lineHeight: 1.5 }}>{j.notes}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: '10px', fontWeight: 700, color: Tbv2.color.text.tertiary, textTransform: 'uppercase', marginBottom: '6px' }}>Pages produced</div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', marginBottom: '4px' }}>
                      <span style={{ fontFamily: Tbv2.font.mono, fontWeight: 700, color: Tbv2.color.text.primary }}>{j.pagesProduced.toLocaleString()} / {j.pagesEst.toLocaleString()}</span>
                      <span style={{ fontFamily: Tbv2.font.mono, color: pct === 100 ? cj.emerald : cj.cobalt, fontWeight: 700 }}>{pct}%</span>
                    </div>
                    <div style={{ height: '10px', background: Tbv2.color.border.light, borderRadius: '5px', overflow: 'hidden' }}>
                      <div style={{ width: `${pct}%`, height: '100%', background: pct === 100 ? cj.emerald : `linear-gradient(90deg, ${cj.cobalt}, ${cj.cyan || cj.teal})` }} />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function BradyInCamera({ data }) {
  const cj = window.__cj;
  const items = data.bradyExt.inCamera;

  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' }}>◆ In Camera Review Docket — Sealed judicial review of contested Brady material</div>
          <div style={{ fontSize: '11px', color: Tbv2.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            {items.length} pending in-camera reviews. Court reviews contested material ex parte to rule on Brady materiality vs. government privilege claims. Rulings may order production, partial redaction, or protective order.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={cj.stat}><span style={cj.statLabel}>In camera pending</span><span style={{ ...cj.statValue, color: cj.violet }}>{items.filter(i=>!i.outcome).length}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Next review</span><span style={{ ...cj.statValue, fontSize: '15px', fontFamily: Tbv2.font.mono }}>{items[0]?.scheduledDate || '—'}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Resolved</span><span style={{ ...cj.statValue, color: cj.emerald }}>{items.filter(i=>i.outcome).length}</span></div>
      </div>

      {items.map(item => (
        <div key={item.id} style={{ ...cj.card, marginBottom: '12px', borderLeft: `3px solid ${cj.violet}` }}>
          <div style={{ padding: '14px 16px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '12px' }}>
              <div>
                <div style={{ display: 'flex', gap: '8px', alignItems: 'center', marginBottom: '4px' }}>
                  <span style={{ fontFamily: Tbv2.font.mono, fontWeight: 700, color: cj.violet }}>{item.id}</span>
                  <span style={{ ...cj.tag, background: cj.violetBg, color: cj.violet }}>In Camera</span>
                  <span style={{ ...cj.tag, background: item.outcome ? cj.emeraldBg : cj.orangeBg, color: item.outcome ? cj.emerald : cj.orange }}>{item.outcome || 'Scheduled'}</span>
                </div>
                <div style={{ fontSize: '13px', fontWeight: 700, color: Tbv2.color.text.primary }}>{item.defendant}</div>
                <div style={{ fontSize: '11px', color: Tbv2.color.text.tertiary }}>{item.judge} · {item.court} · {item.scheduledDate}</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontSize: '11px', color: Tbv2.color.text.tertiary }}>Brady ref:</div>
                <div style={{ fontFamily: Tbv2.font.mono, fontWeight: 700, color: cj.burgundy }}>{item.bradyId}</div>
              </div>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '14px', paddingTop: '10px', borderTop: `1px solid ${Tbv2.color.border.light}` }}>
              <div>
                <div style={{ fontSize: '10px', fontWeight: 700, color: Tbv2.color.text.tertiary, textTransform: 'uppercase', marginBottom: '4px' }}>Material at issue</div>
                <div style={{ fontSize: '12px', color: Tbv2.color.text.primary, lineHeight: 1.6 }}>{item.material}</div>
              </div>
              <div>
                <div style={{ fontSize: '10px', fontWeight: 700, color: cj.burgundy, textTransform: 'uppercase', marginBottom: '4px' }}>Government privilege claim</div>
                <div style={{ fontSize: '12px', color: Tbv2.color.text.secondary, lineHeight: 1.6 }}>{item.govtClaim}</div>
              </div>
              <div>
                <div style={{ fontSize: '10px', fontWeight: 700, color: cj.violet, textTransform: 'uppercase', marginBottom: '4px' }}>Our argument</div>
                <div style={{ fontSize: '12px', color: Tbv2.color.text.secondary, lineHeight: 1.6 }}>{item.ourArgument}</div>
              </div>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

function BradyCompel({ data }) {
  const cj = window.__cj;
  const motions = data.bradyExt.compelMotions;
  const urgencyColor = (u) => ({ 'Critical': cj.burgundy, 'High': cj.amber, 'Medium': cj.cobalt }[u] || cj.slate);

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={cj.stat}><span style={cj.statLabel}>Compel motions</span><span style={{ ...cj.statValue, color: cj.orange }}>{motions.length}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Under submission</span><span style={{ ...cj.statValue, color: cj.amber }}>{motions.filter(m=>m.status==='Under Submission').length}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>In camera</span><span style={{ ...cj.statValue, color: cj.violet }}>{motions.filter(m=>m.status==='In Camera').length}</span></div>
        <div style={cj.stat}><span style={cj.statLabel}>Critical urgency</span><span style={{ ...cj.statValue, color: cj.burgundy }}>{motions.filter(m=>m.urgency==='Critical').length}</span></div>
      </div>

      {motions.map(m => {
        const uc = urgencyColor(m.urgency);
        const sc = m.status === 'Under Submission' ? { bg: cj.amberBg, color: cj.amber }
          : m.status === 'In Camera' ? { bg: cj.violetBg, color: cj.violet }
          : m.status === 'Pending Argument' ? { bg: cj.orangeBg, color: cj.orange }
          : { bg: Tbv2.color.bg.secondary, color: Tbv2.color.text.secondary };
        return (
          <div key={m.id} style={{ ...cj.card, marginBottom: '12px', borderLeft: `3px solid ${uc}` }}>
            <div style={{ padding: '14px 16px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '12px' }}>
                <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                  <span style={{ fontFamily: Tbv2.font.mono, fontWeight: 700, color: cj.burgundy }}>{m.id}</span>
                  <span style={{ ...cj.tag, background: `${uc}14`, color: uc }}>{m.urgency}</span>
                  <span style={{ ...cj.tag, background: sc.bg, color: sc.color }}>{m.status}</span>
                  {m.ruling && <span style={{ ...cj.tag, background: cj.emeraldBg, color: cj.emerald }}>Ruling: {m.ruling}</span>}
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontSize: '11px', color: Tbv2.color.text.tertiary }}>Brady ref: <span style={{ fontFamily: Tbv2.font.mono, color: cj.burgundy }}>{m.bradyId}</span></div>
                  <div style={{ fontSize: '11px', color: Tbv2.color.text.tertiary }}>{m.judge}</div>
                </div>
              </div>

              <div style={{ fontSize: '13px', fontWeight: 700, color: Tbv2.color.text.primary, marginBottom: '4px' }}>{m.defendant}</div>
              <div style={{ fontSize: '12px', color: Tbv2.color.text.secondary, marginBottom: '12px' }}>Material: {m.material}</div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px', paddingTop: '10px', borderTop: `1px solid ${Tbv2.color.border.light}` }}>
                <div>
                  <div style={{ fontSize: '10px', fontWeight: 700, color: cj.violet, textTransform: 'uppercase', marginBottom: '4px' }}>Our argument</div>
                  <div style={{ fontSize: '12px', color: Tbv2.color.text.primary, lineHeight: 1.6 }}>{m.ourArg}</div>
                </div>
                <div>
                  <div style={{ fontSize: '10px', fontWeight: 700, color: cj.burgundy, textTransform: 'uppercase', marginBottom: '4px' }}>Government argument</div>
                  <div style={{ fontSize: '12px', color: Tbv2.color.text.secondary, lineHeight: 1.6 }}>{m.govtArg}</div>
                </div>
              </div>

              <div style={{ marginTop: '10px', padding: '8px 12px', background: cj.orangeBg, borderRadius: '5px', fontSize: '11px', color: cj.orange, lineHeight: 1.5 }}>
                <b>! Note:</b> {m.notes}
              </div>
              <div style={{ marginTop: '8px', fontSize: '11px', color: Tbv2.color.text.tertiary }}>
                Filed: <span style={{ fontFamily: Tbv2.font.mono }}>{m.filed}</span>
                {m.argued && <span> · Argued: <span style={{ fontFamily: Tbv2.font.mono }}>{m.argued}</span></span>}
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ─── MAIN PLATFORM ENTRY ─────────────────────────────────────────────────────
function CriminalBradyPlatform({ data }) {
  const cj = window.__cj;
  const [activeView, setActiveView] = useBV2State('overview');
  const views = [
    { id: 'overview',     label: 'Overview' },
    { id: 'requests',     label: 'Requests' },
    { id: 'cooperators',  label: 'Giglio / Cooperators' },
    { id: 'jencks',       label: 'Jencks § 3500' },
    { id: 'incamera',     label: 'In Camera' },
    { id: 'compel',       label: 'Compel Motions' },
  ];
  const render = () => {
    switch (activeView) {
      case 'overview':    return <BradyOverview data={data} />;
      case 'requests':    return <BradyRequests data={data} />;
      case 'cooperators': return <BradyCooperators data={data} />;
      case 'jencks':      return <BradyJencks data={data} />;
      case 'incamera':    return <BradyInCamera data={data} />;
      case 'compel':      return <BradyCompel data={data} />;
      default:            return <BradyOverview data={data} />;
    }
  };
  return (
    <div>
      <div style={{ display: 'flex', gap: '4px', padding: '5px', background: Tbv2.color.bg.secondary, border: `1px solid ${Tbv2.color.border.light}`, borderRadius: '8px', marginBottom: '16px', flexWrap: 'wrap' }}>
        {views.map(v => (
          <button key={v.id} onClick={() => setActiveView(v.id)} style={{
            padding: '6px 12px', 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' : Tbv2.color.text.secondary,
            fontFamily: Tbv2.font.family, transition: 'all .15s',
          }}>{v.label}</button>
        ))}
      </div>
      {render()}
    </div>
  );
}

window.CriminalBradyPlatform = CriminalBradyPlatform;
