// RESEARCH PLATFORM — Briefs sub-platform (Overview / Detail / Cite Checker / Templates / Activity)
const { useState: useBriefState, useMemo: useBriefMemo } = React;
const Tbr = window.ArbiterTokens;

// ── Overview — list + filter + KPI + alerts ─────────────────
function BriefsOverview({ data, onOpen }) {
  const rs = window.__rs;
  const [statusFilter, setStatusFilter] = useBriefState('All');
  const [matterFilter, setMatterFilter] = useBriefState('All');

  const matters = useBriefMemo(() => ['All', ...new Set(data.briefs.map(b => b.matter))], [data]);
  const statuses = ['All', 'Research', 'Drafting', 'Partner Review', 'Filed'];

  const filtered = data.briefs.filter(b =>
    (statusFilter === 'All' || b.status === statusFilter) &&
    (matterFilter === 'All' || b.matter === matterFilter)
  );

  const statusColor = (s) => ({
    Research: { bg: rs.indigoBg, color: rs.indigo },
    Drafting: { bg: rs.amberBg, color: rs.amber },
    'Partner Review': { bg: rs.violetBg, color: rs.violet },
    Filed: { bg: 'rgba(27,122,74,0.1)', color: '#1B7A4A' },
  }[s] || { bg: Tbr.color.bg.secondary, color: Tbr.color.text.secondary });

  const now = new Date('2026-04-20');
  const dueSoon = data.briefs.filter(b => {
    if (b.status === 'Filed') return false;
    const d = new Date(b.due);
    return (d - now) / 86400000 <= 7 && (d - now) >= 0;
  });
  const redCites = data.briefs.filter(b => b.cites.red > 0);

  const avgCiteHealth = Math.round(data.briefs.reduce((s, b) => s + (b.cites.green / b.cites.total * 100), 0) / data.briefs.length);

  return (
    <div>
      {/* KPI strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={rs.stat}>
          <span style={rs.statLabel}>In progress</span>
          <span style={rs.statValue}>{data.briefs.filter(b => b.status !== 'Filed').length}</span>
          <span style={{ ...rs.statDelta, color: Tbr.color.text.tertiary }}>of {data.briefs.length} total</span>
        </div>
        <div style={rs.stat}>
          <span style={rs.statLabel}>In partner review</span>
          <span style={{ ...rs.statValue, color: rs.violet }}>{data.briefs.filter(b => b.status === 'Partner Review').length}</span>
          <span style={{ ...rs.statDelta, color: Tbr.color.text.tertiary }}>awaiting sign-off</span>
        </div>
        <div style={rs.stat}>
          <span style={rs.statLabel}>Due ≤ 7 days</span>
          <span style={{ ...rs.statValue, color: dueSoon.length > 0 ? '#C23030' : Tbr.color.text.primary }}>{dueSoon.length}</span>
          <span style={{ ...rs.statDelta, color: Tbr.color.text.tertiary }}>{dueSoon.length === 0 ? 'no imminent deadlines' : 'attention required'}</span>
        </div>
        <div style={rs.stat}>
          <span style={rs.statLabel}>Avg cite health</span>
          <span style={{ ...rs.statValue, color: avgCiteHealth >= 95 ? '#1B7A4A' : '#B45309' }}>{avgCiteHealth}%</span>
          <span style={{ ...rs.statDelta, color: Tbr.color.text.tertiary }}>verified authorities</span>
        </div>
        <div style={rs.stat}>
          <span style={rs.statLabel}>Red-flag cites</span>
          <span style={{ ...rs.statValue, color: redCites.length > 0 ? '#C23030' : Tbr.color.text.primary }}>{data.briefs.reduce((s, b) => s + b.cites.red, 0)}</span>
          <span style={{ ...rs.statDelta, color: Tbr.color.text.tertiary }}>across {redCites.length} brief{redCites.length === 1 ? '' : 's'}</span>
        </div>
      </div>

      {/* Alerts row */}
      {(dueSoon.length > 0 || redCites.length > 0) && (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '16px' }}>
          {dueSoon.length > 0 && (
            <div style={{ ...rs.card, marginBottom: 0, borderLeft: '3px solid #C23030' }}>
              <div style={{ ...rs.cardH, color: '#C23030' }}>! Due within 7 days</div>
              <div>
                {dueSoon.map(b => (
                  <div key={b.id} onClick={() => onOpen(b.id)} style={{ padding: '10px 16px', borderBottom: `1px solid ${Tbr.color.border.light}`, cursor: 'pointer' }}>
                    <div style={{ fontSize: '12px', fontWeight: 600, color: Tbr.color.text.primary }}>{b.title}</div>
                    <div style={{ fontSize: '11px', color: Tbr.color.text.tertiary, marginTop: '3px' }}>{b.matter} · Due {b.due} · {b.status}</div>
                  </div>
                ))}
              </div>
            </div>
          )}
          {redCites.length > 0 && (
            <div style={{ ...rs.card, marginBottom: 0, borderLeft: `3px solid ${rs.amber}` }}>
              <div style={{ ...rs.cardH, color: rs.amber }}>! Briefs with negative-treatment cites</div>
              <div>
                {redCites.map(b => (
                  <div key={b.id} onClick={() => onOpen(b.id)} style={{ padding: '10px 16px', borderBottom: `1px solid ${Tbr.color.border.light}`, cursor: 'pointer' }}>
                    <div style={{ fontSize: '12px', fontWeight: 600, color: Tbr.color.text.primary }}>{b.title}</div>
                    <div style={{ fontSize: '11px', color: Tbr.color.text.tertiary, marginTop: '3px' }}>
                      <span style={{ ...rs.tag, ...rs.signalNegative, marginRight: '6px' }}>{b.cites.red} red</span>
                      <span style={{ ...rs.tag, ...rs.signalCaution }}>{b.cites.caution} caution</span>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      )}

      {/* List */}
      <div style={rs.card}>
        <div style={rs.cardH}>
          <span>All briefs — {filtered.length} of {data.briefs.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <select value={statusFilter} onChange={e => setStatusFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tbr.color.border.light}`, borderRadius: '5px', background: Tbr.color.bg.card, color: Tbr.color.text.secondary }}>
              {statuses.map(s => <option key={s} value={s}>Status: {s}</option>)}
            </select>
            <select value={matterFilter} onChange={e => setMatterFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tbr.color.border.light}`, borderRadius: '5px', background: Tbr.color.bg.card, color: Tbr.color.text.secondary }}>
              {matters.map(m => <option key={m} value={m}>Matter: {m}</option>)}
            </select>
            <button style={rs.btnPrimary}>+ New brief</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={rs.th}>Title</th>
              <th style={rs.th}>Matter</th>
              <th style={rs.th}>Author</th>
              <th style={rs.th}>Status</th>
              <th style={rs.th}>Progress</th>
              <th style={rs.th}>Cites</th>
              <th style={rs.th}>Due</th>
              <th style={rs.th}>Edited</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(b => {
              const sc = statusColor(b.status);
              const pct = Math.round((b.wordCount / b.targetWords) * 100);
              const citeHealth = (b.cites.green / b.cites.total) * 100;
              return (
                <tr key={b.id} onClick={() => onOpen(b.id)} style={{ cursor: 'pointer' }}>
                  <td style={{ ...rs.td, maxWidth: '320px' }}>
                    <div style={{ fontSize: '12px', fontWeight: 600, color: Tbr.color.text.primary }}>{b.title}</div>
                    <div style={{ fontSize: '10px', color: Tbr.color.text.tertiary, fontFamily: Tbr.font.mono, marginTop: '2px' }}>{b.id}</div>
                  </td>
                  <td style={{ ...rs.td, color: Tbr.color.text.secondary }}>{b.matter}</td>
                  <td style={{ ...rs.td, color: Tbr.color.text.secondary }}>{b.author}</td>
                  <td style={rs.td}><span style={{ ...rs.tag, background: sc.bg, color: sc.color }}>{b.status}</span></td>
                  <td style={rs.td}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                      <div style={{ width: '90px', height: '4px', background: Tbr.color.border.light, borderRadius: '2px', overflow: 'hidden' }}>
                        <div style={{ width: `${Math.min(100, pct)}%`, height: '100%', background: pct >= 80 ? '#1B7A4A' : pct >= 40 ? rs.indigo : rs.amber }} />
                      </div>
                      <span style={{ fontFamily: Tbr.font.mono, fontSize: '10px', color: Tbr.color.text.tertiary }}>{b.wordCount.toLocaleString()} / {b.targetWords.toLocaleString()}</span>
                    </div>
                  </td>
                  <td style={rs.td}>
                    <div style={{ display: 'flex', gap: '4px' }}>
                      <span style={{ ...rs.tag, ...rs.signalPositive }}>{b.cites.green} ok</span>
                      {b.cites.caution > 0 && <span style={{ ...rs.tag, ...rs.signalCaution }}>{b.cites.caution} !</span>}
                      {b.cites.red > 0 && <span style={{ ...rs.tag, ...rs.signalNegative }}>{b.cites.red} x</span>}
                    </div>
                    <div style={{ fontSize: '10px', color: citeHealth >= 95 ? '#1B7A4A' : citeHealth >= 85 ? rs.amber : '#C23030', marginTop: '3px', fontFamily: Tbr.font.mono }}>{citeHealth.toFixed(0)}% green</div>
                  </td>
                  <td style={{ ...rs.td, color: Tbr.color.text.secondary, fontFamily: Tbr.font.mono, fontSize: '11px' }}>{b.due}</td>
                  <td style={{ ...rs.td, color: Tbr.color.text.tertiary, fontSize: '11px' }}>{b.lastEdited}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ── Detail — in-place brief workspace view ─────────────────
function BriefDetail({ data, briefId, onBack }) {
  const rs = window.__rs;
  const b = data.briefs.find(x => x.id === briefId);
  const d = data.briefDetails[briefId];
  if (!b) return null;

  const statusPillColor = {
    Research: { bg: rs.indigoBg, color: rs.indigo },
    Drafting: { bg: rs.amberBg, color: rs.amber },
    'Partner Review': { bg: rs.violetBg, color: rs.violet },
    Filed: { bg: 'rgba(27,122,74,0.1)', color: '#1B7A4A' },
  }[b.status];

  const sectionStatusColor = (s) => ({
    complete: { bg: 'rgba(27,122,74,0.1)', color: '#1B7A4A' },
    drafting: { bg: rs.amberBg, color: rs.amber },
    outlined: { bg: rs.indigoBg, color: rs.indigo },
    'not-started': { bg: Tbr.color.bg.secondary, color: Tbr.color.text.tertiary },
  }[s] || { bg: Tbr.color.bg.secondary, color: Tbr.color.text.secondary });

  const sectionCompletePct = d ? Math.round(d.sections.filter(s => s.status === 'complete').length / d.sections.length * 100) : 0;

  if (!d) {
    return (
      <div>
        <button onClick={onBack} style={rs.btnSecondary}>← Back to briefs</button>
        <div style={{ ...rs.card, marginTop: '16px', padding: '40px', textAlign: 'center' }}>
          <div style={{ fontSize: '14px', color: Tbr.color.text.primary, fontWeight: 600, marginBottom: '4px' }}>{b.title}</div>
          <div style={{ fontSize: '12px', color: Tbr.color.text.tertiary }}>Detail view not yet populated for this brief.</div>
        </div>
      </div>
    );
  }

  return (
    <div>
      {/* Header strip */}
      <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '16px' }}>
        <button onClick={onBack} style={rs.btnSecondary}>← Back to briefs</button>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: '16px', fontWeight: 700, color: Tbr.color.text.primary, letterSpacing: '-0.01em' }}>{b.title}</div>
          <div style={{ fontSize: '11px', color: Tbr.color.text.tertiary, marginTop: '2px' }}>
            {d.court} · {d.caption} · {d.docketNo} · {d.judge}
          </div>
        </div>
        <span style={{ ...rs.tag, background: statusPillColor.bg, color: statusPillColor.color, fontSize: '11px', padding: '4px 12px' }}>{b.status}</span>
        <button style={rs.btnSecondary}>Check cites</button>
        <button style={rs.btnSecondary}>Export DOCX</button>
        <button style={rs.btnPrimary}>Send for review →</button>
      </div>

      {/* Meta strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={rs.stat}>
          <span style={rs.statLabel}>Sections</span>
          <span style={rs.statValue}>{d.sections.length}</span>
          <span style={{ ...rs.statDelta, color: Tbr.color.text.tertiary }}>{sectionCompletePct}% complete</span>
        </div>
        <div style={rs.stat}>
          <span style={rs.statLabel}>Words</span>
          <span style={rs.statValue}>{b.wordCount.toLocaleString()}</span>
          <span style={{ ...rs.statDelta, color: Tbr.color.text.tertiary }}>of {b.targetWords.toLocaleString()} target</span>
        </div>
        <div style={rs.stat}>
          <span style={rs.statLabel}>Cites</span>
          <span style={rs.statValue}>{b.cites.total}</span>
          <span style={{ ...rs.statDelta, color: '#1B7A4A' }}>{b.cites.green} verified</span>
        </div>
        <div style={rs.stat}>
          <span style={rs.statLabel}>Caution</span>
          <span style={{ ...rs.statValue, color: b.cites.caution > 0 ? rs.amber : Tbr.color.text.primary }}>{b.cites.caution}</span>
          <span style={{ ...rs.statDelta, color: Tbr.color.text.tertiary }}>need review</span>
        </div>
        <div style={rs.stat}>
          <span style={rs.statLabel}>Assigned</span>
          <div style={{ display: 'flex', gap: '2px', marginTop: '4px' }}>
            {d.assignedTo.map(a => (
              <span key={a} title={a} style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: '24px', height: '24px', borderRadius: '50%', background: rs.indigo, color: '#fff', fontSize: '10px', fontWeight: 700 }}>
                {a.split(' ').map(p => p[0]).join('').slice(0, 2)}
              </span>
            ))}
          </div>
          <span style={{ ...rs.statDelta, color: Tbr.color.text.tertiary, marginTop: '6px' }}>+ {d.reviewers.length} reviewer{d.reviewers.length === 1 ? '' : 's'}</span>
        </div>
        <div style={rs.stat}>
          <span style={rs.statLabel}>Due</span>
          <span style={{ ...rs.statValue, fontSize: '16px', color: Tbr.color.text.primary, marginTop: '4px' }}>{b.due}</span>
          <span style={{ ...rs.statDelta, color: Tbr.color.text.tertiary }}>{d.filingEvent}</span>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: '16px' }}>
        {/* Sections + Cites column */}
        <div>
          <div style={rs.card}>
            <div style={rs.cardH}>Table of contents · section progress</div>
            <div>
              {d.sections.map((s, i) => {
                const ssc = sectionStatusColor(s.status);
                const pct = Math.round((s.words / s.target) * 100);
                return (
                  <div key={s.id} style={{ padding: '12px 16px', borderBottom: i < d.sections.length - 1 ? `1px solid ${Tbr.color.border.light}` : 'none' }}>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '6px' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flex: 1, minWidth: 0 }}>
                        <span style={{ fontFamily: Tbr.font.mono, fontSize: '10px', color: Tbr.color.text.tertiary, minWidth: '22px' }}>{s.id}</span>
                        <span style={{ fontSize: '12px', fontWeight: 600, color: Tbr.color.text.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.title}</span>
                      </div>
                      <div style={{ display: 'flex', gap: '6px', alignItems: 'center' }}>
                        <span style={{ ...rs.tag, background: ssc.bg, color: ssc.color }}>{s.status}</span>
                        <span style={{ ...rs.tag, background: rs.indigoBg, color: rs.indigo }}>{s.cites} cites</span>
                      </div>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                      <div style={{ flex: 1, height: '4px', background: Tbr.color.border.light, borderRadius: '2px', overflow: 'hidden' }}>
                        <div style={{ width: `${Math.min(100, pct)}%`, height: '100%', background: pct >= 95 ? '#1B7A4A' : pct >= 40 ? rs.indigo : rs.amber }} />
                      </div>
                      <span style={{ fontFamily: Tbr.font.mono, fontSize: '10px', color: Tbr.color.text.tertiary, minWidth: '80px', textAlign: 'right' }}>{s.words.toLocaleString()} / {s.target.toLocaleString()}</span>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          <div style={rs.card}>
            <div style={rs.cardH}>
              <span>Brief authorities — {d.cites.length}</span>
              <button style={rs.btnGhost}>Re-verify all ◆</button>
            </div>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr>
                  <th style={rs.th}>Authority</th>
                  <th style={rs.th}>Section</th>
                  <th style={rs.th}>Pincite</th>
                  <th style={rs.th}>Context</th>
                  <th style={rs.th}>Signal</th>
                </tr>
              </thead>
              <tbody>
                {d.cites.map(c => {
                  const sig = c.signal === 'positive' ? rs.signalPositive
                    : c.signal === 'caution' ? rs.signalCaution
                    : c.signal === 'negative' ? rs.signalNegative
                    : rs.signalNeutral;
                  return (
                    <tr key={c.id}>
                      <td style={rs.td}>
                        <div style={{ fontSize: '12px', fontWeight: 600, color: Tbr.color.text.primary }}>{c.short}</div>
                        <div style={{ fontSize: '11px', color: Tbr.color.text.secondary, marginTop: '3px', lineHeight: 1.5 }}>{c.note}</div>
                      </td>
                      <td style={{ ...rs.td, fontFamily: Tbr.font.mono, fontSize: '11px', color: Tbr.color.text.tertiary }}>{c.section}</td>
                      <td style={{ ...rs.td, fontFamily: Tbr.font.mono, fontSize: '11px', color: Tbr.color.text.secondary }}>{c.pincite}</td>
                      <td style={{ ...rs.td, color: Tbr.color.text.secondary }}>{c.context}</td>
                      <td style={rs.td}><span style={{ ...rs.tag, ...sig }}>{c.signal}</span></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>

        {/* Comments + Changes + Bundles column */}
        <div>
          <div style={rs.card}>
            <div style={rs.cardH}>Comments · {d.comments.length}</div>
            <div>
              {d.comments.map((c, i) => (
                <div key={c.id} style={{ padding: '12px 16px', borderBottom: i < d.comments.length - 1 ? `1px solid ${Tbr.color.border.light}` : 'none', display: 'flex', gap: '10px' }}>
                  <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: '28px', height: '28px', borderRadius: '50%', background: rs.indigo, color: '#fff', fontSize: '11px', fontWeight: 700, flexShrink: 0 }}>{c.initials}</span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', gap: '8px', alignItems: 'baseline', marginBottom: '3px' }}>
                      <span style={{ fontSize: '12px', fontWeight: 600, color: Tbr.color.text.primary }}>{c.author}</span>
                      <span style={{ fontSize: '10px', color: Tbr.color.text.tertiary }}>· {c.time}</span>
                      <span style={{ ...rs.tag, background: rs.indigoBg, color: rs.indigo, marginLeft: 'auto' }}>{c.section}</span>
                    </div>
                    <div style={{ fontSize: '12px', color: Tbr.color.text.secondary, lineHeight: 1.55 }}>{c.text}</div>
                  </div>
                </div>
              ))}
              {d.comments.length === 0 && <div style={{ padding: '20px', textAlign: 'center', fontSize: '12px', color: Tbr.color.text.tertiary }}>No comments yet.</div>}
            </div>
          </div>

          <div style={rs.card}>
            <div style={rs.cardH}>Recent changes</div>
            <div style={{ padding: '10px 16px' }}>
              {d.changes.map((ch, i) => {
                const sev = ch.severity === 'warn' ? { bg: rs.amberBg, color: rs.amber } : { bg: rs.indigoBg, color: rs.indigo };
                return (
                  <div key={i} style={{ padding: '8px 0', borderBottom: i < d.changes.length - 1 ? `1px solid ${Tbr.color.border.light}` : 'none', display: 'flex', gap: '12px' }}>
                    <div style={{ width: '70px', fontFamily: Tbr.font.mono, fontSize: '10px', color: Tbr.color.text.tertiary, flexShrink: 0 }}>{ch.time}</div>
                    <div style={{ flex: 1, fontSize: '12px', color: Tbr.color.text.primary }}>
                      <span style={{ fontWeight: 600 }}>{ch.actor}</span> <span style={{ color: Tbr.color.text.secondary }}>— {ch.action}</span>
                    </div>
                    {ch.severity === 'warn' && <span style={{ ...rs.tag, background: sev.bg, color: sev.color }}><Icons.Alert size={11}/></span>}
                  </div>
                );
              })}
            </div>
          </div>

          <div style={rs.card}>
            <div style={rs.cardH}>Linked research bundles</div>
            <div style={{ padding: '8px 16px 14px' }}>
              {d.linkedBundles.map(lb => (
                <div key={lb} style={{ padding: '8px 0', borderBottom: `1px solid ${Tbr.color.border.light}`, display: 'flex', alignItems: 'center', gap: '10px' }}>
                  <span style={{ ...rs.tag, background: rs.indigoBg, color: rs.indigo, fontFamily: Tbr.font.mono }}>{lb}</span>
                  <span style={{ flex: 1, fontSize: '11px', color: Tbr.color.text.secondary }}>Imported from workspace</span>
                  <button style={rs.btnGhost}>Open →</button>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Cite Checker — cross-brief authority health ─────────────────
function BriefsCiteChecker({ data }) {
  const rs = window.__rs;
  // Aggregate all cites across briefs that have details
  const allCites = [];
  Object.entries(data.briefDetails).forEach(([bid, bd]) => {
    bd.cites.forEach(c => {
      allCites.push({ ...c, briefId: bid, briefTitle: data.briefs.find(b => b.id === bid)?.title || bid });
    });
  });
  const green = allCites.filter(c => c.signal === 'positive').length;
  const caution = allCites.filter(c => c.signal === 'caution').length;
  const negative = allCites.filter(c => c.signal === 'negative').length;

  const needAttention = allCites.filter(c => c.signal !== 'positive');

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={rs.stat}>
          <span style={rs.statLabel}>Cites verified</span>
          <span style={{ ...rs.statValue, color: '#1B7A4A' }}>{green}</span>
          <span style={{ ...rs.statDelta, color: Tbr.color.text.tertiary }}>of {allCites.length} tracked</span>
        </div>
        <div style={rs.stat}>
          <span style={rs.statLabel}>Caution</span>
          <span style={{ ...rs.statValue, color: rs.amber }}>{caution}</span>
          <span style={{ ...rs.statDelta, color: Tbr.color.text.tertiary }}>review recommended</span>
        </div>
        <div style={rs.stat}>
          <span style={rs.statLabel}>Negative</span>
          <span style={{ ...rs.statValue, color: '#C23030' }}>{negative}</span>
          <span style={{ ...rs.statDelta, color: Tbr.color.text.tertiary }}>replace or distinguish</span>
        </div>
        <div style={rs.stat}>
          <span style={rs.statLabel}>Overall health</span>
          <span style={{ ...rs.statValue, color: '#1B7A4A' }}>{allCites.length ? Math.round(green / allCites.length * 100) : 100}%</span>
          <span style={{ ...rs.statDelta, color: Tbr.color.text.tertiary }}>across {Object.keys(data.briefDetails).length} briefs</span>
        </div>
      </div>

      <div style={rs.card}>
        <div style={rs.cardH}>
          <span>Authorities needing attention — {needAttention.length}</span>
          <button style={rs.btnSecondary}>Run Shepard batch ◆</button>
        </div>
        {needAttention.length > 0 ? (
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={rs.th}>Authority</th>
                <th style={rs.th}>In brief</th>
                <th style={rs.th}>Section</th>
                <th style={rs.th}>Pincite</th>
                <th style={rs.th}>Signal</th>
                <th style={rs.th}>Action</th>
              </tr>
            </thead>
            <tbody>
              {needAttention.map((c, i) => {
                const sig = c.signal === 'caution' ? rs.signalCaution : c.signal === 'negative' ? rs.signalNegative : rs.signalNeutral;
                return (
                  <tr key={`${c.briefId}-${c.id}-${i}`}>
                    <td style={{ ...rs.td, maxWidth: '260px' }}>
                      <div style={{ fontSize: '12px', fontWeight: 600, color: Tbr.color.text.primary }}>{c.short}</div>
                      <div style={{ fontSize: '11px', color: Tbr.color.text.secondary, marginTop: '3px', lineHeight: 1.5 }}>{c.note}</div>
                    </td>
                    <td style={{ ...rs.td, color: Tbr.color.text.secondary, maxWidth: '220px' }}>{c.briefTitle}</td>
                    <td style={{ ...rs.td, fontFamily: Tbr.font.mono, fontSize: '11px', color: Tbr.color.text.tertiary }}>{c.section}</td>
                    <td style={{ ...rs.td, fontFamily: Tbr.font.mono, fontSize: '11px', color: Tbr.color.text.secondary }}>{c.pincite}</td>
                    <td style={rs.td}><span style={{ ...rs.tag, ...sig }}>{c.signal}</span></td>
                    <td style={rs.td}>
                      <button style={rs.btnGhost}>Open brief →</button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        ) : (
          <div style={{ padding: '28px', textAlign: 'center', fontSize: '12px', color: Tbr.color.text.tertiary }}>All tracked authorities are verified. Run a batch Shepard check to refresh.</div>
        )}
      </div>
    </div>
  );
}

// ── Templates ─────────────────
function BriefsTemplates({ data }) {
  const rs = window.__rs;
  const [cat, setCat] = useBriefState('All');
  const cats = useBriefMemo(() => ['All', ...new Set(data.briefTemplates.map(t => t.category))], [data]);
  const filtered = data.briefTemplates.filter(t => cat === 'All' || t.category === cat);

  return (
    <div>
      <div style={{ display: 'flex', gap: '8px', marginBottom: '14px' }}>
        {cats.map(c => (
          <button key={c} onClick={() => setCat(c)} style={{
            padding: '4px 12px', borderRadius: '12px', border: `1px solid ${cat === c ? rs.indigo : Tbr.color.border.light}`,
            background: cat === c ? rs.indigoBg : Tbr.color.bg.card, color: cat === c ? rs.indigo : Tbr.color.text.secondary,
            fontSize: '11px', fontWeight: 500, cursor: 'pointer', fontFamily: Tbr.font.family,
          }}>{c}</button>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(380px, 1fr))', gap: '14px' }}>
        {filtered.map(t => (
          <div key={t.id} style={{ ...rs.card, marginBottom: 0 }}>
            <div style={{ padding: '14px 16px', borderBottom: `1px solid ${Tbr.color.border.light}`, background: 'linear-gradient(135deg, rgba(67,56,202,0.04) 0%, transparent 100%)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>
                <span style={{ ...rs.tag, background: rs.indigoBg, color: rs.indigo }}>{t.category}</span>
                <span style={{ fontSize: '10px', color: Tbr.color.text.tertiary }}>{t.jurisdiction}</span>
              </div>
              <div style={{ fontSize: '14px', fontWeight: 700, color: Tbr.color.text.primary }}>{t.name}</div>
            </div>
            <div style={{ padding: '14px 16px' }}>
              <div style={{ fontSize: '12px', color: Tbr.color.text.secondary, lineHeight: 1.55, marginBottom: '12px', minHeight: '44px' }}>{t.description}</div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '10px', marginBottom: '12px' }}>
                <div>
                  <div style={{ fontSize: '9px', color: Tbr.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Words</div>
                  <div style={{ fontSize: '13px', fontWeight: 600, color: Tbr.color.text.primary, fontFamily: Tbr.font.mono }}>{t.words.toLocaleString()}</div>
                </div>
                <div>
                  <div style={{ fontSize: '9px', color: Tbr.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Sections</div>
                  <div style={{ fontSize: '13px', fontWeight: 600, color: Tbr.color.text.primary, fontFamily: Tbr.font.mono }}>{t.sections}</div>
                </div>
                <div>
                  <div style={{ fontSize: '9px', color: Tbr.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Used</div>
                  <div style={{ fontSize: '13px', fontWeight: 600, color: rs.indigo, fontFamily: Tbr.font.mono }}>{t.usedBy}×</div>
                </div>
              </div>
              {t.coreCites.length > 0 && (
                <div style={{ marginBottom: '12px' }}>
                  <div style={{ fontSize: '9px', color: Tbr.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '4px' }}>Core citations</div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: '3px' }}>
                    {t.coreCites.map(c => <span key={c} style={{ ...rs.tag, background: Tbr.color.bg.secondary, color: Tbr.color.text.secondary, fontFamily: Tbr.font.mono }}>{c}</span>)}
                  </div>
                </div>
              )}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: '10px', borderTop: `1px solid ${Tbr.color.border.light}` }}>
                <span style={{ fontSize: '10px', color: Tbr.color.text.tertiary }}>{t.author} · updated {t.updated}</span>
                <button style={rs.btnPrimary}>Use template →</button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Activity — cross-brief activity stream ─────────────────
function BriefsActivity({ data }) {
  const rs = window.__rs;
  const stream = [];
  Object.entries(data.briefDetails).forEach(([bid, bd]) => {
    const title = data.briefs.find(b => b.id === bid)?.title;
    bd.changes.forEach((ch, i) => stream.push({ ...ch, briefId: bid, briefTitle: title, key: `${bid}-${i}` }));
  });

  return (
    <div style={rs.card}>
      <div style={rs.cardH}>
        <span>Activity across all briefs — {stream.length} events</span>
        <button style={rs.btnSecondary}>Export CSV</button>
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr>
            <th style={rs.th}>When</th>
            <th style={rs.th}>Brief</th>
            <th style={rs.th}>Actor</th>
            <th style={rs.th}>Action</th>
            <th style={rs.th}>Severity</th>
          </tr>
        </thead>
        <tbody>
          {stream.map(ev => {
            const sev = ev.severity === 'warn' ? { bg: rs.amberBg, color: rs.amber }
              : ev.severity === 'error' ? { bg: 'rgba(194,48,48,0.08)', color: '#C23030' }
              : { bg: rs.indigoBg, color: rs.indigo };
            return (
              <tr key={ev.key}>
                <td style={{ ...rs.td, fontFamily: Tbr.font.mono, color: Tbr.color.text.tertiary, fontSize: '11px' }}>{ev.time}</td>
                <td style={{ ...rs.td, color: Tbr.color.text.primary, fontWeight: 500, maxWidth: '280px' }}>{ev.briefTitle}</td>
                <td style={{ ...rs.td, color: Tbr.color.text.primary, fontWeight: 500 }}>
                  <span style={{ display: 'inline-block', width: '6px', height: '6px', borderRadius: '50%', background: sev.color, marginRight: '8px' }} />
                  {ev.actor}
                </td>
                <td style={{ ...rs.td, color: Tbr.color.text.secondary }}>{ev.action}</td>
                <td style={rs.td}><span style={{ ...rs.tag, background: sev.bg, color: sev.color }}>{ev.severity}</span></td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

// ── Entry — sub-nav pill bar ─────────────────
function ResearchBriefs({ data }) {
  const rs = window.__rs;
  const [sub, setSub] = useBriefState('overview');
  const [openBriefId, setOpenBriefId] = useBriefState(null);

  const subs = [
    { id: 'overview', label: 'Overview' },
    { id: 'detail', label: 'Brief detail', disabled: !openBriefId },
    { id: 'checker', label: 'Cite Checker' },
    { id: 'templates', label: 'Templates' },
    { id: 'activity', label: 'Activity' },
  ];

  const handleOpen = (bid) => { setOpenBriefId(bid); setSub('detail'); };

  return (
    <div>
      {/* Sub-nav pill bar */}
      <div style={{ display: 'flex', gap: '6px', marginBottom: '16px', padding: '4px', background: Tbr.color.bg.secondary, borderRadius: '8px', border: `1px solid ${Tbr.color.border.light}`, alignSelf: 'flex-start', width: 'fit-content' }}>
        {subs.map(s => (
          <button key={s.id} onClick={() => !s.disabled && setSub(s.id)} disabled={s.disabled} style={{
            padding: '5px 14px', borderRadius: '5px', border: 'none',
            background: sub === s.id ? Tbr.color.bg.card : 'transparent',
            color: s.disabled ? Tbr.color.text.tertiary : sub === s.id ? rs.indigo : Tbr.color.text.secondary,
            fontSize: '11px', fontWeight: sub === s.id ? 700 : 500, cursor: s.disabled ? 'not-allowed' : 'pointer',
            fontFamily: Tbr.font.family, boxShadow: sub === s.id ? '0 1px 2px rgba(10,22,40,0.06)' : 'none',
            opacity: s.disabled ? 0.5 : 1,
          }}>{s.label}</button>
        ))}
      </div>

      {sub === 'overview' && <BriefsOverview data={data} onOpen={handleOpen} />}
      {sub === 'detail' && openBriefId && <BriefDetail data={data} briefId={openBriefId} onBack={() => setSub('overview')} />}
      {sub === 'checker' && <BriefsCiteChecker data={data} />}
      {sub === 'templates' && <BriefsTemplates data={data} />}
      {sub === 'activity' && <BriefsActivity data={data} />}
    </div>
  );
}

window.ResearchBriefs = ResearchBriefs;
