// RESEARCH PLATFORM — Dashboard + Search tabs
const { useState, useMemo } = React;
const T = window.ArbiterTokens;

function ResearchDashboard({ data }) {
  const rs = window.__rs;
  const k = data.kpis;
  const hoursDelta = ((k.researchHoursMTD - k.researchHoursPrior) / k.researchHoursPrior * 100).toFixed(0);

  const topTopics = data.analytics.topTopics.slice(0, 6);
  const maxVol = Math.max(...data.analytics.volumeByDay);
  const saved = data.history.filter(h => h.saved);

  return (
    <div>
      {/* KPI strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={rs.stat}>
          <span style={rs.statLabel}>Queries today</span>
          <span style={rs.statValue}>{k.queriesToday}</span>
          <span style={{ ...rs.statDelta, color: '#1B7A4A' }}>↑ {k.queriesYtd.toLocaleString()} YTD</span>
        </div>
        <div style={rs.stat}>
          <span style={rs.statLabel}>Saved items</span>
          <span style={rs.statValue}>{k.savedItems}</span>
          <span style={{ ...rs.statDelta, color: T.color.text.tertiary }}>{k.briefsInProgress} briefs in progress</span>
        </div>
        <div style={rs.stat}>
          <span style={rs.statLabel}>Citation health</span>
          <span style={{ ...rs.statValue, color: k.citationHealth >= 95 ? '#1B7A4A' : '#B45309' }}>{k.citationHealth}%</span>
          <span style={{ ...rs.statDelta, color: T.color.text.tertiary }}>across {k.briefsInProgress} drafts</span>
        </div>
        <div style={rs.stat}>
          <span style={rs.statLabel}>Hours MTD</span>
          <span style={rs.statValue}>{k.researchHoursMTD}</span>
          <span style={{ ...rs.statDelta, color: hoursDelta >= 0 ? '#1B7A4A' : '#C23030' }}>{hoursDelta >= 0 ? '↑' : '↓'} {Math.abs(hoursDelta)}% vs last month</span>
        </div>
        <div style={rs.stat}>
          <span style={rs.statLabel}>Cost avoided</span>
          <span style={rs.statValue}>${(k.costAvoided / 1000).toFixed(1)}K</span>
          <span style={{ ...rs.statDelta, color: '#1B7A4A' }}>vs outside counsel</span>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: '16px', marginBottom: '16px' }}>
        {/* AI-suggested queries */}
        <div style={rs.card}>
          <div style={rs.cardH}>
            <span><span style={{ color: rs.indigo }}>◆</span> AI — queries suggested for your active matters</span>
            <span style={{ ...rs.tag, background: rs.indigoBg, color: rs.indigo }}>{data.suggestions.length} new</span>
          </div>
          <div style={{ padding: '8px 16px 14px' }}>
            {data.suggestions.map((s, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 0', borderBottom: i < data.suggestions.length - 1 ? `1px solid ${T.color.border.light}` : 'none' }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: '13px', color: T.color.text.primary, fontWeight: 500 }}>{s.text}</div>
                  <div style={{ display: 'flex', gap: '10px', marginTop: '3px', fontSize: '10px', color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>
                    <span>{s.matterHint}</span>
                    <span style={{ ...rs.tag, background: s.novelty === 'fresh' ? rs.tealBg : rs.amberBg, color: s.novelty === 'fresh' ? rs.teal : rs.amber }}>{s.novelty}</span>
                  </div>
                </div>
                <button style={rs.btnSecondary}>Run →</button>
              </div>
            ))}
          </div>
        </div>

        {/* Volume sparkline + top topics */}
        <div style={rs.card}>
          <div style={rs.cardH}>
            <span>Query volume — last 14 days</span>
            <span style={{ fontSize: '10px', color: T.color.text.tertiary }}>total: {data.analytics.volumeByDay.reduce((a,b) => a+b, 0)}</span>
          </div>
          <div style={{ padding: '16px', display: 'flex', gap: '3px', alignItems: 'flex-end', height: '80px' }}>
            {data.analytics.volumeByDay.map((v, i) => (
              <div key={i} style={{ flex: 1, height: `${(v / maxVol) * 100}%`, background: i === data.analytics.volumeByDay.length - 1 ? rs.indigo : rs.indigoLight, opacity: i === data.analytics.volumeByDay.length - 1 ? 1 : 0.55, borderRadius: '2px 2px 0 0' }} />
            ))}
          </div>
          <div style={{ padding: '0 16px 14px', borderTop: `1px solid ${T.color.border.light}`, marginTop: '4px' }}>
            <div style={{ fontSize: '10px', textTransform: 'uppercase', letterSpacing: '0.08em', color: T.color.text.tertiary, margin: '12px 0 8px' }}>Top topics this week</div>
            {topTopics.map(t => (
              <div key={t.topic} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '5px 0', fontSize: '12px' }}>
                <span style={{ color: T.color.text.primary }}>{t.topic}</span>
                <span style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                  <span style={{ fontFamily: T.font.mono, color: T.color.text.secondary, fontSize: '11px' }}>{t.queries}</span>
                  <span style={{ fontSize: '10px', color: t.change >= 0 ? '#1B7A4A' : '#C23030', fontWeight: 600, minWidth: '26px', textAlign: 'right' }}>{t.change >= 0 ? '↑' : '↓'}{Math.abs(t.change)}%</span>
                </span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Recent searches table */}
      <div style={rs.card}>
        <div style={rs.cardH}><span>Recent searches</span><button style={rs.btnGhost}>View all →</button></div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={rs.th}>Query</th>
              <th style={rs.th}>Matter</th>
              <th style={rs.th}>Jurisdiction</th>
              <th style={rs.th}>Author</th>
              <th style={{ ...rs.th, textAlign: 'right' }}>Results</th>
              <th style={rs.th}>When</th>
              <th style={rs.th}></th>
            </tr>
          </thead>
          <tbody>
            {data.history.map(h => (
              <tr key={h.id}>
                <td style={{ ...rs.td, maxWidth: '320px' }}>
                  <div style={{ fontWeight: 500, color: T.color.text.primary }}>{h.query}</div>
                  <div style={{ fontSize: '10px', color: T.color.text.tertiary, fontFamily: T.font.mono, marginTop: '2px' }}>{h.id}</div>
                </td>
                <td style={{ ...rs.td, color: T.color.text.secondary }}>{h.matter}</td>
                <td style={rs.td}>{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, color: T.color.text.secondary }}>{h.author}</td>
                <td style={{ ...rs.td, textAlign: 'right', fontFamily: T.font.mono, color: T.color.text.primary, fontWeight: 600 }}>{h.results}</td>
                <td style={{ ...rs.td, color: T.color.text.tertiary, fontSize: '11px' }}>{h.time}</td>
                <td style={rs.td}>{h.saved && <span style={{ ...rs.tag, background: rs.tealBg, color: rs.teal }}>* saved</span>}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Saved authorities quick list */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
        <div style={rs.card}>
          <div style={rs.cardH}>* Saved for active matters</div>
          <div>
            {saved.map(h => (
              <div key={h.id} style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}` }}>
                <div style={{ fontSize: '12px', fontWeight: 500, color: T.color.text.primary }}>{h.query}</div>
                <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginTop: '3px' }}>{h.matter} · {h.results} authorities · {h.time}</div>
              </div>
            ))}
          </div>
        </div>
        <div style={rs.card}>
          <div style={rs.cardH}>! Negative-treatment watch</div>
          <div>
            {data.activity.filter(a => a.severity === 'warn').map(a => (
              <div key={a.id} style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', gap: '12px' }}>
                <span style={{ ...rs.tag, ...rs.signalCaution }}><Icons.Flag size={11}/></span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: '12px', fontWeight: 500, color: T.color.text.primary }}>{a.target}</div>
                  <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginTop: '3px' }}>{a.action} · {a.matter} · {a.time}</div>
                </div>
              </div>
            ))}
            {data.activity.filter(a => a.severity === 'warn').length === 0 && (
              <div style={{ padding: '24px', textAlign: 'center', fontSize: '12px', color: T.color.text.tertiary }}>No negative-treatment flags this week.</div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

function ResearchSearchTab({ data }) {
  const rs = window.__rs;
  const [query, setQuery] = useState('');
  const [facets, setFacets] = useState({ jurisdiction: 'All', type: 'All', court: 'All', dateRange: 'Any' });
  const [mode, setMode] = useState('natural'); // natural | boolean | citation

  const combinedResults = useMemo(() => {
    const cases = data.cases.map(c => ({ kind: 'Case', title: c.shortCite, cite: c.cite, snippet: c.headnote, signal: c.signal, court: c.court, year: c.year, topic: c.topic, id: c.id }));
    const stats = data.statutes.map(s => ({ kind: 'Statute', title: s.short, cite: s.cite, snippet: s.synopsis, signal: 'positive', court: s.jurisdiction, year: s.lastAmended, topic: s.title, id: s.id }));
    const regs = data.regulations.map(r => ({ kind: 'Regulation', title: r.short, cite: r.cite, snippet: r.synopsis, signal: 'positive', court: r.agency, year: (r.lastAmended || '').toString(), topic: r.title, id: r.id }));
    const sec = data.secondary.map(s => ({ kind: 'Secondary', title: s.title, cite: `${s.author} — ${s.volume}`, snippet: s.topic, signal: 'neutral', court: s.provider, year: '', topic: s.type, id: s.id }));
    const all = [...cases, ...stats, ...regs, ...sec];
    if (!query.trim()) return all.slice(0, 12);
    const q = query.toLowerCase();
    return all.filter(r =>
      r.title.toLowerCase().includes(q) ||
      (r.snippet || '').toLowerCase().includes(q) ||
      (r.topic || '').toLowerCase().includes(q) ||
      (r.cite || '').toLowerCase().includes(q)
    );
  }, [query, data]);

  const signalStyle = (s) => s === 'positive' ? rs.signalPositive : s === 'caution' ? rs.signalCaution : s === 'negative' ? rs.signalNegative : s === 'overruled' ? rs.signalOverruled : rs.signalNeutral;

  return (
    <div>
      {/* Search bar */}
      <div style={{ ...rs.card, padding: '0' }}>
        <div style={{ padding: '14px 16px 10px' }}>
          <div style={{ display: 'flex', gap: '8px', marginBottom: '10px' }}>
            {['natural', 'boolean', 'citation'].map(m => (
              <button key={m} onClick={() => setMode(m)} style={{
                padding: '4px 12px', borderRadius: '6px', border: `1px solid ${mode === m ? rs.indigo : T.color.border.light}`,
                background: mode === m ? rs.indigoBg : T.color.bg.card, color: mode === m ? rs.indigo : T.color.text.secondary,
                fontSize: '11px', fontWeight: 600, textTransform: 'capitalize', cursor: 'pointer', fontFamily: T.font.family,
              }}>{m}</button>
            ))}
            <div style={{ flex: 1 }} />
            <button style={rs.btnSecondary}>AI Assist ◆</button>
            <button style={rs.btnPrimary}>Run search</button>
          </div>
          <input
            value={query}
            onChange={e => setQuery(e.target.value)}
            placeholder={mode === 'natural' ? 'Ask a legal question in plain English…' : mode === 'boolean' ? '(antitrust OR "price fixing") AND /s damages' : 'Enter a citation (e.g., 509 U.S. 579)'}
            style={{ width: '100%', height: '40px', border: `1px solid ${T.color.border.medium}`, borderRadius: '6px', padding: '0 14px', fontSize: '14px', fontFamily: T.font.family, background: T.color.bg.primary, color: T.color.text.primary, outline: 'none' }}
          />
        </div>
        {/* Facet row */}
        <div style={{ display: 'flex', gap: '8px', padding: '0 16px 14px', flexWrap: 'wrap', alignItems: 'center' }}>
          <span style={{ fontSize: '10px', textTransform: 'uppercase', letterSpacing: '0.08em', color: T.color.text.tertiary, fontWeight: 600, marginRight: '4px' }}>Filter</span>
          {[
            { k: 'jurisdiction', opts: ['All', 'Federal', 'Delaware', 'California', 'New York'] },
            { k: 'type', opts: ['All', 'Case', 'Statute', 'Regulation', 'Secondary'] },
            { k: 'court', opts: ['All', 'SCOTUS', 'Circuit', 'District', 'State High'] },
            { k: 'dateRange', opts: ['Any', 'Last year', 'Last 5 years', 'Since 2000'] },
          ].map(({ k, opts }) => (
            <select key={k} value={facets[k]} onChange={e => setFacets({ ...facets, [k]: e.target.value })}
              style={{ padding: '4px 8px', fontSize: '11px', border: `1px solid ${T.color.border.light}`, borderRadius: '5px', background: T.color.bg.card, color: T.color.text.secondary, fontFamily: T.font.family }}>
              {opts.map(o => <option key={o} value={o}>{k[0].toUpperCase() + k.slice(1)}: {o}</option>)}
            </select>
          ))}
          <div style={{ flex: 1 }} />
          <span style={{ fontSize: '11px', color: T.color.text.tertiary }}>{combinedResults.length} result{combinedResults.length === 1 ? '' : 's'}</span>
        </div>
      </div>

      {/* Suggestions row */}
      <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap', marginBottom: '16px' }}>
        {data.suggestions.slice(0, 4).map((s, i) => (
          <button key={i} onClick={() => setQuery(s.text)} style={{
            padding: '5px 12px', borderRadius: '14px', border: `1px solid ${rs.indigoBorder}`,
            background: rs.indigoBg, fontSize: '11px', color: rs.indigo, cursor: 'pointer', fontFamily: T.font.family,
          }}>◆ {s.text}</button>
        ))}
      </div>

      {/* Result cards */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
        {combinedResults.slice(0, 16).map((r, i) => (
          <div key={`${r.kind}-${r.id}-${i}`} style={{ ...rs.card, marginBottom: 0, padding: '14px 16px' }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: '16px' }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', gap: '8px', alignItems: 'center', marginBottom: '4px' }}>
                  <span style={{ ...rs.tag, background: rs.indigoBg, color: rs.indigo }}>{r.kind}</span>
                  <span style={{ ...rs.tag, ...signalStyle(r.signal) }}>{r.signal}</span>
                  {r.topic && <span style={{ fontSize: '10px', color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>{r.topic}</span>}
                </div>
                <div style={{ fontSize: '14px', fontWeight: 600, color: T.color.text.primary, marginBottom: '3px' }}>{r.title}</div>
                <div style={{ fontSize: '11px', color: T.color.text.tertiary, fontFamily: T.font.mono, marginBottom: '6px' }}>{r.cite}</div>
                <div style={{ fontSize: '12px', color: T.color.text.secondary, lineHeight: 1.55 }}>{r.snippet}</div>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: '6px', alignItems: 'flex-end' }}>
                <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>{r.court}{r.year ? ` · ${r.year}` : ''}</div>
                <div style={{ display: 'flex', gap: '4px' }}>
                  <button style={rs.btnGhost}>* Save</button>
                  <button style={rs.btnGhost}>+ Brief</button>
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

window.ResearchDashboard = ResearchDashboard;
window.ResearchSearchTab = ResearchSearchTab;
