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

// Risk platform shared styles — crimson accent
const rk = {
  container: { flex: 1, overflow: 'auto', background: T.color.bg.primary },
  header: {
    padding: '16px 24px', borderBottom: `1px solid ${T.color.border.light}`,
    background: T.color.bg.card, display: 'flex', alignItems: 'center', justifyContent: 'space-between',
  },
  headerTitle: { display: 'flex', alignItems: 'center', gap: '12px' },
  rkIcon: {
    width: '32px', height: '32px', borderRadius: '6px',
    background: 'linear-gradient(135deg, #B91C1C 0%, #991B1B 100%)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    fontSize: '14px', fontWeight: 700, color: '#fff',
  },
  title: { fontSize: '18px', fontWeight: 700, color: T.color.text.primary, letterSpacing: '-0.02em' },
  subtitle: { fontSize: '12px', color: T.color.text.tertiary, marginTop: '1px' },
  tabs: {
    display: 'flex', gap: '0', borderBottom: `1px solid ${T.color.border.light}`,
    background: T.color.bg.card, padding: '0 24px',
  },
  tab: {
    padding: '10px 16px', fontSize: '12px', fontWeight: 500,
    color: T.color.text.tertiary, cursor: 'pointer', border: 'none', background: 'none',
    borderBottom: '2px solid transparent', fontFamily: T.font.family,
    transition: 'all 0.15s', marginBottom: '-1px',
  },
  tabActive: { color: '#B91C1C', borderBottomColor: '#B91C1C', fontWeight: 600 },
  body: { padding: '20px 24px' },
  card: { background: T.color.bg.card, border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.lg, overflow: 'hidden', marginBottom: '16px' },
  cardH: { padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: '12px', fontWeight: 600, color: T.color.text.primary, display: 'flex', alignItems: 'center', justifyContent: 'space-between' },
  stat: { display: 'flex', flexDirection: 'column', gap: '2px', padding: '12px 16px', background: T.color.bg.secondary, borderRadius: '6px', border: `1px solid ${T.color.border.light}` },
  statLabel: { fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em' },
  statValue: { fontSize: '22px', fontWeight: 700, letterSpacing: '-0.02em', lineHeight: 1.1, color: T.color.text.primary },
  crimson: '#B91C1C',
  crimsonBg: 'rgba(185,28,28,0.06)',
  crimsonLight: '#DC2626',
  tag: { display: 'inline-flex', alignItems: 'center', padding: '2px 8px', borderRadius: '10px', fontSize: '10px', fontWeight: 600 },
  filterBtn: { padding: '4px 10px', borderRadius: T.radius.md, border: `1px solid ${T.color.border.light}`, background: T.color.bg.card, fontSize: '11px', fontWeight: 500, color: T.color.text.secondary, cursor: 'pointer', fontFamily: T.font.family },
  filterBtnActive: { background: '#B91C1C', color: '#fff', borderColor: '#B91C1C' },
  row: { padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', alignItems: 'center', gap: '10px', fontSize: '12px', transition: 'background 0.1s', cursor: 'pointer' },
  barTrack: { height: '6px', borderRadius: '3px', background: T.color.border.light },
  barFill: { height: '100%', borderRadius: '3px', transition: 'width 0.5s ease' },
};

window.rk = rk;

// Shared helpers
function scoreColor(s) { return s >= 15 ? '#C23030' : s >= 10 ? '#D97706' : s >= 5 ? '#3B82F6' : '#6E7D9E'; }
function trendIcon(t) { return t === 'rising' ? '↑' : t === 'declining' ? '↓' : '→'; }
function trendColor(t) { return t === 'rising' ? '#C23030' : t === 'declining' ? '#1B7A4A' : '#6E7D9E'; }
window.scoreColor = scoreColor;
window.trendIcon = trendIcon;
window.trendColor = trendColor;

// Sparkline component
function Sparkline({ data, width, height, color }) {
  if (!data || data.length < 2) return null;
  const maxY = Math.max(...data.map(d => d.score));
  const minY = Math.min(...data.map(d => d.score));
  const range = maxY - minY || 1;
  const points = data.map((d, i) => {
    const x = (i / (data.length - 1)) * width;
    const y = height - ((d.score - minY) / range) * (height - 2) - 1;
    return `${x},${y}`;
  }).join(' ');
  return (
    <svg width={width} height={height} style={{ display: 'block' }}>
      <polyline points={points} fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
      {data.length > 0 && (() => {
        const last = data[data.length - 1];
        const lx = width;
        const ly = height - ((last.score - minY) / range) * (height - 2) - 1;
        return <circle cx={lx} cy={ly} r="2" fill={color} />;
      })()}
    </svg>
  );
}
window.Sparkline = Sparkline;

// ── RISK DASHBOARD (Overview Tab) ──
function RiskDashboard({ data, onFilterFromMatrix, onNavigateToMatter }) {
  const [hoveredCell, setHoveredCell] = useState(null);
  const [selectedCell, setSelectedCell] = useState(null);
  const reg = data.register;

  const critical = reg.filter(r => r.score >= 15).length;
  const high = reg.filter(r => r.score >= 10 && r.score < 15).length;
  const medium = reg.filter(r => r.score >= 5 && r.score < 10).length;
  const low = reg.filter(r => r.score < 5).length;
  const rising = reg.filter(r => r.trend === 'rising').length;
  const avgScore = (reg.reduce((s, r) => s + r.score, 0) / reg.length).toFixed(1);

  // Build 5x5 risk matrix
  const matrix = Array.from({ length: 5 }, () => Array.from({ length: 5 }, () => []));
  reg.forEach(r => {
    const li = Math.min(r.likelihood, 5) - 1;
    const im = Math.min(r.impact, 5) - 1;
    matrix[li][im].push(r);
  });

  const matrixCellColor = (li, im) => {
    const s = (li + 1) * (im + 1);
    if (s >= 15) return 'rgba(194,48,48,0.15)';
    if (s >= 10) return 'rgba(217,119,6,0.12)';
    if (s >= 5) return 'rgba(59,130,246,0.08)';
    return 'rgba(110,125,158,0.05)';
  };

  // Selected cell filtered risks
  const selectedRisks = selectedCell ? matrix[selectedCell.li - 1][selectedCell.im - 1] : null;

  const handleCellClick = (li, im) => {
    const cellRisks = matrix[li - 1][im - 1];
    if (cellRisks.length === 0) return;
    if (selectedCell && selectedCell.li === li && selectedCell.im === im) {
      setSelectedCell(null);
    } else {
      setSelectedCell({ li, im });
    }
  };

  return (
    <div>
      {/* Stats row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 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}>Critical</span><span style={{ ...rk.statValue, color: '#C23030' }}>{critical}</span></div>
        <div style={rk.stat}><span style={rk.statLabel}>High</span><span style={{ ...rk.statValue, color: '#D97706' }}>{high}</span></div>
        <div style={rk.stat}><span style={rk.statLabel}>Medium</span><span style={{ ...rk.statValue, color: '#3B82F6' }}>{medium}</span></div>
        <div style={rk.stat}><span style={rk.statLabel}>Avg Score</span><span style={{ ...rk.statValue, color: scoreColor(parseFloat(avgScore)) }}>{avgScore}</span></div>
        <div style={rk.stat}><span style={rk.statLabel}>Trending Up</span><span style={{ ...rk.statValue, color: '#C23030' }}>{rising}</span></div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '16px' }}>
        {/* 5x5 Risk Matrix — Interactive */}
        <div style={rk.card}>
          <div style={rk.cardH}>
            <span>Risk Heat Map</span>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
              {selectedCell && (
                <button onClick={() => setSelectedCell(null)} style={{ ...rk.filterBtn, fontSize: '10px', padding: '2px 8px' }}>Clear Filter</button>
              )}
              {selectedCell && (
                <button onClick={() => onFilterFromMatrix && onFilterFromMatrix(selectedCell.li, selectedCell.im)} style={{ ...rk.filterBtn, ...rk.filterBtnActive, fontSize: '10px', padding: '2px 8px' }}>View in Register →</button>
              )}
              <span style={{ fontSize: '9px', color: T.color.text.tertiary }}>Click cell to filter</span>
            </div>
          </div>
          <div style={{ padding: '16px' }}>
            <div style={{ display: 'flex', gap: '0' }}>
              <div style={{ width: '24px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', paddingRight: '4px', paddingBottom: '24px' }}>
                {[5, 4, 3, 2, 1].map(l => (
                  <div key={l} style={{ fontSize: '9px', fontFamily: T.font.mono, color: T.color.text.tertiary, textAlign: 'right', height: '48px', display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>{l}</div>
                ))}
              </div>
              <div style={{ flex: 1 }}>
                {[5, 4, 3, 2, 1].map(li => (
                  <div key={li} style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '2px' }}>
                    {[1, 2, 3, 4, 5].map(im => {
                      const cellRisks = matrix[li - 1][im - 1];
                      const cellKey = `${li}-${im}`;
                      const isHovered = hoveredCell === cellKey;
                      const isSelected = selectedCell && selectedCell.li === li && selectedCell.im === im;
                      return (
                        <div
                          key={im}
                          onMouseEnter={() => setHoveredCell(cellKey)}
                          onMouseLeave={() => setHoveredCell(null)}
                          onClick={() => handleCellClick(li, im)}
                          style={{
                            height: '48px', borderRadius: '4px',
                            background: isSelected ? matrixCellColor(li, im).replace(/[\d.]+\)$/, '0.4)') : isHovered ? matrixCellColor(li, im).replace(/[\d.]+\)$/, '0.3)') : matrixCellColor(li, im),
                            border: isSelected ? `2px solid ${scoreColor(li * im)}` : cellRisks.length > 0 ? `2px solid ${scoreColor(li * im)}40` : `1px solid ${T.color.border.light}`,
                            display: 'flex', alignItems: 'center', justifyContent: 'center',
                            flexDirection: 'column', gap: '2px', cursor: cellRisks.length > 0 ? 'pointer' : 'default',
                            transition: 'all 0.15s', position: 'relative',
                            boxShadow: isSelected ? `0 0 0 2px ${scoreColor(li * im)}30` : 'none',
                          }}>
                          {cellRisks.length > 0 && (
                            <>
                              <span style={{ fontSize: '14px', fontWeight: 700, color: scoreColor(li * im) }}>{cellRisks.length}</span>
                              {isHovered && !isSelected && (
                                <div style={{
                                  position: 'absolute', bottom: '100%', left: '50%', transform: 'translateX(-50%)',
                                  background: T.color.navy900, color: T.color.ivory100, padding: '6px 10px',
                                  borderRadius: '6px', fontSize: '10px', whiteSpace: 'nowrap', zIndex: 10,
                                  boxShadow: T.shadow.lg, marginBottom: '4px',
                                }}>
                                  {cellRisks.map(r => r.id).join(', ')}
                                </div>
                              )}
                            </>
                          )}
                        </div>
                      );
                    })}
                  </div>
                ))}
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '2px', marginTop: '4px' }}>
                  {[1, 2, 3, 4, 5].map(i => (
                    <div key={i} style={{ textAlign: 'center', fontSize: '9px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>{i}</div>
                  ))}
                </div>
              </div>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '8px', padding: '0 24px' }}>
              <span style={{ fontSize: '9px', color: T.color.text.tertiary, fontStyle: 'italic' }}>← Likelihood</span>
              <span style={{ fontSize: '9px', color: T.color.text.tertiary, fontStyle: 'italic' }}>Impact →</span>
            </div>
          </div>

          {/* Filtered risks from matrix click */}
          {selectedRisks && selectedRisks.length > 0 && (
            <div style={{ borderTop: `1px solid ${T.color.border.light}`, padding: '8px 0' }}>
              <div style={{ padding: '4px 16px 6px', fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>
                L={selectedCell.li} × I={selectedCell.im} — {selectedRisks.length} risk{selectedRisks.length > 1 ? 's' : ''}
              </div>
              {selectedRisks.map(r => (
                <div key={r.id} style={{ padding: '6px 16px', display: 'flex', alignItems: 'center', gap: '8px', fontSize: '11px', borderBottom: `1px solid ${T.color.border.light}` }}>
                  <span style={{ fontFamily: T.font.mono, fontSize: '9px', color: T.color.text.tertiary, width: '52px' }}>{r.id}</span>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 500, color: T.color.text.primary }}>{r.name}</div>
                    <div style={{ fontSize: '9px', color: T.color.text.tertiary }}>{r.matter}</div>
                  </div>
                  <Sparkline data={r.history} width={48} height={16} color={scoreColor(r.score)} />
                  <span style={{ fontWeight: 700, color: trendColor(r.trend) }}>{trendIcon(r.trend)}</span>
                  <span style={{ fontFamily: T.font.mono, fontWeight: 700, color: scoreColor(r.score) }}>{r.score}</span>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Top risks with sparklines */}
        <div style={rk.card}>
          <div style={rk.cardH}><span>Top Risks by Score</span></div>
          {[...reg].sort((a, b) => b.score - a.score).slice(0, 8).map((r, i) => (
            <div key={r.id} style={{ padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', alignItems: 'center', gap: '10px', cursor: r.matterId ? 'pointer' : 'default' }}
              onClick={() => r.matterId && onNavigateToMatter && onNavigateToMatter(r.matterId)}>
              <span style={{ fontFamily: T.font.mono, fontSize: '10px', color: T.color.text.tertiary, width: '56px' }}>{r.id}</span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: '12px', fontWeight: 500, color: T.color.text.primary }}>{r.name}</div>
                <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginTop: '1px' }}>{r.category} · <span style={{ textDecoration: r.matterId ? 'underline' : 'none', textDecorationColor: T.color.border.medium }}>{r.matter}</span></div>
              </div>
              <Sparkline data={r.history} width={48} height={18} color={scoreColor(r.score)} />
              <span style={{ fontSize: '11px', fontWeight: 700, color: trendColor(r.trend) }}>{trendIcon(r.trend)}</span>
              <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                <div style={{ width: '32px', height: '6px', 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), minWidth: '20px' }}>{r.score}</span>
              </div>
            </div>
          ))}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
        {/* Category breakdown */}
        <div style={rk.card}>
          <div style={rk.cardH}><span>Risk by Category</span></div>
          {data.categories.map((c, i) => (
            <div key={c.name} style={{ padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', alignItems: 'center', gap: '10px', fontSize: '12px' }}>
              <div style={{ width: '8px', height: '8px', borderRadius: '50%', background: c.color, flexShrink: 0 }} />
              <span style={{ width: '100px', fontWeight: 500, color: T.color.text.primary }}>{c.name}</span>
              <div style={{ flex: 1, ...rk.barTrack }}>
                <div style={{ ...rk.barFill, width: `${(c.count / reg.length) * 100}%`, background: c.color }} />
              </div>
              <span style={{ fontFamily: T.font.mono, fontSize: '10px', color: T.color.text.secondary, minWidth: '20px' }}>{c.count}</span>
              <span style={{ fontFamily: T.font.mono, fontSize: '10px', color: scoreColor(c.avgScore), fontWeight: 600, minWidth: '32px' }}>avg {c.avgScore}</span>
            </div>
          ))}
        </div>

        {/* Recent activity */}
        <div style={rk.card}>
          <div style={rk.cardH}><span>Recent Risk Activity</span></div>
          {data.auditLog.slice(0, 8).map((l, i) => (
            <div key={i} style={{ padding: '6px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: '11px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
                <span style={{ fontWeight: 600, color: T.color.text.primary }}>{l.action}</span>
                <span style={{ fontFamily: T.font.mono, fontSize: '10px', color: T.color.text.tertiary }}>{l.date}</span>
              </div>
              <div style={{ color: T.color.text.tertiary, fontSize: '10px' }}>{l.user} — {l.detail}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

window.RiskDashboard = RiskDashboard;
