const { useState, useMemo } = React;
const T = window.ArbiterTokens;

// ── RISK REGISTER (Full Table) — with sparklines, bulk ops, evidence links, deep linking ──
function RiskRegister({ data, matrixFilter, onNavigateToMatter, onNavigateToEvidence }) {
  const [search, setSearch] = useState('');
  const [catFilter, setCatFilter] = useState('All');
  const [statusFilter, setStatusFilter] = useState('All');
  const [sortBy, setSortBy] = useState('score');
  const [hovered, setHovered] = useState(null);
  const [expanded, setExpanded] = useState(null);
  const [selected, setSelected] = useState(new Set());
  const [bulkAction, setBulkAction] = useState(null);

  const reg = data.register;
  const evLinks = data.evidenceLinks || {};
  const categories = ['All', ...new Set(reg.map(r => r.category))];
  const statuses = ['All', ...new Set(reg.map(r => r.status))];

  const filtered = useMemo(() => {
    let items = reg;
    // Matrix filter from dashboard click
    if (matrixFilter) {
      items = items.filter(r => r.likelihood === matrixFilter.li && r.impact === matrixFilter.im);
    }
    if (catFilter !== 'All') items = items.filter(r => r.category === catFilter);
    if (statusFilter !== 'All') items = items.filter(r => r.status === statusFilter);
    if (search) {
      const q = search.toLowerCase();
      items = items.filter(r => r.name.toLowerCase().includes(q) || r.id.toLowerCase().includes(q) || r.matter.toLowerCase().includes(q) || r.owner.toLowerCase().includes(q));
    }
    if (sortBy === 'score') items = [...items].sort((a, b) => b.score - a.score);
    if (sortBy === 'trend') items = [...items].sort((a, b) => (a.trend === 'rising' ? -1 : a.trend === 'declining' ? 1 : 0) - (b.trend === 'rising' ? -1 : b.trend === 'declining' ? 1 : 0));
    if (sortBy === 'category') items = [...items].sort((a, b) => a.category.localeCompare(b.category));
    if (sortBy === 'date') items = [...items].sort((a, b) => b.lastAssessed.localeCompare(a.lastAssessed));
    return items;
  }, [search, catFilter, statusFilter, sortBy, reg, matrixFilter]);

  const toggleSelect = (id) => {
    setSelected(prev => {
      const next = new Set(prev);
      next.has(id) ? next.delete(id) : next.add(id);
      return next;
    });
  };
  const toggleAll = () => {
    if (selected.size === filtered.length) setSelected(new Set());
    else setSelected(new Set(filtered.map(r => r.id)));
  };

  return (
    <div>
      {/* Stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={rk.stat}><span style={rk.statLabel}>Total Risks</span><span style={rk.statValue}>{reg.length}</span></div>
        <div style={rk.stat}><span style={rk.statLabel}>Active</span><span style={{ ...rk.statValue, color: '#C23030' }}>{reg.filter(r => r.status === 'Active').length}</span></div>
        <div style={rk.stat}><span style={rk.statLabel}>Monitoring</span><span style={{ ...rk.statValue, color: '#D97706' }}>{reg.filter(r => r.status === 'Monitoring').length}</span></div>
        <div style={rk.stat}><span style={rk.statLabel}>Planning</span><span style={{ ...rk.statValue, color: '#3B82F6' }}>{reg.filter(r => r.status === 'Planning').length}</span></div>
        <div style={rk.stat}><span style={rk.statLabel}>Avg Residual</span><span style={{ ...rk.statValue, color: T.color.status.active }}>{(reg.reduce((s, r) => s + r.residualScore, 0) / reg.length).toFixed(1)}</span></div>
      </div>

      {/* Toolbar */}
      <div style={{ display: 'flex', gap: '8px', marginBottom: '12px', alignItems: 'center', flexWrap: 'wrap' }}>
        <input style={{ height: '32px', border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.md, padding: '0 12px', fontSize: '12px', fontFamily: T.font.family, background: T.color.bg.card, color: T.color.text.primary, outline: 'none', width: '220px' }} placeholder="Search risks..." value={search} onChange={e => setSearch(e.target.value)} />
        {matrixFilter && (
          <span style={{ ...rk.filterBtn, ...rk.filterBtnActive, fontSize: '10px' }}>
            Matrix: L={matrixFilter.li} × I={matrixFilter.im}
          </span>
        )}
        {categories.slice(0, 7).map(c => (
          <button key={c} style={{ ...rk.filterBtn, ...(catFilter === c ? rk.filterBtnActive : {}) }} onClick={() => setCatFilter(c)}>{c}</button>
        ))}
        <div style={{ flex: 1 }} />
        <select style={{ ...rk.filterBtn, padding: '4px 8px' }} value={statusFilter} onChange={e => setStatusFilter(e.target.value)}>
          {statuses.map(s => <option key={s} value={s}>{s === 'All' ? 'All Statuses' : s}</option>)}
        </select>
        <select style={{ ...rk.filterBtn, padding: '4px 8px' }} value={sortBy} onChange={e => setSortBy(e.target.value)}>
          <option value="score">Sort: Score</option>
          <option value="trend">Sort: Trend</option>
          <option value="category">Sort: Category</option>
          <option value="date">Sort: Last Assessed</option>
        </select>
      </div>

      {/* Bulk action bar */}
      {selected.size > 0 && (
        <div style={{ display: 'flex', alignItems: 'center', gap: '10px', padding: '8px 16px', marginBottom: '12px', background: rk.crimsonBg, borderRadius: T.radius.lg, border: `1px solid ${rk.crimson}20` }}>
          <span style={{ fontSize: '12px', fontWeight: 600, color: rk.crimson }}>{selected.size} selected</span>
          <div style={{ flex: 1 }} />
          <select style={{ ...rk.filterBtn, padding: '3px 8px', fontSize: '11px' }} value={bulkAction || ''} onChange={e => setBulkAction(e.target.value)}>
            <option value="">Bulk Action...</option>
            <option value="reassign">Reassign Owner</option>
            <option value="status">Change Status</option>
            <option value="review">Set Review Date</option>
            <option value="escalate">Escalate (+2 score)</option>
            <option value="deescalate">De-escalate (-2 score)</option>
          </select>
          <button style={{ ...rk.filterBtn, ...rk.filterBtnActive, fontSize: '11px', padding: '3px 10px' }}
            onClick={() => { if (bulkAction) { setBulkAction(null); setSelected(new Set()); } }}>
            Apply
          </button>
          <button style={{ ...rk.filterBtn, fontSize: '11px', padding: '3px 8px' }} onClick={() => setSelected(new Set())}>Clear</button>
        </div>
      )}

      {/* Table */}
      <div style={rk.card}>
        <div style={{ display: 'grid', gridTemplateColumns: '28px 56px 1fr 52px 80px 44px 44px 55px 40px 62px', padding: '6px 16px', background: T.color.bg.secondary, borderBottom: `1px solid ${T.color.border.light}`, fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', gap: '6px', alignItems: 'center' }}>
          <span style={{ cursor: 'pointer' }} onClick={toggleAll}>
            <span style={{ width: '14px', height: '14px', borderRadius: '3px', border: `1.5px solid ${selected.size === filtered.length && filtered.length > 0 ? rk.crimson : T.color.border.medium}`, background: selected.size === filtered.length && filtered.length > 0 ? rk.crimson : 'transparent', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: '9px', color: '#fff' }}>
              {selected.size === filtered.length && filtered.length > 0 ? 'ok' : ''}
            </span>
          </span>
          <span>ID</span><span>Risk</span><span>Trend</span><span>Category</span><span>L</span><span>I</span><span>Score</span><span></span><span>Status</span>
        </div>
        {filtered.map((r, i) => {
          const isSelected = selected.has(r.id);
          return (
          <React.Fragment key={r.id}>
            <div
              style={{ display: 'grid', gridTemplateColumns: '28px 56px 1fr 52px 80px 44px 44px 55px 40px 62px', padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, alignItems: 'center', gap: '6px', fontSize: '12px', background: isSelected ? rk.crimsonBg : hovered === i ? T.color.bg.hover : 'transparent', cursor: 'pointer' }}
              onMouseEnter={() => setHovered(i)} onMouseLeave={() => setHovered(null)}
              onClick={() => setExpanded(expanded === i ? null : i)}>
              <span onClick={e => { e.stopPropagation(); toggleSelect(r.id); }} style={{ cursor: 'pointer' }}>
                <span style={{ width: '14px', height: '14px', borderRadius: '3px', border: `1.5px solid ${isSelected ? rk.crimson : T.color.border.medium}`, background: isSelected ? rk.crimson : 'transparent', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: '9px', color: '#fff' }}>
                  {isSelected ? 'ok' : ''}
                </span>
              </span>
              <span style={{ fontFamily: T.font.mono, fontSize: '10px', color: T.color.text.tertiary }}>{r.id}</span>
              <div>
                <div style={{ fontWeight: 500, color: T.color.text.primary }}>{r.name}</div>
                <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginTop: '1px' }}>{r.owner} · Review {r.nextReview}</div>
              </div>
              <Sparkline data={r.history} width={44} height={16} color={scoreColor(r.score)} />
              <span style={{ fontSize: '10px', color: T.color.text.secondary }}>{r.category}</span>
              <span style={{ fontFamily: T.font.mono, fontSize: '11px', textAlign: 'center', color: T.color.text.secondary }}>{r.likelihood}</span>
              <span style={{ fontFamily: T.font.mono, fontSize: '11px', textAlign: 'center', color: T.color.text.secondary }}>{r.impact}</span>
              <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                <div style={{ width: '24px', height: '5px', borderRadius: '3px', background: T.color.border.light }}>
                  <div style={{ width: `${(r.score / 25) * 100}%`, height: '100%', borderRadius: '3px', background: scoreColor(r.score) }} />
                </div>
                <span style={{ fontFamily: T.font.mono, fontSize: '11px', fontWeight: 700, color: scoreColor(r.score) }}>{r.score}</span>
              </div>
              <span style={{ fontSize: '12px', fontWeight: 700, color: trendColor(r.trend), textAlign: 'center' }}>{trendIcon(r.trend)}</span>
              <span style={{ fontSize: '9px', padding: '2px 6px', borderRadius: '8px', background: r.status === 'Active' ? 'rgba(194,48,48,0.06)' : r.status === 'Monitoring' ? 'rgba(217,119,6,0.06)' : 'rgba(59,130,246,0.06)', color: r.status === 'Active' ? '#C23030' : r.status === 'Monitoring' ? '#D97706' : '#3B82F6', fontWeight: 600 }}>{r.status}</span>
            </div>
            {/* Expanded detail with evidence links */}
            {expanded === i && (
              <div style={{ padding: '12px 16px 12px 44px', borderBottom: `1px solid ${T.color.border.light}`, background: T.color.bg.secondary, fontSize: '11px' }}>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '16px' }}>
                  <div>
                    <div style={{ fontWeight: 600, color: T.color.text.primary, marginBottom: '6px', fontSize: '10px', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Mitigation Strategy</div>
                    <div style={{ color: T.color.text.secondary, lineHeight: 1.5, marginBottom: '8px' }}>{r.mitigation}</div>
                    <div style={{ fontWeight: 600, color: T.color.text.primary, marginBottom: '4px', fontSize: '10px', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Triggers</div>
                    {r.triggers.map((t, j) => (
                      <div key={j} style={{ display: 'flex', gap: '6px', marginBottom: '2px', color: T.color.text.tertiary }}>
                        <span style={{ color: '#C23030' }}>•</span> {t}
                      </div>
                    ))}
                  </div>
                  <div>
                    <div style={{ fontWeight: 600, color: T.color.text.primary, marginBottom: '6px', fontSize: '10px', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Controls in Place</div>
                    {r.controls.map((c, j) => (
                      <div key={j} style={{ display: 'flex', gap: '6px', marginBottom: '2px', color: T.color.text.secondary }}>
                        <span style={{ color: T.color.status.active }}><Icons.Check size={11}/></span> {c}
                      </div>
                    ))}
                    <div style={{ marginTop: '8px' }}>
                      <div style={{ fontWeight: 600, color: T.color.text.primary, marginBottom: '4px', fontSize: '10px', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Residual Score</div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                        <span style={{ fontFamily: T.font.mono, fontSize: '14px', fontWeight: 700, color: scoreColor(r.score) }}>{r.score}</span>
                        <span style={{ color: T.color.text.tertiary }}>→</span>
                        <span style={{ fontFamily: T.font.mono, fontSize: '14px', fontWeight: 700, color: scoreColor(r.residualScore) }}>{r.residualScore}</span>
                        <span style={{ fontSize: '10px', color: T.color.status.active, fontWeight: 600 }}>(-{r.score - r.residualScore})</span>
                      </div>
                    </div>

                    {/* Matter deep link */}
                    {r.matterId && (
                      <div style={{ marginTop: '10px' }}>
                        <button onClick={() => onNavigateToMatter && onNavigateToMatter(r.matterId)} style={{ ...rk.filterBtn, fontSize: '10px', color: rk.crimson, borderColor: `${rk.crimson}40` }}>
                          Open Matter → {r.matter}
                        </button>
                      </div>
                    )}
                  </div>
                  <div>
                    <div style={{ fontWeight: 600, color: T.color.text.primary, marginBottom: '6px', fontSize: '10px', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Score History</div>
                    <div style={{ marginBottom: '8px' }}>
                      <Sparkline data={r.history} width={120} height={28} color={scoreColor(r.score)} />
                    </div>
                    {r.history.map((h, j) => (
                      <div key={j} style={{ display: 'flex', gap: '8px', marginBottom: '3px' }}>
                        <span style={{ fontFamily: T.font.mono, color: T.color.text.tertiary, minWidth: '72px', fontSize: '10px' }}>{h.date}</span>
                        <span style={{ fontFamily: T.font.mono, fontWeight: 700, color: scoreColor(h.score), minWidth: '20px', fontSize: '10px' }}>{h.score}</span>
                        <span style={{ color: T.color.text.tertiary, fontSize: '10px' }}>{h.note}</span>
                      </div>
                    ))}

                    {/* Evidence cross-references (#2) */}
                    {evLinks[r.id] && evLinks[r.id].length > 0 && (
                      <div style={{ marginTop: '10px' }}>
                        <div style={{ fontWeight: 600, color: T.color.text.primary, marginBottom: '4px', fontSize: '10px', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Linked Evidence</div>
                        <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>
                          {evLinks[r.id].map((evId, j) => (
                            <span key={j} onClick={e => { e.stopPropagation(); onNavigateToEvidence && onNavigateToEvidence(r.matterId); }}
                              style={{ fontSize: '9px', padding: '2px 6px', borderRadius: '8px', background: 'rgba(13,148,136,0.06)', color: '#0D9488', fontWeight: 600, fontFamily: T.font.mono, cursor: 'pointer' }}>
                              {evId}
                            </span>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            )}
          </React.Fragment>
          );
        })}
      </div>
    </div>
  );
}

window.RiskRegister = RiskRegister;
