// RESEARCH PLATFORM — Authority browsers: CaseLaw, Statutes, Regulations, Secondary
const { useState, useMemo } = React;
const T2 = window.ArbiterTokens;

function ResearchCaseLaw({ data }) {
  const rs = window.__rs;
  const [topicFilter, setTopicFilter] = useState('All');
  const [signalFilter, setSignalFilter] = useState('All');

  const topics = useMemo(() => ['All', ...new Set(data.cases.map(c => c.topic))], [data]);
  const filtered = data.cases.filter(c =>
    (topicFilter === 'All' || c.topic === topicFilter) &&
    (signalFilter === 'All' || c.signal === signalFilter)
  );

  const signalStyle = (s) => s === 'positive' ? rs.signalPositive : s === 'caution' ? rs.signalCaution : s === 'negative' ? rs.signalNegative : s === 'overruled' ? rs.signalOverruled : rs.signalNeutral;
  const maxCases = Math.max(...data.courtBreakdown.map(c => c.cases));

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: '16px', marginBottom: '16px' }}>
        {/* Cases table */}
        <div style={rs.card}>
          <div style={rs.cardH}>
            <span>Case law — {filtered.length} cases</span>
            <div style={{ display: 'flex', gap: '6px' }}>
              <select value={topicFilter} onChange={e => setTopicFilter(e.target.value)}
                style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${T2.color.border.light}`, borderRadius: '5px', background: T2.color.bg.card, color: T2.color.text.secondary, fontFamily: T2.font.family }}>
                {topics.map(t => <option key={t} value={t}>Topic: {t}</option>)}
              </select>
              <select value={signalFilter} onChange={e => setSignalFilter(e.target.value)}
                style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${T2.color.border.light}`, borderRadius: '5px', background: T2.color.bg.card, color: T2.color.text.secondary, fontFamily: T2.font.family }}>
                {['All', 'positive', 'caution', 'negative'].map(s => <option key={s} value={s}>Signal: {s}</option>)}
              </select>
            </div>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={rs.th}>Case</th>
                <th style={rs.th}>Court</th>
                <th style={rs.th}>Topic</th>
                <th style={rs.th}>Signal</th>
                <th style={{ ...rs.th, textAlign: 'right' }}>Citations</th>
                <th style={rs.th}>Checked</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(c => (
                <tr key={c.id}>
                  <td style={{ ...rs.td, maxWidth: '300px' }}>
                    <div style={{ fontSize: '12px', fontWeight: 600, color: T2.color.text.primary }}>{c.shortCite}</div>
                    <div style={{ fontSize: '11px', color: T2.color.text.tertiary, fontFamily: T2.font.mono, marginTop: '2px' }}>{c.cite}</div>
                    <div style={{ fontSize: '11px', color: T2.color.text.secondary, marginTop: '4px', lineHeight: 1.5 }}>{c.headnote}</div>
                  </td>
                  <td style={{ ...rs.td, color: T2.color.text.secondary }}>{c.court} · {c.year}</td>
                  <td style={rs.td}>
                    <span style={{ ...rs.tag, background: rs.indigoBg, color: rs.indigo }}>{c.topic}</span>
                  </td>
                  <td style={rs.td}><span style={{ ...rs.tag, ...signalStyle(c.signal) }}>{c.signal}</span></td>
                  <td style={{ ...rs.td, textAlign: 'right', fontFamily: T2.font.mono, color: T2.color.text.primary }}>{c.cites.toLocaleString()}</td>
                  <td style={{ ...rs.td, color: T2.color.text.tertiary, fontSize: '11px' }}>{c.lastChecked}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Court breakdown */}
        <div style={rs.card}>
          <div style={rs.cardH}>Court breakdown · {data.courtBreakdown.reduce((s, c) => s + c.cases, 0).toLocaleString()} total</div>
          <div style={{ padding: '8px 16px 14px' }}>
            {data.courtBreakdown.map(c => (
              <div key={c.court} style={{ padding: '6px 0', borderBottom: `1px solid ${T2.color.border.light}` }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px', fontSize: '12px' }}>
                  <span style={{ color: T2.color.text.primary, fontWeight: 500 }}>{c.court}</span>
                  <span style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                    <span style={{ ...rs.tag, background: c.signal === 'binding' ? rs.tealBg : rs.indigoBg, color: c.signal === 'binding' ? rs.teal : rs.indigo }}>{c.signal}</span>
                    <span style={{ fontFamily: T2.font.mono, color: T2.color.text.secondary, fontSize: '11px', minWidth: '30px', textAlign: 'right' }}>{c.cases}</span>
                  </span>
                </div>
                <div style={{ height: '3px', background: T2.color.border.light, borderRadius: '2px', overflow: 'hidden' }}>
                  <div style={{ width: `${(c.cases / maxCases) * 100}%`, height: '100%', background: c.signal === 'binding' ? rs.teal : rs.indigo }} />
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function ResearchStatutes({ data }) {
  const rs = window.__rs;
  const [jur, setJur] = useState('All');
  const jurs = useMemo(() => ['All', ...new Set(data.statutes.map(s => s.jurisdiction))], [data]);
  const filtered = data.statutes.filter(s => jur === 'All' || s.jurisdiction === jur);

  return (
    <div style={rs.card}>
      <div style={rs.cardH}>
        <span>Statutes — {filtered.length}</span>
        <select value={jur} onChange={e => setJur(e.target.value)}
          style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${T2.color.border.light}`, borderRadius: '5px', background: T2.color.bg.card, color: T2.color.text.secondary }}>
          {jurs.map(j => <option key={j} value={j}>Jurisdiction: {j}</option>)}
        </select>
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr>
            <th style={rs.th}>Cite</th>
            <th style={rs.th}>Title</th>
            <th style={rs.th}>Jurisdiction</th>
            <th style={rs.th}>Last amended</th>
            <th style={rs.th}>Version</th>
            <th style={rs.th}>Used in</th>
          </tr>
        </thead>
        <tbody>
          {filtered.map(s => (
            <tr key={s.id}>
              <td style={rs.td}>
                <div style={{ fontFamily: T2.font.mono, fontSize: '12px', color: T2.color.text.primary, fontWeight: 600 }}>{s.short}</div>
                <div style={{ fontFamily: T2.font.mono, fontSize: '10px', color: T2.color.text.tertiary, marginTop: '2px' }}>{s.cite}</div>
              </td>
              <td style={{ ...rs.td, maxWidth: '360px' }}>
                <div style={{ fontSize: '12px', fontWeight: 500, color: T2.color.text.primary }}>{s.title}</div>
                <div style={{ fontSize: '11px', color: T2.color.text.secondary, marginTop: '3px', lineHeight: 1.5 }}>{s.synopsis}</div>
              </td>
              <td style={{ ...rs.td, color: T2.color.text.secondary }}>{s.jurisdiction}</td>
              <td style={{ ...rs.td, color: T2.color.text.secondary }}>{s.lastAmended}</td>
              <td style={rs.td}>
                <span style={{ ...rs.tag, ...(s.changes > 0 ? rs.signalCaution : rs.signalPositive) }}>
                  {s.changes > 0 ? `${s.changes} recent change${s.changes > 1 ? 's' : ''}` : s.version}
                </span>
              </td>
              <td style={rs.td}>
                {s.usedIn.length > 0 ? (
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: '3px' }}>
                    {s.usedIn.slice(0, 2).map(m => (
                      <span key={m} style={{ ...rs.tag, background: rs.indigoBg, color: rs.indigo }}>{m.length > 22 ? m.slice(0, 20) + '…' : m}</span>
                    ))}
                    {s.usedIn.length > 2 && <span style={{ fontSize: '10px', color: T2.color.text.tertiary }}>+{s.usedIn.length - 2}</span>}
                  </div>
                ) : <span style={{ fontSize: '10px', color: T2.color.text.tertiary }}>—</span>}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function ResearchRegulations({ data }) {
  const rs = window.__rs;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' }}>
      {data.regulations.map(r => (
        <div key={r.id} style={rs.card}>
          <div style={rs.cardH}>
            <span><span style={{ fontFamily: T2.font.mono, color: rs.indigo, fontWeight: 700 }}>{r.short}</span></span>
            <span style={{ ...rs.tag, background: rs.tealBg, color: rs.teal }}>{r.agency}</span>
          </div>
          <div style={{ padding: '12px 16px' }}>
            <div style={{ fontSize: '13px', fontWeight: 600, color: T2.color.text.primary, marginBottom: '4px' }}>{r.title}</div>
            <div style={{ fontFamily: T2.font.mono, fontSize: '10px', color: T2.color.text.tertiary, marginBottom: '8px' }}>{r.cite}</div>
            <div style={{ fontSize: '12px', color: T2.color.text.secondary, lineHeight: 1.55, marginBottom: '12px' }}>{r.synopsis}</div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '10px', color: T2.color.text.tertiary }}>
              <span>Effective {r.effective} · amended {r.lastAmended}</span>
              {r.usedIn.length > 0 && <span>Used in {r.usedIn.length} matter{r.usedIn.length > 1 ? 's' : ''}</span>}
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

function ResearchSecondary({ data }) {
  const rs = window.__rs;
  const [type, setType] = useState('All');
  const types = useMemo(() => ['All', ...new Set(data.secondary.map(s => s.type))], [data]);
  const filtered = data.secondary.filter(s => type === 'All' || s.type === type);

  const typeStyle = (t) => {
    const map = {
      Treatise: { bg: rs.indigoBg, color: rs.indigo },
      Restatement: { bg: rs.violetBg, color: rs.violet },
      'Law Review': { bg: rs.tealBg, color: rs.teal },
      'Practice Guide': { bg: rs.amberBg, color: rs.amber },
    };
    return map[t] || { bg: rs.indigoBg, color: rs.indigo };
  };

  return (
    <div style={rs.card}>
      <div style={rs.cardH}>
        <span>Secondary sources — {filtered.length}</span>
        <div style={{ display: 'flex', gap: '6px' }}>
          {types.map(t => (
            <button key={t} onClick={() => setType(t)} style={{
              padding: '3px 10px', borderRadius: '12px', border: `1px solid ${type === t ? rs.indigo : T2.color.border.light}`,
              background: type === t ? rs.indigoBg : T2.color.bg.card, color: type === t ? rs.indigo : T2.color.text.secondary,
              fontSize: '11px', fontWeight: 500, cursor: 'pointer', fontFamily: T2.font.family,
            }}>{t}</button>
          ))}
        </div>
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr>
            <th style={rs.th}>Type</th>
            <th style={rs.th}>Title</th>
            <th style={rs.th}>Author</th>
            <th style={rs.th}>Volume / pinpoint</th>
            <th style={rs.th}>Topic</th>
            <th style={rs.th}>Provider</th>
            <th style={rs.th}>Used in</th>
          </tr>
        </thead>
        <tbody>
          {filtered.map(s => {
            const ts = typeStyle(s.type);
            return (
              <tr key={s.id}>
                <td style={rs.td}><span style={{ ...rs.tag, background: ts.bg, color: ts.color }}>{s.type}</span></td>
                <td style={{ ...rs.td, fontWeight: 600, color: T2.color.text.primary, maxWidth: '300px' }}>{s.title}</td>
                <td style={{ ...rs.td, color: T2.color.text.secondary }}>{s.author}</td>
                <td style={{ ...rs.td, fontFamily: T2.font.mono, color: T2.color.text.secondary, fontSize: '11px' }}>{s.volume}</td>
                <td style={{ ...rs.td, color: T2.color.text.secondary }}>{s.topic}</td>
                <td style={rs.td}><span style={{ ...rs.tag, background: T2.color.bg.secondary, color: T2.color.text.secondary }}>{s.provider}</span></td>
                <td style={{ ...rs.td, color: T2.color.text.secondary }}>{s.usedIn.length > 0 ? s.usedIn.join(', ') : '—'}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

window.ResearchCaseLaw = ResearchCaseLaw;
window.ResearchStatutes = ResearchStatutes;
window.ResearchRegulations = ResearchRegulations;
window.ResearchSecondary = ResearchSecondary;
