// RESEARCH PLATFORM — hub sub-platforms + pill sub-nav
// 10 hubs: Search · Case Law · Statutes · Regulations · Secondary · Citator · Briefs · Workspace · Analytics · Activity
const { useState: useRsH, useMemo: useRsHMemo } = React;
const Trsh = window.ArbiterTokens;

// ── Shared pill sub-nav ─────────────────────────────────────────────────────
function RsSubNav({ views, active, onChange }) {
  const rs = window.__rs;
  return (
    <div style={{
      display: 'flex', gap: '4px', padding: '6px',
      background: Trsh.color.bg.secondary,
      border: `1px solid ${Trsh.color.border.light}`,
      borderRadius: '8px', marginBottom: '16px', flexWrap: 'wrap',
    }}>
      {views.map(v => {
        const isActive = active === v.id;
        return (
          <button key={v.id} onClick={() => onChange(v.id)} style={{
            padding: '6px 12px', fontSize: '11px',
            fontWeight: isActive ? 700 : 500,
            borderRadius: '6px', border: 'none', cursor: 'pointer',
            background: isActive ? rs.indigo : 'transparent',
            color: isActive ? '#fff' : Trsh.color.text.secondary,
            display: 'inline-flex', alignItems: 'center', gap: '6px',
            transition: 'all 0.12s', fontFamily: Trsh.font.family,
          }}>
            {v.label}
            {v.badge != null && (
              <span style={{
                fontSize: '10px', fontWeight: 700,
                padding: '1px 6px', borderRadius: '8px',
                background: isActive ? 'rgba(255,255,255,0.22)' : Trsh.color.bg.card,
                color: isActive ? '#fff' : Trsh.color.text.tertiary,
                fontFamily: Trsh.font.mono,
              }}>{v.badge}</span>
            )}
          </button>
        );
      })}
    </div>
  );
}
window.RsSubNav = RsSubNav;

// ── Shared helper: simple sortable table section header ─────────────────────
function rsCardHeader(rs, title, badge) {
  return (
    <div style={rs.cardH}>
      <span>{title}</span>
      {badge != null && <span style={{ fontSize: '11px', color: Trsh.color.text.tertiary, fontWeight: 500 }}>{badge}</span>}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// SEARCH — new sub-views
// ═══════════════════════════════════════════════════════════════════════════

function RsSearchHistory({ data }) {
  const rs = window.__rs;
  const [search, setSearch] = useRsH('');
  const [matterFilter, setMatterFilter] = useRsH('All');
  const matters = ['All', ...new Set(data.history.map(h => h.matter))];
  const filtered = data.history.filter(h =>
    (matterFilter === 'All' || h.matter === matterFilter) &&
    (!search || h.query.toLowerCase().includes(search.toLowerCase()))
  );
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={rs.stat}><span style={rs.statLabel}>Shown</span><span style={rs.statValue}>{filtered.length}</span><span style={{ ...rs.statDelta, color: Trsh.color.text.tertiary }}>of {data.history.length}</span></div>
        <div style={rs.stat}><span style={rs.statLabel}>Saved</span><span style={{ ...rs.statValue, color: rs.indigo }}>{data.history.filter(h => h.saved).length}</span></div>
        <div style={rs.stat}><span style={rs.statLabel}>Matters</span><span style={rs.statValue}>{new Set(data.history.map(h => h.matter)).size}</span></div>
        <div style={rs.stat}><span style={rs.statLabel}>Avg results</span><span style={{ ...rs.statValue, color: rs.teal }}>{Math.round(data.history.reduce((a,h) => a + h.results, 0) / data.history.length)}</span></div>
      </div>

      <div style={rs.card}>
        <div style={rs.cardH}>
          <span>Query history</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search queries…"
              style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Trsh.color.border.light}`, borderRadius: '5px', background: Trsh.color.bg.card, minWidth: '200px', fontFamily: Trsh.font.family }} />
            <select value={matterFilter} onChange={e => setMatterFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Trsh.color.border.light}`, borderRadius: '5px', background: Trsh.color.bg.card, color: Trsh.color.text.secondary }}>
              {matters.map(m => <option key={m} value={m}>{m.length > 22 ? m.slice(0, 20) + '…' : m}</option>)}
            </select>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr>
            <th style={rs.th}>ID</th>
            <th style={rs.th}>Query</th>
            <th style={rs.th}>Matter</th>
            <th style={rs.th}>Author</th>
            <th style={rs.th}>Jurisdictions</th>
            <th style={{ ...rs.th, textAlign: 'right' }}>Results</th>
            <th style={{ ...rs.th, textAlign: 'right' }}>When</th>
            <th style={rs.th}>Saved</th>
          </tr></thead>
          <tbody>{filtered.map(h => (
            <tr key={h.id}>
              <td style={{ ...rs.td, fontFamily: Trsh.font.mono, color: rs.indigo, fontWeight: 700 }}>{h.id}</td>
              <td style={{ ...rs.td, maxWidth: '360px', fontWeight: 500 }}>{h.query}</td>
              <td style={{ ...rs.td, fontSize: '11px', color: Trsh.color.text.secondary }}>{h.matter}</td>
              <td style={{ ...rs.td, fontSize: '11px' }}>{h.author}</td>
              <td style={{ ...rs.td, fontSize: '10px' }}>{h.jurisdictions.map(j => <span key={j} style={{ ...rs.tag, background: rs.indigoBg, color: rs.indigo, marginRight: '4px' }}>{j}</span>)}</td>
              <td style={{ ...rs.td, textAlign: 'right', fontFamily: Trsh.font.mono, color: rs.indigo, fontWeight: 700 }}>{h.results}</td>
              <td style={{ ...rs.td, textAlign: 'right', fontSize: '10px', color: Trsh.color.text.tertiary }}>{h.time}</td>
              <td style={rs.td}>{h.saved ? <span style={{ ...rs.tag, background: rs.indigoBg, color: rs.indigo }}>* Saved</span> : <button style={rs.btnGhost}>Save</button>}</td>
            </tr>
          ))}</tbody>
        </table>
      </div>
    </div>
  );
}
window.RsSearchHistory = RsSearchHistory;

function RsSearchSaved({ data }) {
  const rs = window.__rs;
  const saved = data.history.filter(h => h.saved);
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '12px' }}>
      {saved.map(q => (
        <div key={q.id} style={rs.card}>
          <div style={rs.cardH}>
            <div>
              <div style={{ fontSize: '12px', fontFamily: Trsh.font.mono, color: rs.indigo, fontWeight: 700 }}>{q.id}</div>
              <div style={{ fontSize: '10px', color: Trsh.color.text.tertiary, marginTop: '2px' }}>Saved · {q.time} · {q.author}</div>
            </div>
            <span style={{ ...rs.tag, background: rs.indigoBg, color: rs.indigo }}>* Pinned</span>
          </div>
          <div style={{ padding: '12px 16px' }}>
            <div style={{ fontSize: '13px', fontWeight: 600, marginBottom: '8px' }}>{q.query}</div>
            <div style={{ display: 'flex', gap: '4px', marginBottom: '10px', flexWrap: 'wrap' }}>
              {q.jurisdictions.map(j => <span key={j} style={{ ...rs.tag, background: rs.indigoBg, color: rs.indigo }}>{j}</span>)}
            </div>
            <div style={{ fontSize: '10px', color: Trsh.color.text.tertiary, marginBottom: '10px' }}>{q.matter} · <span style={{ fontFamily: Trsh.font.mono, color: rs.indigo }}>{q.results} results</span></div>
            <div style={{ display: 'flex', gap: '6px' }}>
              <button style={rs.btnSecondary}>Re-run</button>
              <button style={rs.btnGhost}>Edit query</button>
              <button style={rs.btnGhost}>Create alert</button>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}
window.RsSearchSaved = RsSearchSaved;

function RsSearchAlerts({ data }) {
  const rs = window.__rs;
  const alerts = useRsHMemo(() => data.history.filter(h => h.saved).map((q, i) => ({
    ...q,
    status: ['active','active','paused','active'][i % 4],
    frequency: ['Daily','Weekly','Weekly','Hourly'][i % 4],
    newHits: [3, 0, 12, 1, 0][i % 5],
    nextRun: ['2h','1d','3d','15m'][i % 4],
  })), [data]);
  return (
    <div>
      <div style={{ padding: '12px 16px', background: rs.indigoBg, border: `1px solid ${rs.indigoBorder}`, borderRadius: '8px', marginBottom: '16px', display: 'flex', alignItems: 'center', gap: '12px' }}>
        <span style={{ fontSize: '16px', color: rs.indigo }}>◉</span>
        <div>
          <div style={{ fontSize: '13px', fontWeight: 700, color: rs.indigo }}>{alerts.filter(a => a.newHits > 0).length} alert{alerts.filter(a => a.newHits > 0).length === 1 ? '' : 's'} with new results since last check</div>
          <div style={{ fontSize: '11px', color: Trsh.color.text.secondary, marginTop: '2px' }}>Saved queries become topic alerts that re-run on your schedule — new hits surface here and in Activity.</div>
        </div>
      </div>

      <div style={rs.card}>
        {rsCardHeader(rs, 'Active alerts', `${alerts.length} subscriptions`)}
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr>
            <th style={rs.th}>Query</th>
            <th style={rs.th}>Matter</th>
            <th style={rs.th}>Frequency</th>
            <th style={{ ...rs.th, textAlign: 'right' }}>New hits</th>
            <th style={rs.th}>Next run</th>
            <th style={rs.th}>Status</th>
            <th style={{ ...rs.th, textAlign: 'right' }}>Action</th>
          </tr></thead>
          <tbody>{alerts.map(a => (
            <tr key={a.id}>
              <td style={{ ...rs.td, maxWidth: '360px', fontWeight: 500 }}>{a.query}<div style={{ fontSize: '10px', color: Trsh.color.text.tertiary, fontFamily: Trsh.font.mono, marginTop: '2px' }}>{a.id}</div></td>
              <td style={{ ...rs.td, fontSize: '11px', color: Trsh.color.text.secondary }}>{a.matter}</td>
              <td style={rs.td}><span style={{ ...rs.tag, background: Trsh.color.bg.secondary, color: Trsh.color.text.secondary }}>{a.frequency}</span></td>
              <td style={{ ...rs.td, textAlign: 'right', fontFamily: Trsh.font.mono, fontWeight: 700, color: a.newHits > 0 ? rs.indigo : Trsh.color.text.tertiary }}>{a.newHits === 0 ? '—' : `+${a.newHits}`}</td>
              <td style={{ ...rs.td, fontFamily: Trsh.font.mono, fontSize: '10px', color: Trsh.color.text.tertiary }}>in {a.nextRun}</td>
              <td style={rs.td}>{a.status === 'active' ? <span style={{ ...rs.tag, background: rs.tealBg, color: rs.teal }}>● Active</span> : <span style={{ ...rs.tag, background: rs.amberBg, color: rs.amber }}> Paused</span>}</td>
              <td style={{ ...rs.td, textAlign: 'right' }}><button style={rs.btnGhost}>{a.status === 'active' ? 'Pause' : 'Resume'}</button></td>
            </tr>
          ))}</tbody>
        </table>
      </div>
    </div>
  );
}
window.RsSearchAlerts = RsSearchAlerts;

// ═══════════════════════════════════════════════════════════════════════════
// CASE LAW — new sub-views
// ═══════════════════════════════════════════════════════════════════════════

function RsCasesByCourt({ data }) {
  const rs = window.__rs;
  const breakdown = data.courtBreakdown;
  const max = Math.max(...breakdown.map(c => c.cases));
  return (
    <div style={rs.card}>
      {rsCardHeader(rs, 'Case law — by court', `${breakdown.length} courts · ${breakdown.reduce((a,c) => a + c.cases, 0)} cases indexed`)}
      <div style={{ padding: '8px 0' }}>{breakdown.map(c => (
        <div key={c.court} style={{ display: 'grid', gridTemplateColumns: '200px 1fr 100px 80px', gap: '16px', alignItems: 'center', padding: '10px 16px', borderBottom: `1px solid ${Trsh.color.border.light}` }}>
          <span style={{ fontSize: '12px', fontWeight: 700 }}>{c.court}</span>
          <div style={{ height: '8px', background: Trsh.color.bg.secondary, borderRadius: '4px', overflow: 'hidden' }}>
            <div style={{ width: `${(c.cases / max) * 100}%`, height: '100%', background: c.signal === 'binding' ? rs.indigo : rs.teal, borderRadius: '4px' }} />
          </div>
          <span style={{ ...rs.tag, background: c.signal === 'binding' ? rs.indigoBg : rs.tealBg, color: c.signal === 'binding' ? rs.indigo : rs.teal, textTransform: 'capitalize', justifySelf: 'start' }}>{c.signal}</span>
          <span style={{ fontSize: '14px', fontFamily: Trsh.font.mono, fontWeight: 700, textAlign: 'right', color: rs.indigo }}>{c.cases}</span>
        </div>
      ))}</div>
    </div>
  );
}
window.RsCasesByCourt = RsCasesByCourt;

function RsCasesByTopic({ data }) {
  const rs = window.__rs;
  const groups = useRsHMemo(() => {
    const g = {};
    data.cases.forEach(c => {
      if (!g[c.topic]) g[c.topic] = { topic: c.topic, cases: [], totalCites: 0 };
      g[c.topic].cases.push(c);
      g[c.topic].totalCites += c.cites;
    });
    return Object.values(g).sort((a,b) => b.cases.length - a.cases.length);
  }, [data]);
  const sig = (s) => ({ positive: { bg: rs.tealBg, c: rs.teal }, caution: { bg: rs.amberBg, c: rs.amber }, negative: { bg: rs.crimsonBg, c: rs.crimson } }[s] || { bg: Trsh.color.bg.secondary, c: Trsh.color.text.secondary });
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '12px' }}>
      {groups.map(g => (
        <div key={g.topic} style={rs.card}>
          <div style={rs.cardH}>
            <div>
              <div style={{ fontSize: '13px', fontWeight: 700 }}>{g.topic}</div>
              <div style={{ fontSize: '10px', color: Trsh.color.text.tertiary, marginTop: '2px' }}>{g.cases.length} case{g.cases.length === 1 ? '' : 's'} · {g.totalCites.toLocaleString()} downstream cites</div>
            </div>
            <span style={{ ...rs.tag, background: rs.indigoBg, color: rs.indigo, fontWeight: 700 }}>{g.cases.length}</span>
          </div>
          <div>{g.cases.map(c => {
            const s = sig(c.signal);
            return (
              <div key={c.id} style={{ display: 'flex', alignItems: 'center', gap: '10px', padding: '8px 16px', borderBottom: `1px solid ${Trsh.color.border.light}` }}>
                <span style={{ ...rs.tag, background: s.bg, color: s.c, fontSize: '9px', textTransform: 'capitalize' }}>{c.signal}</span>
                <div style={{ flex: 1, fontSize: '11px' }}>
                  <div style={{ fontWeight: 700 }}>{c.shortCite}</div>
                  <div style={{ fontSize: '10px', color: Trsh.color.text.tertiary, marginTop: '1px' }}>{c.court} · {c.year} · {c.cites.toLocaleString()} citing refs</div>
                </div>
              </div>
            );
          })}</div>
        </div>
      ))}
    </div>
  );
}
window.RsCasesByTopic = RsCasesByTopic;

function RsCasesFlagged({ data }) {
  const rs = window.__rs;
  const flagged = data.cases.filter(c => c.signal !== 'positive');
  return (
    <div>
      <div style={{ padding: '12px 16px', background: rs.crimsonBg, border: `1px solid ${rs.crimson}30`, borderRadius: '8px', marginBottom: '16px', display: 'flex', alignItems: 'center', gap: '12px' }}>
        <span style={{ fontSize: '18px', color: rs.crimson }}><Icons.Alert size={11}/></span>
        <div>
          <div style={{ fontSize: '13px', fontWeight: 700, color: rs.crimson }}>{flagged.length} authorities need review</div>
          <div style={{ fontSize: '11px', color: Trsh.color.text.secondary, marginTop: '2px' }}>Cases with caution, negative, or overruled treatment signals — verify before citing.</div>
        </div>
      </div>

      <div style={{ display: 'grid', gap: '10px' }}>
        {flagged.map(c => {
          const clr = c.signal === 'negative' ? rs.crimson : c.signal === 'caution' ? rs.amber : Trsh.color.text.secondary;
          const bg  = c.signal === 'negative' ? rs.crimsonBg : c.signal === 'caution' ? rs.amberBg : Trsh.color.bg.secondary;
          return (
            <div key={c.id} style={{ ...rs.card, marginBottom: 0, borderLeft: `3px solid ${clr}` }}>
              <div style={{ padding: '12px 16px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '6px' }}>
                  <span style={{ fontSize: '13px', fontWeight: 700 }}>{c.shortCite}</span>
                  <span style={{ ...rs.tag, background: bg, color: clr, textTransform: 'capitalize' }}>{c.signal}</span>
                  <span style={{ ...rs.tag, background: Trsh.color.bg.secondary, color: Trsh.color.text.secondary }}>{c.court} · {c.year}</span>
                </div>
                <div style={{ fontSize: '11px', color: Trsh.color.text.secondary, fontFamily: Trsh.font.mono, marginBottom: '8px' }}>{c.cite}</div>
                <div style={{ fontSize: '11px', color: Trsh.color.text.primary, marginBottom: '10px' }}>{c.headnote}</div>
                <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
                  <span style={{ fontSize: '10px', color: Trsh.color.text.tertiary, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Used in</span>
                  {c.usedIn.length === 0 ? <span style={{ fontSize: '11px', color: Trsh.color.text.tertiary, fontStyle: 'italic' }}>No active matter</span> : c.usedIn.map(m => <span key={m} style={{ ...rs.tag, background: rs.indigoBg, color: rs.indigo }}>{m}</span>)}
                  <div style={{ flex: 1 }} />
                  <button style={rs.btnSecondary}>Run Shepard</button>
                  <button style={rs.btnGhost}>Find replacement →</button>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
window.RsCasesFlagged = RsCasesFlagged;

// ═══════════════════════════════════════════════════════════════════════════
// STATUTES — new sub-views
// ═══════════════════════════════════════════════════════════════════════════

function RsStatByJuris({ data }) {
  const rs = window.__rs;
  const groups = useRsHMemo(() => {
    const g = {};
    data.statutes.forEach(s => { if (!g[s.jurisdiction]) g[s.jurisdiction] = []; g[s.jurisdiction].push(s); });
    return Object.entries(g).sort((a,b) => b[1].length - a[1].length);
  }, [data]);
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '12px' }}>
      {groups.map(([juris, list]) => (
        <div key={juris} style={rs.card}>
          <div style={rs.cardH}>
            <span style={{ fontSize: '13px', fontWeight: 700 }}>{juris}</span>
            <span style={{ ...rs.tag, background: rs.indigoBg, color: rs.indigo }}>{list.length} statute{list.length === 1 ? '' : 's'}</span>
          </div>
          <div>{list.map(s => (
            <div key={s.id} style={{ padding: '10px 16px', borderBottom: `1px solid ${Trsh.color.border.light}` }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '3px' }}>
                <span style={{ fontSize: '12px', fontWeight: 700, fontFamily: Trsh.font.mono, color: rs.indigo }}>{s.short}</span>
                <span style={{ fontSize: '10px', color: Trsh.color.text.tertiary }}>{s.cite}</span>
              </div>
              <div style={{ fontSize: '11px', color: Trsh.color.text.primary, marginBottom: '4px' }}>{s.title}</div>
              <div style={{ fontSize: '10px', color: Trsh.color.text.tertiary }}>Last amended {s.lastAmended} · used in {s.usedIn.length} matter{s.usedIn.length === 1 ? '' : 's'}</div>
            </div>
          ))}</div>
        </div>
      ))}
    </div>
  );
}
window.RsStatByJuris = RsStatByJuris;

function RsStatAmendments({ data }) {
  const rs = window.__rs;
  const ranked = useRsHMemo(() => [...data.statutes].sort((a,b) => (b.lastAmended || '').localeCompare(a.lastAmended || '')), [data]);
  return (
    <div style={rs.card}>
      {rsCardHeader(rs, 'Statutes — recent amendments', `${ranked.length} tracked · sorted newest first`)}
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead><tr>
          <th style={rs.th}>Amended</th>
          <th style={rs.th}>Citation</th>
          <th style={rs.th}>Title</th>
          <th style={rs.th}>Jurisdiction</th>
          <th style={rs.th}>Used in</th>
          <th style={{ ...rs.th, textAlign: 'right' }}>Changes</th>
        </tr></thead>
        <tbody>{ranked.map(s => (
          <tr key={s.id}>
            <td style={{ ...rs.td, fontFamily: Trsh.font.mono, fontWeight: 700, color: rs.indigo }}>{s.lastAmended}</td>
            <td style={{ ...rs.td, fontFamily: Trsh.font.mono, fontSize: '11px' }}>{s.short}<div style={{ fontSize: '10px', color: Trsh.color.text.tertiary, marginTop: '2px' }}>{s.cite}</div></td>
            <td style={{ ...rs.td, maxWidth: '320px' }}>{s.title}</td>
            <td style={rs.td}><span style={{ ...rs.tag, background: Trsh.color.bg.secondary, color: Trsh.color.text.secondary }}>{s.jurisdiction}</span></td>
            <td style={{ ...rs.td, fontSize: '10px' }}>{s.usedIn.slice(0, 2).join(', ') || <span style={{ color: Trsh.color.text.tertiary, fontStyle: 'italic' }}>—</span>}</td>
            <td style={{ ...rs.td, textAlign: 'right', fontFamily: Trsh.font.mono, color: s.changes > 0 ? rs.amber : Trsh.color.text.tertiary, fontWeight: 700 }}>{s.changes > 0 ? `Δ ${s.changes}` : '—'}</td>
          </tr>
        ))}</tbody>
      </table>
    </div>
  );
}
window.RsStatAmendments = RsStatAmendments;

// ═══════════════════════════════════════════════════════════════════════════
// REGULATIONS — new sub-views
// ═══════════════════════════════════════════════════════════════════════════

function RsRegByAgency({ data }) {
  const rs = window.__rs;
  const groups = useRsHMemo(() => {
    const g = {};
    data.regulations.forEach(r => { if (!g[r.agency]) g[r.agency] = []; g[r.agency].push(r); });
    return Object.entries(g).sort((a,b) => b[1].length - a[1].length);
  }, [data]);
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '12px' }}>
      {groups.map(([agency, list]) => (
        <div key={agency} style={rs.card}>
          <div style={rs.cardH}>
            <div>
              <div style={{ fontSize: '13px', fontWeight: 700, fontFamily: Trsh.font.mono, color: rs.indigo }}>{agency}</div>
              <div style={{ fontSize: '10px', color: Trsh.color.text.tertiary, marginTop: '2px' }}>{list.length} rule{list.length === 1 ? '' : 's'} tracked</div>
            </div>
            <span style={{ ...rs.tag, background: rs.indigoBg, color: rs.indigo }}>{list.length}</span>
          </div>
          <div>{list.map(r => (
            <div key={r.id} style={{ padding: '10px 16px', borderBottom: `1px solid ${Trsh.color.border.light}` }}>
              <div style={{ fontSize: '12px', fontWeight: 700 }}>{r.short}</div>
              <div style={{ fontSize: '10px', color: Trsh.color.text.tertiary, fontFamily: Trsh.font.mono, marginTop: '2px' }}>{r.cite}</div>
              <div style={{ fontSize: '11px', color: Trsh.color.text.secondary, marginTop: '4px' }}>{r.title}</div>
              <div style={{ fontSize: '10px', color: Trsh.color.text.tertiary, marginTop: '4px' }}>Last amended {r.lastAmended} · {r.usedIn.length === 0 ? 'not in active matter' : `${r.usedIn.length} matter${r.usedIn.length === 1 ? '' : 's'}`}</div>
            </div>
          ))}</div>
        </div>
      ))}
    </div>
  );
}
window.RsRegByAgency = RsRegByAgency;

function RsRegChangeLog({ data }) {
  const rs = window.__rs;
  const ranked = useRsHMemo(() => [...data.regulations].sort((a,b) => (b.lastAmended || '').localeCompare(a.lastAmended || '')), [data]);
  return (
    <div style={rs.card}>
      {rsCardHeader(rs, 'Regulations — change log', `${ranked.length} rules · sorted by last amendment`)}
      <div>{ranked.map(r => (
        <div key={r.id} style={{ display: 'grid', gridTemplateColumns: '80px 140px 1fr 100px', gap: '16px', alignItems: 'start', padding: '12px 16px', borderBottom: `1px solid ${Trsh.color.border.light}` }}>
          <span style={{ fontSize: '12px', fontFamily: Trsh.font.mono, color: rs.indigo, fontWeight: 700 }}>{r.lastAmended}</span>
          <div>
            <div style={{ fontSize: '12px', fontWeight: 700, fontFamily: Trsh.font.mono, color: rs.indigo }}>{r.agency}</div>
            <div style={{ fontSize: '10px', color: Trsh.color.text.tertiary, fontFamily: Trsh.font.mono, marginTop: '2px' }}>{r.cite}</div>
          </div>
          <div>
            <div style={{ fontSize: '12px', fontWeight: 600 }}>{r.title}</div>
            <div style={{ fontSize: '11px', color: Trsh.color.text.secondary, marginTop: '4px' }}>{r.synopsis}</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: '9px', color: Trsh.color.text.tertiary, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Effective</div>
            <div style={{ fontSize: '10px', fontFamily: Trsh.font.mono, color: Trsh.color.text.secondary, marginTop: '2px' }}>{r.effective}</div>
          </div>
        </div>
      ))}</div>
    </div>
  );
}
window.RsRegChangeLog = RsRegChangeLog;

// ═══════════════════════════════════════════════════════════════════════════
// SECONDARY — new sub-views
// ═══════════════════════════════════════════════════════════════════════════

function RsSecByType({ data }) {
  const rs = window.__rs;
  const groups = useRsHMemo(() => {
    const g = {};
    data.secondary.forEach(s => { if (!g[s.type]) g[s.type] = []; g[s.type].push(s); });
    return Object.entries(g).sort((a,b) => b[1].length - a[1].length);
  }, [data]);
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '12px' }}>
      {groups.map(([type, list]) => (
        <div key={type} style={rs.card}>
          <div style={rs.cardH}>
            <span style={{ fontSize: '13px', fontWeight: 700 }}>{type}</span>
            <span style={{ ...rs.tag, background: rs.violetBg, color: rs.violet }}>{list.length} source{list.length === 1 ? '' : 's'}</span>
          </div>
          <div>{list.map(s => (
            <div key={s.id} style={{ padding: '10px 16px', borderBottom: `1px solid ${Trsh.color.border.light}` }}>
              <div style={{ fontSize: '12px', fontWeight: 700 }}>{s.title}</div>
              <div style={{ fontSize: '10px', color: Trsh.color.text.tertiary, marginTop: '2px' }}>{s.author} · {s.volume}</div>
              <div style={{ fontSize: '10px', color: Trsh.color.text.secondary, marginTop: '4px' }}>{s.topic} · <span style={{ color: rs.indigo, fontWeight: 600 }}>{s.provider}</span></div>
            </div>
          ))}</div>
        </div>
      ))}
    </div>
  );
}
window.RsSecByType = RsSecByType;

function RsSecProviders({ data }) {
  const rs = window.__rs;
  const providers = useRsHMemo(() => {
    const g = {};
    data.secondary.forEach(s => { if (!g[s.provider]) g[s.provider] = { name: s.provider, count: 0, types: new Set() }; g[s.provider].count++; g[s.provider].types.add(s.type); });
    return Object.values(g).sort((a,b) => b.count - a.count);
  }, [data]);
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px' }}>
      {providers.map(p => (
        <div key={p.name} style={rs.card}>
          <div style={{ padding: '16px', textAlign: 'center' }}>
            <div style={{ fontSize: '10px', color: Trsh.color.text.tertiary, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Provider</div>
            <div style={{ fontSize: '15px', fontWeight: 700, marginTop: '4px', color: rs.indigo }}>{p.name}</div>
            <div style={{ fontSize: '28px', fontFamily: Trsh.font.mono, fontWeight: 700, marginTop: '10px', color: Trsh.color.text.primary }}>{p.count}</div>
            <div style={{ fontSize: '10px', color: Trsh.color.text.tertiary, marginTop: '2px' }}>sources subscribed</div>
            <div style={{ display: 'flex', gap: '4px', justifyContent: 'center', flexWrap: 'wrap', marginTop: '10px' }}>
              {[...p.types].map(t => <span key={t} style={{ ...rs.tag, background: rs.violetBg, color: rs.violet }}>{t}</span>)}
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}
window.RsSecProviders = RsSecProviders;

// ═══════════════════════════════════════════════════════════════════════════
// CITATOR — new sub-views
// ═══════════════════════════════════════════════════════════════════════════

function RsCitTreatments({ data }) {
  const rs = window.__rs;
  const t = data.citator.treatments;
  const weightColor = (w) => w === 'binding' ? rs.indigo : Trsh.color.text.secondary;
  const treatmentColor = (tr) => {
    if (/abrogat|overrul/i.test(tr)) return rs.crimson;
    if (/distinguished|limited/i.test(tr)) return rs.amber;
    if (/followed|clarified/i.test(tr)) return rs.teal;
    return Trsh.color.text.secondary;
  };
  return (
    <div style={rs.card}>
      {rsCardHeader(rs, `Treatments — ${data.citator.focal.cite}`, `${t.length} downstream citing decisions`)}
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead><tr>
          <th style={rs.th}>Citing case</th>
          <th style={rs.th}>Court</th>
          <th style={rs.th}>Year</th>
          <th style={rs.th}>Treatment</th>
          <th style={rs.th}>Weight</th>
          <th style={rs.th}>Note</th>
        </tr></thead>
        <tbody>{t.map(row => (
          <tr key={row.id}>
            <td style={{ ...rs.td, maxWidth: '360px', fontWeight: 500 }}>
              {row.citingCase}
              {row.flagged && <span style={{ ...rs.tag, background: rs.crimsonBg, color: rs.crimson, marginLeft: '6px', fontSize: '9px' }}>! Flagged</span>}
            </td>
            <td style={{ ...rs.td, fontSize: '11px' }}>{row.court}</td>
            <td style={{ ...rs.td, fontFamily: Trsh.font.mono }}>{row.year}</td>
            <td style={rs.td}><span style={{ ...rs.tag, background: treatmentColor(row.treatment) + '22', color: treatmentColor(row.treatment), textTransform: 'capitalize' }}>{row.treatment}</span></td>
            <td style={rs.td}><span style={{ fontSize: '11px', fontWeight: 700, color: weightColor(row.weight), textTransform: 'capitalize' }}>{row.weight}</span></td>
            <td style={{ ...rs.td, fontSize: '11px', color: Trsh.color.text.secondary, fontStyle: 'italic', maxWidth: '300px' }}>{row.note}</td>
          </tr>
        ))}</tbody>
      </table>
    </div>
  );
}
window.RsCitTreatments = RsCitTreatments;

function RsCitHistory({ data }) {
  const rs = window.__rs;
  const h = data.citator.history;
  const sevColor = (s) => s === 'negative' ? rs.crimson : s === 'positive' ? rs.teal : Trsh.color.text.secondary;
  const sevBg    = (s) => s === 'negative' ? rs.crimsonBg : s === 'positive' ? rs.tealBg : Trsh.color.bg.secondary;
  return (
    <div style={rs.card}>
      {rsCardHeader(rs, `Citator history — ${data.citator.focal.cite}`, `${h.length} treatment events`)}
      <div style={{ padding: '16px' }}>
        <div style={{ position: 'relative', paddingLeft: '24px', borderLeft: `2px solid ${Trsh.color.border.light}` }}>
          {h.map((e, i) => (
            <div key={i} style={{ position: 'relative', paddingBottom: i === h.length - 1 ? 0 : '20px' }}>
              <div style={{ position: 'absolute', left: '-30px', top: '2px', width: '12px', height: '12px', borderRadius: '50%', background: sevColor(e.severity), border: `2px solid ${Trsh.color.bg.card}`, boxShadow: `0 0 0 2px ${sevColor(e.severity)}40` }} />
              <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '4px' }}>
                <span style={{ fontSize: '12px', fontFamily: Trsh.font.mono, fontWeight: 700, color: sevColor(e.severity) }}>{e.date}</span>
                <span style={{ ...rs.tag, background: sevBg(e.severity), color: sevColor(e.severity), textTransform: 'capitalize' }}>{e.severity}</span>
              </div>
              <div style={{ fontSize: '12px', color: Trsh.color.text.primary }}>{e.event}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
window.RsCitHistory = RsCitHistory;

function RsCitBatch({ data }) {
  const rs = window.__rs;
  const today = new Date('2026-04-21');
  const batch = useRsHMemo(() => data.cases.map(c => {
    const days = Math.round((today - new Date(c.lastChecked)) / 86400000);
    let priority = 'low';
    if (c.signal !== 'positive') priority = 'high';
    else if (days > 30) priority = 'medium';
    return { ...c, daysSince: days, priority };
  }).sort((a,b) => {
    const rank = { high: 0, medium: 1, low: 2 };
    return rank[a.priority] - rank[b.priority] || b.daysSince - a.daysSince;
  }), [data]);
  const counts = batch.reduce((a,c) => { a[c.priority] = (a[c.priority] || 0) + 1; return a; }, {});
  const prStyle = { high: { bg: rs.crimsonBg, c: rs.crimson, label: 'High' }, medium: { bg: rs.amberBg, c: rs.amber, label: 'Medium' }, low: { bg: rs.tealBg, c: rs.teal, label: 'Low' } };

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={rs.stat}><span style={rs.statLabel}>Queue total</span><span style={rs.statValue}>{batch.length}</span></div>
        {['high','medium','low'].map(k => (
          <div key={k} style={rs.stat}>
            <span style={rs.statLabel}>{prStyle[k].label} priority</span>
            <span style={{ ...rs.statValue, color: prStyle[k].c }}>{counts[k] || 0}</span>
          </div>
        ))}
      </div>

      <div style={rs.card}>
        <div style={rs.cardH}>
          <span>Batch Shepardize queue</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <button style={rs.btnSecondary}>Schedule batch</button>
            <button style={rs.btnPrimary}>Run all high-priority</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr>
            <th style={rs.th}>Priority</th>
            <th style={rs.th}>Case</th>
            <th style={rs.th}>Signal</th>
            <th style={rs.th}>Used in</th>
            <th style={{ ...rs.th, textAlign: 'right' }}>Last checked</th>
            <th style={{ ...rs.th, textAlign: 'right' }}>Action</th>
          </tr></thead>
          <tbody>{batch.map(c => {
            const ps = prStyle[c.priority];
            return (
              <tr key={c.id}>
                <td style={rs.td}><span style={{ ...rs.tag, background: ps.bg, color: ps.c }}>{ps.label}</span></td>
                <td style={{ ...rs.td, fontWeight: 700, maxWidth: '320px' }}>{c.shortCite}<div style={{ fontSize: '10px', color: Trsh.color.text.tertiary, fontFamily: Trsh.font.mono, marginTop: '2px' }}>{c.cite}</div></td>
                <td style={rs.td}><span style={{ ...rs.tag, background: c.signal === 'positive' ? rs.tealBg : c.signal === 'caution' ? rs.amberBg : rs.crimsonBg, color: c.signal === 'positive' ? rs.teal : c.signal === 'caution' ? rs.amber : rs.crimson, textTransform: 'capitalize' }}>{c.signal}</span></td>
                <td style={{ ...rs.td, fontSize: '10px' }}>{c.usedIn.length === 0 ? <span style={{ color: Trsh.color.text.tertiary, fontStyle: 'italic' }}>—</span> : c.usedIn.slice(0, 2).join(', ')}</td>
                <td style={{ ...rs.td, textAlign: 'right', fontFamily: Trsh.font.mono, fontSize: '10px', color: c.daysSince > 30 ? rs.amber : Trsh.color.text.tertiary }}>{c.daysSince}d ago</td>
                <td style={{ ...rs.td, textAlign: 'right' }}><button style={rs.btnGhost}>Run →</button></td>
              </tr>
            );
          })}</tbody>
        </table>
      </div>
    </div>
  );
}
window.RsCitBatch = RsCitBatch;

// ═══════════════════════════════════════════════════════════════════════════
// BRIEFS — new sub-views
// ═══════════════════════════════════════════════════════════════════════════

function RsBriefsTemplates({ data }) {
  const rs = window.__rs;
  const tpls = data.briefTemplates || [
    { id: 'BT-001', name: 'MSJ Opposition — Delaware BJR',         type: 'MSJ',    category: 'Corporate',    sections: 7, words: 12500, cites: 45, updated: '2026-04-10', usedBy: 14 },
    { id: 'BT-002', name: 'Daubert — Expert Methodology',          type: 'Daubert',category: 'Expert',       sections: 5, words: 4500,  cites: 22, updated: '2026-03-22', usedBy: 18 },
    { id: 'BT-003', name: 'Class Cert — Comcast Predominance',     type: 'Class',  category: 'Antitrust',    sections: 6, words: 8500,  cites: 38, updated: '2026-04-02', usedBy: 8  },
    { id: 'BT-004', name: 'Markman — §112(f) Claim Construction',  type: 'Markman',category: 'Patent',       sections: 6, words: 10000, cites: 42, updated: '2026-04-15', usedBy: 9  },
    { id: 'BT-005', name: 'MTD — PSLRA Scienter',                  type: 'MTD',    category: 'Securities',   sections: 5, words: 6000,  cites: 28, updated: '2026-03-20', usedBy: 11 },
    { id: 'BT-006', name: 'Appellate Brief — D.C. Cir. Standard',  type: 'Appeal', category: 'Appellate',    sections: 8, words: 14000, cites: 52, updated: '2026-04-04', usedBy: 4  },
    { id: 'BT-007', name: 'Protective Order — Confidential Investigation', type: 'Protective', category: 'Discovery', sections: 4, words: 4000, cites: 16, updated: '2026-04-14', usedBy: 12 },
    { id: 'BT-008', name: 'Sentencing Memo — §3553(a) Variance',   type: 'Sentencing', category: 'Criminal', sections: 6, words: 8000,  cites: 21, updated: '2026-04-15', usedBy: 22 },
  ];
  return (
    <div style={rs.card}>
      {rsCardHeader(rs, 'Brief templates', `${tpls.length} starter drafts`)}
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead><tr>
          <th style={rs.th}>ID</th>
          <th style={rs.th}>Template</th>
          <th style={rs.th}>Type</th>
          <th style={rs.th}>Category</th>
          <th style={{ ...rs.th, textAlign: 'right' }}>Sections</th>
          <th style={{ ...rs.th, textAlign: 'right' }}>Target words</th>
          <th style={{ ...rs.th, textAlign: 'right' }}>Cites</th>
          <th style={{ ...rs.th, textAlign: 'right' }}>Used by</th>
          <th style={rs.th}>Updated</th>
          <th style={{ ...rs.th, textAlign: 'right' }}>Action</th>
        </tr></thead>
        <tbody>{tpls.map(t => (
          <tr key={t.id}>
            <td style={{ ...rs.td, fontFamily: Trsh.font.mono, color: rs.indigo, fontWeight: 700 }}>{t.id}</td>
            <td style={{ ...rs.td, fontWeight: 600 }}>{t.name}</td>
            <td style={rs.td}><span style={{ ...rs.tag, background: rs.indigoBg, color: rs.indigo }}>{t.type}</span></td>
            <td style={{ ...rs.td, fontSize: '11px', color: Trsh.color.text.secondary }}>{t.category}</td>
            <td style={{ ...rs.td, textAlign: 'right', fontFamily: Trsh.font.mono }}>{t.sections}</td>
            <td style={{ ...rs.td, textAlign: 'right', fontFamily: Trsh.font.mono }}>{t.words.toLocaleString()}</td>
            <td style={{ ...rs.td, textAlign: 'right', fontFamily: Trsh.font.mono, color: rs.indigo, fontWeight: 700 }}>{t.cites}</td>
            <td style={{ ...rs.td, textAlign: 'right', fontFamily: Trsh.font.mono, color: rs.teal, fontWeight: 700 }}>{t.usedBy}×</td>
            <td style={{ ...rs.td, fontFamily: Trsh.font.mono, fontSize: '10px', color: Trsh.color.text.tertiary }}>{t.updated}</td>
            <td style={{ ...rs.td, textAlign: 'right' }}><button style={rs.btnGhost}>Use →</button></td>
          </tr>
        ))}</tbody>
      </table>
    </div>
  );
}
window.RsBriefsTemplates = RsBriefsTemplates;

function RsBriefsArchive({ data }) {
  const rs = window.__rs;
  const archived = data.briefs.filter(b => b.status === 'Filed');
  const synth = archived.length ? archived : [
    { id: 'B-ARC-01', title: 'Previously filed — see Motions platform', matter: '—', author: '—', status: 'Filed', wordCount: 0, targetWords: 0, due: '—', cites: { total: 0, green: 0, caution: 0, red: 0 }, lastEdited: '—' },
  ];
  return (
    <div style={rs.card}>
      {rsCardHeader(rs, 'Filed briefs — archive', `${archived.length} filed · read-only`)}
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead><tr>
          <th style={rs.th}>ID</th>
          <th style={rs.th}>Title</th>
          <th style={rs.th}>Matter</th>
          <th style={rs.th}>Author</th>
          <th style={{ ...rs.th, textAlign: 'right' }}>Words</th>
          <th style={{ ...rs.th, textAlign: 'right' }}>Cites</th>
          <th style={rs.th}>Filed</th>
        </tr></thead>
        <tbody>{synth.map(b => (
          <tr key={b.id}>
            <td style={{ ...rs.td, fontFamily: Trsh.font.mono, color: rs.indigo, fontWeight: 700 }}>{b.id}</td>
            <td style={{ ...rs.td, fontWeight: 600 }}>{b.title}</td>
            <td style={{ ...rs.td, fontSize: '11px', color: Trsh.color.text.secondary }}>{b.matter}</td>
            <td style={{ ...rs.td, fontSize: '11px' }}>{b.author}</td>
            <td style={{ ...rs.td, textAlign: 'right', fontFamily: Trsh.font.mono }}>{(b.wordCount || 0).toLocaleString()}</td>
            <td style={{ ...rs.td, textAlign: 'right', fontFamily: Trsh.font.mono, color: rs.indigo, fontWeight: 700 }}>{b.cites?.total || 0}</td>
            <td style={{ ...rs.td, fontFamily: Trsh.font.mono, fontSize: '10px' }}>{b.due}</td>
          </tr>
        ))}</tbody>
      </table>
    </div>
  );
}
window.RsBriefsArchive = RsBriefsArchive;

function RsBriefsCiteHealth({ data }) {
  const rs = window.__rs;
  const totals = data.briefs.reduce((a,b) => { a.total += b.cites.total; a.green += b.cites.green; a.caution += b.cites.caution; a.red += b.cites.red; return a; }, { total: 0, green: 0, caution: 0, red: 0 });
  const healthPct = totals.total ? Math.round((totals.green / totals.total) * 100) : 0;
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={rs.stat}><span style={rs.statLabel}>Total cites</span><span style={rs.statValue}>{totals.total}</span></div>
        <div style={rs.stat}><span style={rs.statLabel}>Clean (green)</span><span style={{ ...rs.statValue, color: rs.teal }}>{totals.green}</span></div>
        <div style={rs.stat}><span style={rs.statLabel}>Caution</span><span style={{ ...rs.statValue, color: rs.amber }}>{totals.caution}</span></div>
        <div style={rs.stat}><span style={rs.statLabel}>Negative</span><span style={{ ...rs.statValue, color: rs.crimson }}>{totals.red}</span></div>
      </div>

      <div style={rs.card}>
        {rsCardHeader(rs, 'Cite health — by brief', `overall ${healthPct}% clean`)}
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr>
            <th style={rs.th}>Brief</th>
            <th style={rs.th}>Matter</th>
            <th style={rs.th}>Author</th>
            <th style={rs.th}>Status</th>
            <th style={{ ...rs.th, textAlign: 'right' }}>Total</th>
            <th style={{ ...rs.th, textAlign: 'right' }}>Green</th>
            <th style={{ ...rs.th, textAlign: 'right' }}>Caution</th>
            <th style={{ ...rs.th, textAlign: 'right' }}>Red</th>
            <th style={rs.th}>Health</th>
          </tr></thead>
          <tbody>{data.briefs.map(b => {
            const pct = b.cites.total ? Math.round((b.cites.green / b.cites.total) * 100) : 0;
            return (
              <tr key={b.id}>
                <td style={{ ...rs.td, fontWeight: 600, maxWidth: '280px' }}>{b.title}<div style={{ fontSize: '10px', color: Trsh.color.text.tertiary, fontFamily: Trsh.font.mono, marginTop: '2px' }}>{b.id}</div></td>
                <td style={{ ...rs.td, fontSize: '11px', color: Trsh.color.text.secondary }}>{b.matter}</td>
                <td style={{ ...rs.td, fontSize: '11px' }}>{b.author}</td>
                <td style={rs.td}><span style={{ ...rs.tag, background: rs.indigoBg, color: rs.indigo }}>{b.status}</span></td>
                <td style={{ ...rs.td, textAlign: 'right', fontFamily: Trsh.font.mono, fontWeight: 700 }}>{b.cites.total}</td>
                <td style={{ ...rs.td, textAlign: 'right', fontFamily: Trsh.font.mono, color: rs.teal, fontWeight: 700 }}>{b.cites.green}</td>
                <td style={{ ...rs.td, textAlign: 'right', fontFamily: Trsh.font.mono, color: b.cites.caution > 0 ? rs.amber : Trsh.color.text.tertiary, fontWeight: 700 }}>{b.cites.caution}</td>
                <td style={{ ...rs.td, textAlign: 'right', fontFamily: Trsh.font.mono, color: b.cites.red > 0 ? rs.crimson : Trsh.color.text.tertiary, fontWeight: 700 }}>{b.cites.red}</td>
                <td style={{ ...rs.td, minWidth: '140px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <div style={{ flex: 1, height: '6px', borderRadius: '3px', overflow: 'hidden', background: Trsh.color.bg.secondary }}>
                      <div style={{ width: `${pct}%`, height: '100%', background: pct >= 90 ? rs.teal : pct >= 70 ? rs.amber : rs.crimson }} />
                    </div>
                    <span style={{ fontSize: '11px', fontFamily: Trsh.font.mono, fontWeight: 700, color: pct >= 90 ? rs.teal : pct >= 70 ? rs.amber : rs.crimson, minWidth: '32px', textAlign: 'right' }}>{pct}%</span>
                  </div>
                </td>
              </tr>
            );
          })}</tbody>
        </table>
      </div>
    </div>
  );
}
window.RsBriefsCiteHealth = RsBriefsCiteHealth;

// ═══════════════════════════════════════════════════════════════════════════
// WORKSPACE — new sub-views
// ═══════════════════════════════════════════════════════════════════════════

function RsWsPinned({ data }) {
  const rs = window.__rs;
  const pinned = data.cases.filter(c => c.usedIn.length > 0).slice(0, 12);
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '12px' }}>
      {pinned.map(c => (
        <div key={c.id} style={rs.card}>
          <div style={{ padding: '12px 16px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '6px' }}>
              <span style={{ fontSize: '14px', color: rs.indigo }}><Icons.Star size={11}/></span>
              <span style={{ fontSize: '13px', fontWeight: 700 }}>{c.shortCite}</span>
              <span style={{ ...rs.tag, background: c.signal === 'positive' ? rs.tealBg : rs.amberBg, color: c.signal === 'positive' ? rs.teal : rs.amber, textTransform: 'capitalize' }}>{c.signal}</span>
            </div>
            <div style={{ fontSize: '11px', color: Trsh.color.text.secondary, fontFamily: Trsh.font.mono, marginBottom: '6px' }}>{c.court} · {c.year}</div>
            <div style={{ fontSize: '11px', color: Trsh.color.text.primary, marginBottom: '8px' }}>{c.headnote}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '6px', flexWrap: 'wrap' }}>
              <span style={{ fontSize: '9px', color: Trsh.color.text.tertiary, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Pinned in</span>
              {c.usedIn.map(m => <span key={m} style={{ ...rs.tag, background: rs.indigoBg, color: rs.indigo }}>{m}</span>)}
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}
window.RsWsPinned = RsWsPinned;

function RsWsRecent({ data }) {
  const rs = window.__rs;
  const ranked = useRsHMemo(() => {
    const parse = (t) => {
      if (/^(\d+)h ago/.test(t))   return +RegExp.$1;
      if (/^(\d+)d ago/.test(t))   return +RegExp.$1 * 24;
      return 1000;
    };
    return [...data.workspaces].sort((a,b) => parse(a.lastUpdated) - parse(b.lastUpdated));
  }, [data]);
  return (
    <div style={rs.card}>
      {rsCardHeader(rs, 'Workspaces — recent activity', `${ranked.length} workspaces · sorted newest first`)}
      <div>{ranked.map(w => (
        <div key={w.id} style={{ display: 'grid', gridTemplateColumns: '80px 1fr 180px 100px 80px', gap: '16px', alignItems: 'center', padding: '12px 16px', borderBottom: `1px solid ${Trsh.color.border.light}` }}>
          <span style={{ fontSize: '11px', fontFamily: Trsh.font.mono, color: rs.indigo, fontWeight: 700 }}>{w.lastUpdated}</span>
          <div>
            <div style={{ fontSize: '12px', fontWeight: 700 }}>{w.matter}</div>
            <div style={{ fontSize: '10px', color: Trsh.color.text.tertiary, fontFamily: Trsh.font.mono, marginTop: '2px' }}>{w.id} · {w.matterId}</div>
            <div style={{ display: 'flex', gap: '4px', marginTop: '6px', flexWrap: 'wrap' }}>{w.tags.slice(0, 4).map(t => <span key={t} style={{ ...rs.tag, background: rs.indigoBg, color: rs.indigo, fontSize: '9px' }}>{t}</span>)}</div>
          </div>
          <span style={{ fontSize: '11px', color: Trsh.color.text.secondary }}>{w.owner}</span>
          <div style={{ textAlign: 'right' }}><div style={{ fontSize: '14px', fontFamily: Trsh.font.mono, fontWeight: 700, color: rs.indigo }}>{w.items}</div><div style={{ fontSize: '9px', color: Trsh.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>items</div></div>
          <div style={{ textAlign: 'right' }}><div style={{ fontSize: '14px', fontFamily: Trsh.font.mono, fontWeight: 700, color: rs.teal }}>{w.bundles}</div><div style={{ fontSize: '9px', color: Trsh.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>bundles</div></div>
        </div>
      ))}</div>
    </div>
  );
}
window.RsWsRecent = RsWsRecent;

function RsWsBundles({ data }) {
  const rs = window.__rs;
  const bundles = useRsHMemo(() => {
    const out = [];
    data.workspaces.forEach(w => {
      for (let i = 1; i <= w.bundles; i++) {
        const tag = w.tags[(i - 1) % w.tags.length];
        out.push({
          id: `${w.id}/BND-${String(i).padStart(2, '0')}`,
          workspace: w.matter, wsId: w.id,
          name: tag.charAt(0).toUpperCase() + tag.slice(1).replace('-', ' ') + ' bundle',
          tag, itemCount: Math.max(4, Math.round(w.items / w.bundles)),
        });
      }
    });
    return out;
  }, [data]);
  return (
    <div style={rs.card}>
      {rsCardHeader(rs, 'All bundles — firmwide', `${bundles.length} bundles across ${data.workspaces.length} workspaces`)}
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead><tr>
          <th style={rs.th}>Bundle ID</th>
          <th style={rs.th}>Name</th>
          <th style={rs.th}>Workspace</th>
          <th style={rs.th}>Topic tag</th>
          <th style={{ ...rs.th, textAlign: 'right' }}>Items</th>
          <th style={{ ...rs.th, textAlign: 'right' }}>Action</th>
        </tr></thead>
        <tbody>{bundles.map(b => (
          <tr key={b.id}>
            <td style={{ ...rs.td, fontFamily: Trsh.font.mono, color: rs.indigo, fontWeight: 700, fontSize: '10px' }}>{b.id}</td>
            <td style={{ ...rs.td, fontWeight: 600 }}>{b.name}</td>
            <td style={{ ...rs.td, fontSize: '11px', color: Trsh.color.text.secondary }}>{b.workspace}</td>
            <td style={rs.td}><span style={{ ...rs.tag, background: rs.indigoBg, color: rs.indigo }}>{b.tag}</span></td>
            <td style={{ ...rs.td, textAlign: 'right', fontFamily: Trsh.font.mono, fontWeight: 700, color: rs.indigo }}>{b.itemCount}</td>
            <td style={{ ...rs.td, textAlign: 'right' }}><button style={rs.btnGhost}>Open →</button></td>
          </tr>
        ))}</tbody>
      </table>
    </div>
  );
}
window.RsWsBundles = RsWsBundles;

// ═══════════════════════════════════════════════════════════════════════════
// ANALYTICS — new sub-views
// ═══════════════════════════════════════════════════════════════════════════

function RsAnTopics({ data }) {
  const rs = window.__rs;
  const topics = data.analytics.topTopics;
  const max = Math.max(...topics.map(t => t.queries));
  return (
    <div style={rs.card}>
      {rsCardHeader(rs, 'Top research topics — firmwide', `${topics.length} tracked · query volume`)}
      <div style={{ padding: '8px 0' }}>{topics.map((t, i) => (
        <div key={t.topic} style={{ display: 'grid', gridTemplateColumns: '40px 240px 1fr 80px 80px', gap: '16px', alignItems: 'center', padding: '10px 16px', borderBottom: `1px solid ${Trsh.color.border.light}` }}>
          <span style={{ fontSize: '13px', fontFamily: Trsh.font.mono, fontWeight: 700, color: i < 3 ? rs.indigo : Trsh.color.text.tertiary }}>#{i + 1}</span>
          <span style={{ fontSize: '12px', fontWeight: 700 }}>{t.topic}</span>
          <div style={{ height: '8px', background: Trsh.color.bg.secondary, borderRadius: '4px', overflow: 'hidden' }}>
            <div style={{ width: `${(t.queries / max) * 100}%`, height: '100%', background: rs.indigo, borderRadius: '4px' }} />
          </div>
          <span style={{ fontSize: '14px', fontFamily: Trsh.font.mono, fontWeight: 700, color: rs.indigo, textAlign: 'right' }}>{t.queries}</span>
          <span style={{ fontSize: '11px', fontFamily: Trsh.font.mono, fontWeight: 700, color: t.change > 0 ? rs.teal : t.change < 0 ? rs.crimson : Trsh.color.text.tertiary, textAlign: 'right' }}>{t.change > 0 ? `+${t.change}%` : `${t.change}%`}</span>
        </div>
      ))}</div>
    </div>
  );
}
window.RsAnTopics = RsAnTopics;

function RsAnPractice({ data }) {
  const rs = window.__rs;
  const pr = data.analytics.byPractice;
  const total = pr.reduce((a,p) => a + p.pct, 0);
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
      <div style={rs.card}>
        {rsCardHeader(rs, 'Share by practice area', `${pr.length} groups`)}
        <div style={{ padding: '16px' }}>{pr.map(p => (
          <div key={p.practice} style={{ marginBottom: '14px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
              <span style={{ fontSize: '12px', fontWeight: 600 }}>{p.practice}</span>
              <span style={{ fontSize: '12px', fontFamily: Trsh.font.mono, fontWeight: 700, color: rs.indigo }}>{p.pct}%</span>
            </div>
            <div style={{ height: '10px', background: Trsh.color.bg.secondary, borderRadius: '5px', overflow: 'hidden' }}>
              <div style={{ width: `${(p.pct / Math.max(...pr.map(x => x.pct))) * 100}%`, height: '100%', background: rs.indigo, borderRadius: '5px' }} />
            </div>
          </div>
        ))}</div>
      </div>
      <div style={rs.card}>
        {rsCardHeader(rs, 'Practice distribution', `${total}% of total queries`)}
        <div style={{ padding: '16px' }}>
          <div style={{ display: 'flex', height: '24px', borderRadius: '6px', overflow: 'hidden', marginBottom: '16px' }}>
            {pr.map((p, i) => {
              const colors = [rs.indigo, rs.teal, rs.violet, rs.amber, rs.crimson];
              return <div key={p.practice} style={{ width: `${(p.pct / total) * 100}%`, background: colors[i % colors.length] }} title={`${p.practice} — ${p.pct}%`} />;
            })}
          </div>
          {pr.map((p, i) => {
            const colors = [rs.indigo, rs.teal, rs.violet, rs.amber, rs.crimson];
            return (
              <div key={p.practice} style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '6px 0', borderBottom: `1px solid ${Trsh.color.border.light}` }}>
                <span style={{ width: '12px', height: '12px', background: colors[i % colors.length], borderRadius: '2px', display: 'inline-block' }} />
                <span style={{ fontSize: '12px', flex: 1 }}>{p.practice}</span>
                <span style={{ fontSize: '12px', fontFamily: Trsh.font.mono, fontWeight: 700, color: colors[i % colors.length] }}>{p.pct}%</span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}
window.RsAnPractice = RsAnPractice;

function RsAnAttorneys({ data }) {
  const rs = window.__rs;
  const att = data.analytics.byAttorney;
  const maxH = Math.max(...att.map(a => a.hours));
  return (
    <div style={rs.card}>
      {rsCardHeader(rs, 'Research by attorney — leaderboard', `${att.length} active researchers`)}
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead><tr>
          <th style={{ ...rs.th, width: '40px' }}>#</th>
          <th style={rs.th}>Attorney</th>
          <th style={{ ...rs.th, textAlign: 'right' }}>Hours</th>
          <th style={rs.th}>Share</th>
          <th style={{ ...rs.th, textAlign: 'right' }}>Queries</th>
          <th style={{ ...rs.th, textAlign: 'right' }}>Saved / hr</th>
          <th style={{ ...rs.th, textAlign: 'right' }}>Efficiency</th>
        </tr></thead>
        <tbody>{att.map((a, i) => {
          const eff = a.savedPerHr;
          return (
            <tr key={a.attorney}>
              <td style={{ ...rs.td, fontFamily: Trsh.font.mono, fontWeight: 700, color: i < 3 ? rs.indigo : Trsh.color.text.tertiary, textAlign: 'center' }}>#{i + 1}</td>
              <td style={{ ...rs.td, fontWeight: 700 }}>{a.attorney}</td>
              <td style={{ ...rs.td, textAlign: 'right', fontFamily: Trsh.font.mono, fontWeight: 700, color: rs.indigo }}>{a.hours}</td>
              <td style={{ ...rs.td, minWidth: '160px' }}>
                <div style={{ height: '6px', background: Trsh.color.bg.secondary, borderRadius: '3px', overflow: 'hidden' }}>
                  <div style={{ width: `${(a.hours / maxH) * 100}%`, height: '100%', background: rs.indigo, borderRadius: '3px' }} />
                </div>
              </td>
              <td style={{ ...rs.td, textAlign: 'right', fontFamily: Trsh.font.mono }}>{a.queries}</td>
              <td style={{ ...rs.td, textAlign: 'right', fontFamily: Trsh.font.mono, fontWeight: 700, color: rs.teal }}>{a.savedPerHr}</td>
              <td style={{ ...rs.td, textAlign: 'right' }}><span style={{ ...rs.tag, background: eff >= 4.4 ? rs.tealBg : rs.amberBg, color: eff >= 4.4 ? rs.teal : rs.amber }}>{eff >= 4.4 ? 'Above avg' : 'Avg'}</span></td>
            </tr>
          );
        })}</tbody>
      </table>
    </div>
  );
}
window.RsAnAttorneys = RsAnAttorneys;

// ═══════════════════════════════════════════════════════════════════════════
// ACTIVITY — new sub-views
// ═══════════════════════════════════════════════════════════════════════════

function RsActAlerts({ data }) {
  const rs = window.__rs;
  const alerts = data.activity.filter(a => a.severity === 'warn' || a.actor.includes('Citator') || a.actor === 'Compliance');
  return (
    <div>
      <div style={{ padding: '12px 16px', background: rs.amberBg, border: `1px solid ${rs.amber}30`, borderRadius: '8px', marginBottom: '16px', display: 'flex', alignItems: 'center', gap: '12px' }}>
        <span style={{ fontSize: '18px', color: rs.amber }}><Icons.Alert size={11}/></span>
        <div>
          <div style={{ fontSize: '13px', fontWeight: 700, color: rs.amber }}>{alerts.length} alert{alerts.length === 1 ? '' : 's'} in feed</div>
          <div style={{ fontSize: '11px', color: Trsh.color.text.secondary, marginTop: '2px' }}>Citator flags, compliance events, and warnings — investigate & resolve.</div>
        </div>
      </div>

      <div style={rs.card}>
        {rsCardHeader(rs, 'Alerts feed', `${alerts.length} events`)}
        <div>{alerts.map(a => (
          <div key={a.id} style={{ display: 'grid', gridTemplateColumns: '80px 140px 1fr 180px', gap: '16px', alignItems: 'center', padding: '12px 16px', borderBottom: `1px solid ${Trsh.color.border.light}`, borderLeft: `3px solid ${a.severity === 'warn' ? rs.amber : rs.indigo}` }}>
            <span style={{ fontSize: '11px', fontFamily: Trsh.font.mono, color: Trsh.color.text.tertiary, fontWeight: 700 }}>{a.time}</span>
            <span style={{ fontSize: '12px', fontWeight: 700, color: a.severity === 'warn' ? rs.amber : rs.indigo }}>{a.actor}</span>
            <div>
              <div style={{ fontSize: '12px', fontWeight: 600 }}>{a.action}</div>
              <div style={{ fontSize: '11px', color: Trsh.color.text.secondary, marginTop: '2px' }}>{a.target}</div>
            </div>
            <span style={{ fontSize: '11px', color: Trsh.color.text.secondary }}>{a.matter}</span>
          </div>
        ))}</div>
      </div>
    </div>
  );
}
window.RsActAlerts = RsActAlerts;

function RsActAudit({ data }) {
  const rs = window.__rs;
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={rs.stat}><span style={rs.statLabel}>Total events</span><span style={rs.statValue}>{data.activity.length}</span></div>
        <div style={rs.stat}><span style={rs.statLabel}>Exports</span><span style={{ ...rs.statValue, color: rs.indigo }}>{data.activity.filter(a => /Export/i.test(a.action)).length}</span></div>
        <div style={rs.stat}><span style={rs.statLabel}>Shares</span><span style={{ ...rs.statValue, color: rs.teal }}>{data.activity.filter(a => /Shared/i.test(a.action)).length}</span></div>
        <div style={rs.stat}><span style={rs.statLabel}>Warnings</span><span style={{ ...rs.statValue, color: rs.amber }}>{data.activity.filter(a => a.severity === 'warn').length}</span></div>
      </div>

      <div style={rs.card}>
        {rsCardHeader(rs, 'Audit log — all events', `${data.activity.length} records · exportable`)}
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr>
            <th style={rs.th}>ID</th>
            <th style={rs.th}>Time</th>
            <th style={rs.th}>Actor</th>
            <th style={rs.th}>Action</th>
            <th style={rs.th}>Target</th>
            <th style={rs.th}>Matter</th>
            <th style={rs.th}>Severity</th>
          </tr></thead>
          <tbody>{data.activity.map(a => (
            <tr key={a.id}>
              <td style={{ ...rs.td, fontFamily: Trsh.font.mono, color: rs.indigo, fontWeight: 700, fontSize: '10px' }}>{a.id}</td>
              <td style={{ ...rs.td, fontFamily: Trsh.font.mono, fontSize: '10px', color: Trsh.color.text.tertiary }}>{a.time}</td>
              <td style={{ ...rs.td, fontWeight: 600 }}>{a.actor}</td>
              <td style={{ ...rs.td, fontSize: '11px' }}>{a.action}</td>
              <td style={{ ...rs.td, fontSize: '11px', color: Trsh.color.text.secondary, maxWidth: '280px' }}>{a.target}</td>
              <td style={{ ...rs.td, fontSize: '11px' }}>{a.matter}</td>
              <td style={rs.td}><span style={{ ...rs.tag, background: a.severity === 'warn' ? rs.amberBg : Trsh.color.bg.secondary, color: a.severity === 'warn' ? rs.amber : Trsh.color.text.secondary, textTransform: 'capitalize' }}>{a.severity}</span></td>
            </tr>
          ))}</tbody>
        </table>
      </div>
    </div>
  );
}
window.RsActAudit = RsActAudit;

// ═══════════════════════════════════════════════════════════════════════════
// HUB WRAPPERS
// ═══════════════════════════════════════════════════════════════════════════

function RsSearchHub({ data }) {
  const [sub, setSub] = useRsH('query');
  const views = [
    { id: 'query',   label: 'Query' },
    { id: 'history', label: 'History', badge: data.history.length },
    { id: 'saved',   label: 'Saved',   badge: data.history.filter(h => h.saved).length },
    { id: 'alerts',  label: 'Alerts',  badge: data.history.filter(h => h.saved).length },
  ];
  return (
    <div>
      <RsSubNav views={views} active={sub} onChange={setSub} />
      {sub === 'query'   && <ResearchSearchTab data={data} />}
      {sub === 'history' && <RsSearchHistory data={data} />}
      {sub === 'saved'   && <RsSearchSaved data={data} />}
      {sub === 'alerts'  && <RsSearchAlerts data={data} />}
    </div>
  );
}
window.RsSearchHub = RsSearchHub;

function RsCasesHub({ data }) {
  const [sub, setSub] = useRsH('browse');
  const flagged = data.cases.filter(c => c.signal !== 'positive').length;
  const views = [
    { id: 'browse',  label: 'Browse',   badge: data.cases.length },
    { id: 'court',   label: 'By court' },
    { id: 'topic',   label: 'By topic' },
    { id: 'flagged', label: 'Flagged',  badge: flagged },
  ];
  return (
    <div>
      <RsSubNav views={views} active={sub} onChange={setSub} />
      {sub === 'browse'  && <ResearchCaseLaw data={data} />}
      {sub === 'court'   && <RsCasesByCourt data={data} />}
      {sub === 'topic'   && <RsCasesByTopic data={data} />}
      {sub === 'flagged' && <RsCasesFlagged data={data} />}
    </div>
  );
}
window.RsCasesHub = RsCasesHub;

function RsStatutesHub({ data }) {
  const [sub, setSub] = useRsH('browse');
  const views = [
    { id: 'browse',     label: 'Browse', badge: data.statutes.length },
    { id: 'juris',      label: 'By jurisdiction' },
    { id: 'amendments', label: 'Recent amendments' },
  ];
  return (
    <div>
      <RsSubNav views={views} active={sub} onChange={setSub} />
      {sub === 'browse'     && <ResearchStatutes data={data} />}
      {sub === 'juris'      && <RsStatByJuris data={data} />}
      {sub === 'amendments' && <RsStatAmendments data={data} />}
    </div>
  );
}
window.RsStatutesHub = RsStatutesHub;

function RsRegsHub({ data }) {
  const [sub, setSub] = useRsH('browse');
  const views = [
    { id: 'browse',    label: 'Browse', badge: data.regulations.length },
    { id: 'agency',    label: 'By agency' },
    { id: 'changelog', label: 'Change log' },
  ];
  return (
    <div>
      <RsSubNav views={views} active={sub} onChange={setSub} />
      {sub === 'browse'    && <ResearchRegulations data={data} />}
      {sub === 'agency'    && <RsRegByAgency data={data} />}
      {sub === 'changelog' && <RsRegChangeLog data={data} />}
    </div>
  );
}
window.RsRegsHub = RsRegsHub;

function RsSecondaryHub({ data }) {
  const [sub, setSub] = useRsH('browse');
  const views = [
    { id: 'browse',    label: 'Browse', badge: data.secondary.length },
    { id: 'type',      label: 'By type' },
    { id: 'providers', label: 'Providers' },
  ];
  return (
    <div>
      <RsSubNav views={views} active={sub} onChange={setSub} />
      {sub === 'browse'    && <ResearchSecondary data={data} />}
      {sub === 'type'      && <RsSecByType data={data} />}
      {sub === 'providers' && <RsSecProviders data={data} />}
    </div>
  );
}
window.RsSecondaryHub = RsSecondaryHub;

function RsCitatorHub({ data }) {
  const [sub, setSub] = useRsH('focal');
  const views = [
    { id: 'focal',      label: 'Focal case' },
    { id: 'treatments', label: 'Treatments', badge: data.citator.treatments.length },
    { id: 'history',    label: 'History',    badge: data.citator.history.length },
    { id: 'batch',      label: 'Batch check' },
  ];
  return (
    <div>
      <RsSubNav views={views} active={sub} onChange={setSub} />
      {sub === 'focal'      && <ResearchCitator data={data} />}
      {sub === 'treatments' && <RsCitTreatments data={data} />}
      {sub === 'history'    && <RsCitHistory data={data} />}
      {sub === 'batch'      && <RsCitBatch data={data} />}
    </div>
  );
}
window.RsCitatorHub = RsCitatorHub;

function RsBriefsHub({ data }) {
  const [sub, setSub] = useRsH('progress');
  const filed = data.briefs.filter(b => b.status === 'Filed').length;
  const views = [
    { id: 'progress',  label: 'In progress',  badge: data.briefs.length - filed },
    { id: 'templates', label: 'Templates' },
    { id: 'archive',   label: 'Archive',      badge: filed },
    { id: 'health',    label: 'Cite health' },
  ];
  return (
    <div>
      <RsSubNav views={views} active={sub} onChange={setSub} />
      {sub === 'progress'  && <ResearchBriefs data={data} />}
      {sub === 'templates' && <RsBriefsTemplates data={data} />}
      {sub === 'archive'   && <RsBriefsArchive data={data} />}
      {sub === 'health'    && <RsBriefsCiteHealth data={data} />}
    </div>
  );
}
window.RsBriefsHub = RsBriefsHub;

function RsWorkspaceHub({ data }) {
  const [sub, setSub] = useRsH('all');
  const views = [
    { id: 'all',     label: 'All',     badge: data.workspaces.length },
    { id: 'pinned',  label: 'Pinned authorities' },
    { id: 'recent',  label: 'Recent' },
    { id: 'bundles', label: 'Bundles', badge: data.workspaces.reduce((a,w) => a + w.bundles, 0) },
  ];
  return (
    <div>
      <RsSubNav views={views} active={sub} onChange={setSub} />
      {sub === 'all'     && <ResearchWorkspace data={data} />}
      {sub === 'pinned'  && <RsWsPinned data={data} />}
      {sub === 'recent'  && <RsWsRecent data={data} />}
      {sub === 'bundles' && <RsWsBundles data={data} />}
    </div>
  );
}
window.RsWorkspaceHub = RsWorkspaceHub;

function RsAnalyticsHub({ data }) {
  const [sub, setSub] = useRsH('overview');
  const views = [
    { id: 'overview',  label: 'Overview' },
    { id: 'topics',    label: 'Topics',    badge: data.analytics.topTopics.length },
    { id: 'practice',  label: 'Practice',  badge: data.analytics.byPractice.length },
    { id: 'attorneys', label: 'Attorneys', badge: data.analytics.byAttorney.length },
  ];
  return (
    <div>
      <RsSubNav views={views} active={sub} onChange={setSub} />
      {sub === 'overview'  && <ResearchAnalytics data={data} />}
      {sub === 'topics'    && <RsAnTopics data={data} />}
      {sub === 'practice'  && <RsAnPractice data={data} />}
      {sub === 'attorneys' && <RsAnAttorneys data={data} />}
    </div>
  );
}
window.RsAnalyticsHub = RsAnalyticsHub;

function RsActivityHub({ data }) {
  const [sub, setSub] = useRsH('feed');
  const warnCount = data.activity.filter(a => a.severity === 'warn' || a.actor.includes('Citator') || a.actor === 'Compliance').length;
  const views = [
    { id: 'feed',   label: 'Feed',   badge: data.activity.length },
    { id: 'alerts', label: 'Alerts', badge: warnCount },
    { id: 'audit',  label: 'Audit log' },
  ];
  return (
    <div>
      <RsSubNav views={views} active={sub} onChange={setSub} />
      {sub === 'feed'   && <ResearchActivity data={data} />}
      {sub === 'alerts' && <RsActAlerts data={data} />}
      {sub === 'audit'  && <RsActAudit data={data} />}
    </div>
  );
}
window.RsActivityHub = RsActivityHub;
