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

// ── RISK TIMELINE / GANTT VIEW (#8) ──
function RiskTimeline({ data }) {
  const [hoveredRisk, setHoveredRisk] = useState(null);
  const [selectedRisk, setSelectedRisk] = useState(null);
  const containerRef = React.useRef(null);
  const [wide, setWide] = useState(true);
  React.useEffect(() => {
    const el = containerRef.current;
    if (!el) return;
    const update = () => setWide(el.getBoundingClientRect().width >= 760);
    update();
    const ro = new ResizeObserver(update);
    ro.observe(el);
    return () => ro.disconnect();
  }, []);
  const reg = data.register;

  const allDates = useMemo(() => {
    const dates = new Set();
    reg.forEach(r => r.history.forEach(h => dates.add(h.date)));
    return [...dates].sort();
  }, [reg]);

  const dateRange = allDates.length > 0 ? { start: allDates[0], end: allDates[allDates.length - 1] } : null;
  if (!dateRange) return <div style={{ padding: '40px', textAlign: 'center', color: T.color.text.tertiary }}>No history data.</div>;

  const startMs = new Date(dateRange.start).getTime();
  const endMs = new Date(dateRange.end).getTime();
  const totalMs = endMs - startMs || 1;
  const dateToX = (d) => ((new Date(d).getTime() - startMs) / totalMs) * 100;

  const sorted = [...reg].sort((a, b) => a.history[0].date.localeCompare(b.history[0].date));

  // Axis ticks — evenly spaced at the first/last/interior positions
  const axisTicks = allDates.filter((d, i, arr) => i === 0 || i === arr.length - 1 || i % Math.max(1, Math.floor(arr.length / 5)) === 0);

  // Milestones — alternate label position to prevent overlap
  const milestones = [
    { date: '2026-02-01', label: 'Complaint Filed' },
    { date: '2026-03-15', label: 'Amended Complaint' },
    { date: '2026-04-15', label: 'Harrington Depo' },
    { date: '2026-04-20', label: 'Today' },
  ].filter(m => new Date(m.date).getTime() >= startMs && new Date(m.date).getTime() <= endMs);

  const selected = selectedRisk ? reg.find(r => r.id === selectedRisk) : null;

  const timelineContent = (
    <div>
      {/* AI insight */}
      <div style={rk.card}>
        <div style={{ padding: '12px 16px', background: rk.crimsonBg, fontSize: '12px', color: T.color.text.secondary, lineHeight: 1.5 }}>
          <div style={{ fontSize: '10px', fontWeight: 600, color: rk.crimson, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>◆ AI Timeline Analysis</div>
          Risk velocity accelerated after April 12 discovery production — 5 of 15 risks were escalated in the following week. RSK-001 (Adverse MSJ) has shown consistent upward trajectory across all 4 assessment periods. RSK-003 (Daubert Challenge) is the only critical risk trending favorably.
        </div>
      </div>

      {/* Milestone bar — labels alternate above/below to avoid overlap */}
      <div style={{ ...rk.card, overflow: 'visible' }}>
        <div style={rk.cardH}><span>Case Milestones</span><span style={{ fontSize: '9px', color: T.color.text.tertiary }}>{dateRange.start} — {dateRange.end}</span></div>
        <div style={{ padding: '16px 24px', position: 'relative', height: '72px' }}>
          <div style={{ position: 'absolute', left: '24px', right: '24px', top: '36px', height: '2px', background: T.color.border.light }} />
          <div style={{ position: 'absolute', left: '24px', right: '24px', top: 0, bottom: 0 }}>
            {milestones.map((m, i) => {
              const x = dateToX(m.date);
              const isToday = m.label === 'Today';
              const below = i % 2 === 1;
              return (
                <div key={i} style={{ position: 'absolute', left: `${x}%`, top: '28px', transform: 'translateX(-50%)' }}>
                  <div style={{ width: '10px', height: '10px', borderRadius: '50%', background: isToday ? rk.crimson : '#3B82F6', border: `2px solid ${T.color.bg.card}`, margin: '0 auto' }} />
                  <div style={{ position: 'absolute', left: '50%', transform: 'translateX(-50%)', [below ? 'top' : 'bottom']: '14px', textAlign: 'center' }}>
                    <div style={{ fontSize: '9px', fontFamily: T.font.mono, color: T.color.text.tertiary, whiteSpace: 'nowrap' }}>{m.date.slice(5)}</div>
                    <div style={{ fontSize: '9px', fontWeight: 600, color: isToday ? rk.crimson : T.color.text.secondary, whiteSpace: 'nowrap' }}>{m.label}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Gantt-style risk lifecycle */}
      <div style={{ ...rk.card, overflow: 'visible' }}>
        <div style={rk.cardH}><span>Risk Lifecycle</span><span style={{ fontSize: '9px', color: T.color.text.tertiary }}>{sorted.length} risks{selected ? ` · ${selected.id} selected` : ''}</span></div>
        {/* Date axis — absolute positioning so labels align with bar positions */}
        <div style={{ position: 'relative', height: '24px', padding: '4px 60px 4px 180px', borderBottom: `1px solid ${T.color.border.light}`, background: T.color.bg.secondary }}>
          <div style={{ position: 'absolute', left: '180px', right: '60px', top: 0, bottom: 0 }}>
            {axisTicks.map((d, i) => {
              const x = dateToX(d);
              const alignment = i === 0 ? 'flex-start' : i === axisTicks.length - 1 ? 'flex-end' : 'center';
              const translate = i === 0 ? '0' : i === axisTicks.length - 1 ? '-100%' : '-50%';
              return (
                <div key={d} style={{ position: 'absolute', left: `${x}%`, top: '4px', transform: `translateX(${translate})`, fontSize: '9px', fontFamily: T.font.mono, color: T.color.text.tertiary, whiteSpace: 'nowrap', textAlign: alignment }}>{d.slice(5)}</div>
              );
            })}
          </div>
        </div>
        {sorted.map((r, i) => {
          const firstDate = r.history[0].date;
          const lastDate = r.history[r.history.length - 1].date;
          const startX = dateToX(firstDate);
          const endX = dateToX(lastDate);
          const barWidth = Math.max(endX - startX, 2);
          const isHovered = hoveredRisk === i;
          const isSelected = selectedRisk === r.id;
          return (
            <div key={r.id} style={{
              display: 'flex', alignItems: 'center', padding: '6px 16px',
              borderBottom: `1px solid ${T.color.border.light}`,
              background: isSelected ? rk.crimsonBg : isHovered ? T.color.bg.hover : 'transparent',
              borderLeft: isSelected ? `3px solid ${rk.crimson}` : '3px solid transparent',
              cursor: 'pointer', minHeight: '36px',
            }}
              onMouseEnter={() => setHoveredRisk(i)} onMouseLeave={() => setHoveredRisk(null)}
              onClick={() => setSelectedRisk(isSelected ? null : r.id)}>
              {/* Label */}
              <div style={{ width: '164px', flexShrink: 0, paddingRight: '12px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                  <span style={{ fontFamily: T.font.mono, fontSize: '9px', color: T.color.text.tertiary }}>{r.id}</span>
                  <span style={{ fontSize: '11px', fontWeight: 500, color: T.color.text.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.name.length > 22 ? r.name.slice(0, 22) + '…' : r.name}</span>
                </div>
              </div>
              {/* Timeline bar — reserve 20px at right for trend arrow */}
              <div style={{ flex: 1, position: 'relative', height: '20px' }}>
                <div style={{ position: 'absolute', left: 0, right: '20px', top: '9px', height: '2px', background: T.color.border.light }} />
                <div style={{ position: 'absolute', left: 0, right: '20px', top: 0, bottom: 0 }}>
                  <div style={{ position: 'absolute', left: `${startX}%`, width: `${barWidth}%`, top: '4px', height: '12px', borderRadius: '3px', background: `${scoreColor(r.score)}30`, border: `1px solid ${scoreColor(r.score)}50` }} />
                  {r.history.map((h, j) => {
                    const x = dateToX(h.date);
                    return (
                      <div key={j} style={{ position: 'absolute', left: `${x}%`, top: '6px', width: '8px', height: '8px', borderRadius: '50%', background: scoreColor(h.score), transform: 'translateX(-50%)', border: `1.5px solid ${T.color.bg.card}` }}>
                        {isHovered && (
                          <div style={{ position: 'absolute', bottom: '100%', left: '50%', transform: 'translateX(-50%)', fontSize: '8px', fontFamily: T.font.mono, color: scoreColor(h.score), fontWeight: 700, marginBottom: '2px', whiteSpace: 'nowrap' }}>{h.score}</div>
                        )}
                      </div>
                    );
                  })}
                </div>
                {/* Trend arrow — inside reserved 20px gutter on right */}
                <div style={{ position: 'absolute', right: 0, top: '2px', width: '20px', textAlign: 'center', fontSize: '11px', fontWeight: 700, color: trendColor(r.trend) }}>
                  {trendIcon(r.trend)}
                </div>
              </div>
              {/* Current score */}
              <div style={{ width: '36px', textAlign: 'right', flexShrink: 0 }}>
                <span style={{ fontFamily: T.font.mono, fontSize: '11px', fontWeight: 700, color: scoreColor(r.score) }}>{r.score}</span>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );

  return (
    <div ref={containerRef} style={{ width: '100%' }}>
      {!selected && timelineContent}
      {selected && !wide && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
          <RiskTimelineSidebar risk={selected} onClose={() => setSelectedRisk(null)} />
          {timelineContent}
        </div>
      )}
      {selected && wide && (
        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) 340px', gap: '16px', alignItems: 'start', width: '100%' }}>
          <div style={{ minWidth: 0, width: '100%' }}>{timelineContent}</div>
          <RiskTimelineSidebar risk={selected} onClose={() => setSelectedRisk(null)} />
        </div>
      )}
    </div>
  );
}

function RiskTimelineSidebar({ risk, onClose }) {
  const deltas = [];
  for (let i = 1; i < risk.history.length; i++) {
    deltas.push({
      date: risk.history[i].date,
      delta: risk.history[i].score - risk.history[i - 1].score,
      note: risk.history[i].note,
      score: risk.history[i].score,
    });
  }
  const firstScore = risk.history[0].score;
  const lastScore = risk.history[risk.history.length - 1].score;
  const velocity = lastScore - firstScore;

  return (
    <div style={{ ...rk.card, position: 'sticky', top: '12px', margin: 0 }}>
      <div style={{ ...rk.cardH, padding: '12px 16px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px', minWidth: 0 }}>
          <span style={{ fontFamily: T.font.mono, fontSize: '10px', color: T.color.text.tertiary }}>{risk.id}</span>
          <span style={{ fontSize: '13px', fontWeight: 700, color: T.color.text.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{risk.name}</span>
        </div>
        <button onClick={onClose} style={{ border: 'none', background: 'transparent', cursor: 'pointer', fontSize: '16px', color: T.color.text.tertiary, lineHeight: 1, padding: '0 4px' }} aria-label="Close">×</button>
      </div>

      <div style={{ padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: '12px', maxHeight: '70vh', overflowY: 'auto' }}>
        {/* KPI strip */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '6px' }}>
          <div style={{ padding: '8px', background: T.color.bg.secondary, borderRadius: '4px', border: `1px solid ${T.color.border.light}` }}>
            <div style={{ fontSize: '9px', color: T.color.text.tertiary, fontWeight: 600, textTransform: 'uppercase' }}>Score</div>
            <div style={{ fontSize: '18px', fontFamily: T.font.mono, fontWeight: 700, color: scoreColor(risk.score) }}>{risk.score}</div>
          </div>
          <div style={{ padding: '8px', background: T.color.bg.secondary, borderRadius: '4px', border: `1px solid ${T.color.border.light}` }}>
            <div style={{ fontSize: '9px', color: T.color.text.tertiary, fontWeight: 600, textTransform: 'uppercase' }}>Residual</div>
            <div style={{ fontSize: '18px', fontFamily: T.font.mono, fontWeight: 700, color: scoreColor(risk.residualScore || 0) }}>{risk.residualScore ?? '—'}</div>
          </div>
          <div style={{ padding: '8px', background: T.color.bg.secondary, borderRadius: '4px', border: `1px solid ${T.color.border.light}` }}>
            <div style={{ fontSize: '9px', color: T.color.text.tertiary, fontWeight: 600, textTransform: 'uppercase' }}>Velocity</div>
            <div style={{ fontSize: '18px', fontFamily: T.font.mono, fontWeight: 700, color: velocity > 0 ? '#C23030' : velocity < 0 ? '#1B7A4A' : '#6E7D9E' }}>{velocity > 0 ? '+' : ''}{velocity}</div>
          </div>
        </div>

        {/* Meta */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: '6px', fontSize: '11px' }}>
          {[
            ['Category', `${risk.category} · ${risk.subcategory}`],
            ['Matter', risk.matter],
            ['Owner', risk.owner],
            ['Status', risk.status],
            ['Trend', `${trendIcon(risk.trend)} ${risk.trend}`],
            ['Last Assessed', risk.lastAssessed],
            ['Next Review', risk.nextReview],
          ].map(([k, v]) => (
            <div key={k} style={{ display: 'flex', gap: '8px' }}>
              <div style={{ width: '96px', color: T.color.text.tertiary, fontSize: '10px', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{k}</div>
              <div style={{ flex: 1, color: T.color.text.primary }}>{v}</div>
            </div>
          ))}
        </div>

        {/* History */}
        <div>
          <div style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '6px' }}>Score History</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
            {risk.history.map((h, i) => {
              const prev = i > 0 ? risk.history[i - 1].score : h.score;
              const delta = h.score - prev;
              return (
                <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: '8px', padding: '6px 8px', background: T.color.bg.secondary, borderRadius: '4px', borderLeft: `3px solid ${scoreColor(h.score)}` }}>
                  <div style={{ fontFamily: T.font.mono, fontSize: '9px', color: T.color.text.tertiary, width: '52px', flexShrink: 0 }}>{h.date.slice(5)}</div>
                  <div style={{ fontFamily: T.font.mono, fontSize: '11px', fontWeight: 700, color: scoreColor(h.score), width: '24px', flexShrink: 0 }}>{h.score}</div>
                  {i > 0 && (
                    <div style={{ fontFamily: T.font.mono, fontSize: '9px', color: delta > 0 ? '#C23030' : delta < 0 ? '#1B7A4A' : '#6E7D9E', width: '28px', flexShrink: 0 }}>{delta > 0 ? `+${delta}` : delta === 0 ? '·' : delta}</div>
                  )}
                  {i === 0 && <div style={{ width: '28px', flexShrink: 0, fontSize: '9px', color: T.color.text.tertiary }}>start</div>}
                  <div style={{ fontSize: '10px', color: T.color.text.secondary, flex: 1, minWidth: 0 }}>{h.note}</div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Triggers */}
        {risk.triggers && risk.triggers.length > 0 && (
          <div>
            <div style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '6px' }}>Triggers</div>
            <ul style={{ margin: 0, paddingLeft: '16px', fontSize: '11px', color: T.color.text.secondary, display: 'flex', flexDirection: 'column', gap: '2px' }}>
              {risk.triggers.map((t, i) => <li key={i}>{t}</li>)}
            </ul>
          </div>
        )}

        {/* Controls */}
        {risk.controls && risk.controls.length > 0 && (
          <div>
            <div style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '6px' }}>Controls in Place</div>
            <ul style={{ margin: 0, paddingLeft: '16px', fontSize: '11px', color: T.color.text.secondary, display: 'flex', flexDirection: 'column', gap: '2px' }}>
              {risk.controls.map((c, i) => <li key={i}>{c}</li>)}
            </ul>
          </div>
        )}

        {/* Mitigation */}
        {risk.mitigation && (
          <div>
            <div style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '6px' }}>Mitigation Strategy</div>
            <div style={{ padding: '8px', background: rk.crimsonBg, borderRadius: '4px', fontSize: '11px', color: T.color.text.secondary, lineHeight: 1.5, border: `1px solid ${rk.crimson}20` }}>{risk.mitigation}</div>
          </div>
        )}
      </div>
    </div>
  );
}

// ── RISK CORRELATION GRAPH (#9) ──
function RiskGraph({ data }) {
  const [hoveredNode, setHoveredNode] = useState(null);
  const reg = data.register;
  const deps = data.dependencies || [];

  const hoveredConnections = hoveredNode
    ? deps.filter(d => d.from === hoveredNode || d.to === hoveredNode)
    : [];
  const connectedIds = new Set(hoveredConnections.flatMap(d => [d.from, d.to]));

  // Group risks by category
  const groups = {};
  reg.forEach(r => {
    if (!groups[r.category]) groups[r.category] = [];
    groups[r.category].push(r);
  });

  const catColors = {};
  data.categories.forEach(c => { catColors[c.name] = c.color; });

  // Count connections per risk
  const connectionCount = {};
  deps.forEach(d => {
    connectionCount[d.from] = (connectionCount[d.from] || 0) + 1;
    connectionCount[d.to] = (connectionCount[d.to] || 0) + 1;
  });
  const maxConnections = Math.max(...Object.values(connectionCount), 1);

  return (
    <div>
      {/* AI insight */}
      <div style={rk.card}>
        <div style={{ padding: '12px 16px', background: rk.crimsonBg, fontSize: '12px', color: T.color.text.secondary, lineHeight: 1.5 }}>
          <div style={{ fontSize: '10px', fontWeight: 600, color: rk.crimson, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>◆ AI Dependency Analysis</div>
          RSK-001 (Adverse MSJ) is the highest-connectivity node with {connectionCount['RSK-001'] || 0} dependencies — it is both the most impactful risk and the most influenced by other risks. Cascading failure through RSK-002 → RSK-001 → RSK-014 represents the critical path. Mitigating RSK-009 (Witness) would reduce cascade exposure by breaking 2 dependency chains.
        </div>
      </div>

      {/* Entity-style grouped view */}
      <div style={{ display: 'grid', gridTemplateColumns: `repeat(${Math.min(Object.keys(groups).length, 4)}, 1fr)`, gap: '12px', marginBottom: '16px' }}>
        {Object.entries(groups).map(([group, risks]) => (
          <div key={group} style={rk.card}>
            <div style={{ padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', alignItems: 'center', gap: '6px' }}>
              <div style={{ width: '8px', height: '8px', borderRadius: '50%', background: catColors[group] || '#6E7D9E' }} />
              <span style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>{group}</span>
              <span style={{ fontSize: '9px', color: T.color.text.tertiary, marginLeft: 'auto' }}>{risks.length}</span>
            </div>
            {risks.map(r => {
              const isHighlighted = hoveredNode === r.id || connectedIds.has(r.id);
              const conn = hoveredConnections.find(c => c.from === r.id || c.to === r.id);
              const connCount = connectionCount[r.id] || 0;
              return (
                <div key={r.id} style={{
                  padding: '6px 16px', borderBottom: `1px solid ${T.color.border.light}`,
                  cursor: 'pointer', transition: 'all 0.15s',
                  background: hoveredNode === r.id ? `${catColors[group] || '#6E7D9E'}10` : isHighlighted ? T.color.bg.hover : 'transparent',
                  borderLeft: isHighlighted ? `3px solid ${catColors[group] || '#6E7D9E'}` : '3px solid transparent',
                }} onMouseEnter={() => setHoveredNode(r.id)} onMouseLeave={() => setHoveredNode(null)}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                    <span style={{ fontWeight: 600, fontSize: '11px', color: hoveredNode === r.id ? catColors[group] : T.color.text.primary, flex: 1 }}>{r.name.length > 24 ? r.name.slice(0, 24) + '…' : r.name}</span>
                    {/* Connection count indicator */}
                    {connCount > 0 && (
                      <div style={{ display: 'flex', gap: '1px' }}>
                        {Array.from({ length: Math.min(connCount, 5) }).map((_, k) => (
                          <div key={k} style={{ width: '4px', height: '4px', borderRadius: '50%', background: rk.crimson }} />
                        ))}
                      </div>
                    )}
                    <span style={{ fontFamily: T.font.mono, fontSize: '9px', fontWeight: 700, color: scoreColor(r.score) }}>{r.score}</span>
                  </div>
                  <div style={{ fontSize: '9px', color: T.color.text.tertiary }}>{r.id} · {r.owner}</div>
                  {conn && hoveredNode !== r.id && (
                    <div style={{ fontSize: '9px', color: catColors[group] || rk.crimson, marginTop: '2px', fontWeight: 500 }}>↔ {conn.label}</div>
                  )}
                </div>
              );
            })}
          </div>
        ))}
      </div>

      {/* Dependency list */}
      <div style={rk.card}>
        <div style={rk.cardH}><span>All Dependencies</span><span style={{ fontSize: '10px', color: T.color.text.tertiary }}>{deps.length} connections</span></div>
        {deps.map((d, i) => {
          const fromRisk = reg.find(r => r.id === d.from);
          const toRisk = reg.find(r => r.id === d.to);
          const isHighlighted = hoveredNode && (d.from === hoveredNode || d.to === hoveredNode);
          return (
            <div key={i} style={{ padding: '6px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', alignItems: 'center', gap: '8px', fontSize: '11px', background: isHighlighted ? T.color.bg.hover : 'transparent' }}>
              <span style={{ fontFamily: T.font.mono, fontSize: '9px', color: rk.crimson, minWidth: '52px' }}>{d.from}</span>
              <span style={{ fontWeight: 500, color: T.color.text.primary, minWidth: '140px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{fromRisk?.name.slice(0, 28)}</span>
              <span style={{ color: T.color.text.tertiary, fontStyle: 'italic', flex: 1, textAlign: 'center', fontSize: '10px' }}>{d.label}</span>
              <span style={{ fontWeight: 500, color: T.color.text.primary, minWidth: '140px', textAlign: 'right', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{toRisk?.name.slice(0, 28)}</span>
              <span style={{ fontFamily: T.font.mono, fontSize: '9px', color: rk.crimson, minWidth: '52px', textAlign: 'right' }}>{d.to}</span>
              <div style={{ display: 'flex', gap: '2px' }}>
                {[1, 2, 3].map(w => (
                  <div key={w} style={{ width: '5px', height: '5px', borderRadius: '50%', background: w <= d.weight ? rk.crimson : T.color.border.light }} />
                ))}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ── WHAT-IF SIMULATOR (#10) ──
function RiskWhatIf({ data }) {
  const reg = data.register;
  const scenarios = data.scenarios;
  const mc = data.monteCarlo;

  const [overrides, setOverrides] = useState({});

  const toggleRisk = (id, action) => {
    setOverrides(prev => {
      const next = { ...prev };
      if (next[id] === action) delete next[id];
      else next[id] = action;
      return next;
    });
  };

  // Calculate adjusted scenario probabilities
  const adjustedScenarios = useMemo(() => {
    let mitigatedCount = 0;
    let materializedCount = 0;
    Object.values(overrides).forEach(v => { if (v === 'mitigated') mitigatedCount++; if (v === 'materialized') materializedCount++; });

    return scenarios.map(sc => {
      let adjProb = sc.probability;
      // Each mitigated risk shifts probability toward better outcomes
      // Each materialized risk shifts toward worse outcomes
      const linkedMitigated = sc.risks.filter(rId => overrides[rId] === 'mitigated').length;
      const linkedMaterialized = sc.risks.filter(rId => overrides[rId] === 'materialized').length;

      if (sc.id === 'SC-01') adjProb += linkedMitigated * 5 - linkedMaterialized * 4;
      else if (sc.id === 'SC-02') adjProb += linkedMitigated * 3 - linkedMaterialized * 3;
      else if (sc.id === 'SC-03') adjProb -= linkedMitigated * 3 - linkedMaterialized * 4;
      else if (sc.id === 'SC-04') adjProb -= linkedMitigated * 4 - linkedMaterialized * 5;

      return { ...sc, adjProb: Math.max(1, Math.min(80, Math.round(adjProb))) };
    });
  }, [overrides, scenarios]);

  // Normalize probabilities
  const totalProb = adjustedScenarios.reduce((s, sc) => s + sc.adjProb, 0);
  const normalized = adjustedScenarios.map(sc => ({ ...sc, normProb: Math.round((sc.adjProb / totalProb) * 100) }));

  // Adjusted expected value (rough)
  const scenarioValues = { 'SC-01': 18700000, 'SC-02': 12200000, 'SC-03': 6250000, 'SC-04': -500000 };
  const adjustedEV = normalized.reduce((s, sc) => s + (scenarioValues[sc.id] || 0) * (sc.normProb / 100), 0);
  const evDelta = adjustedEV - mc.expectedValue;

  const overrideCount = Object.keys(overrides).length;

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={rk.stat}><span style={rk.statLabel}>Overrides Applied</span><span style={rk.statValue}>{overrideCount}</span></div>
        <div style={rk.stat}><span style={rk.statLabel}>Base EV</span><span style={rk.statValue}>${(mc.expectedValue / 1e6).toFixed(1)}M</span></div>
        <div style={rk.stat}><span style={rk.statLabel}>Adjusted EV</span><span style={{ ...rk.statValue, color: adjustedEV > mc.expectedValue ? '#1B7A4A' : adjustedEV < mc.expectedValue ? '#C23030' : T.color.text.primary }}>${(adjustedEV / 1e6).toFixed(1)}M</span></div>
        <div style={rk.stat}><span style={rk.statLabel}>EV Delta</span><span style={{ ...rk.statValue, color: evDelta > 0 ? '#1B7A4A' : evDelta < 0 ? '#C23030' : T.color.text.tertiary }}>{evDelta >= 0 ? '+' : ''}${(evDelta / 1e6).toFixed(1)}M</span></div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '16px' }}>
        {/* Risk toggles */}
        <div style={rk.card}>
          <div style={rk.cardH}>
            <span>Toggle Risks</span>
            {overrideCount > 0 && <button onClick={() => setOverrides({})} style={{ ...rk.filterBtn, fontSize: '10px', padding: '2px 8px' }}>Reset All</button>}
          </div>
          {reg.map(r => {
            const state = overrides[r.id];
            return (
              <div key={r.id} style={{ padding: '6px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', alignItems: 'center', gap: '8px', fontSize: '11px', background: state ? (state === 'mitigated' ? 'rgba(27,122,74,0.04)' : 'rgba(194,48,48,0.04)') : 'transparent' }}>
                <span style={{ fontFamily: T.font.mono, fontSize: '9px', color: T.color.text.tertiary, width: '52px' }}>{r.id}</span>
                <span style={{ flex: 1, fontWeight: 500, color: T.color.text.primary }}>{r.name.length > 30 ? r.name.slice(0, 30) + '…' : r.name}</span>
                <span style={{ fontFamily: T.font.mono, fontSize: '10px', fontWeight: 700, color: scoreColor(r.score), width: '20px' }}>{r.score}</span>
                <button onClick={() => toggleRisk(r.id, 'mitigated')}
                  style={{ ...rk.filterBtn, fontSize: '9px', padding: '2px 6px', ...(state === 'mitigated' ? { background: '#1B7A4A', color: '#fff', borderColor: '#1B7A4A' } : {}) }}>
                  ok Mitigated
                </button>
                <button onClick={() => toggleRisk(r.id, 'materialized')}
                  style={{ ...rk.filterBtn, fontSize: '9px', padding: '2px 6px', ...(state === 'materialized' ? { background: '#C23030', color: '#fff', borderColor: '#C23030' } : {}) }}>
                  x Materialized
                </button>
              </div>
            );
          })}
        </div>

        {/* Adjusted scenario probabilities */}
        <div>
          <div style={rk.card}>
            <div style={rk.cardH}><span>Scenario Impact</span></div>
            {normalized.map((sc, i) => {
              const delta = sc.normProb - sc.probability;
              const probColor = sc.id === 'SC-01' || sc.id === 'SC-02' ? '#1B7A4A' : '#C23030';
              return (
                <div key={sc.id} style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}` }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '6px' }}>
                    <span style={{ fontWeight: 600, fontSize: '12px', color: T.color.text.primary }}>{sc.name}</span>
                    <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                      <span style={{ fontFamily: T.font.mono, fontSize: '10px', color: T.color.text.tertiary }}>{sc.probability}%</span>
                      <span style={{ color: T.color.text.tertiary }}>→</span>
                      <span style={{ fontFamily: T.font.mono, fontSize: '12px', fontWeight: 700, color: probColor }}>{sc.normProb}%</span>
                      {delta !== 0 && (
                        <span style={{ fontSize: '10px', fontWeight: 600, color: delta > 0 ? (sc.id === 'SC-01' || sc.id === 'SC-02' ? '#1B7A4A' : '#C23030') : (sc.id === 'SC-01' || sc.id === 'SC-02' ? '#C23030' : '#1B7A4A') }}>
                          {delta > 0 ? '+' : ''}{delta}
                        </span>
                      )}
                    </div>
                  </div>
                  <div style={{ display: 'flex', gap: '4px', height: '8px' }}>
                    <div style={{ width: `${sc.probability}%`, height: '100%', borderRadius: '3px', background: `${probColor}30` }} />
                    <div style={{ width: `${sc.normProb}%`, height: '100%', borderRadius: '3px', background: probColor, marginTop: '0' }} />
                  </div>
                  <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginTop: '4px' }}>{sc.damages} · {sc.timeline}</div>
                </div>
              );
            })}
          </div>

          {/* Summary insight */}
          <div style={rk.card}>
            <div style={{ padding: '12px 16px', background: evDelta >= 0 ? 'rgba(27,122,74,0.04)' : rk.crimsonBg, fontSize: '12px', color: T.color.text.secondary, lineHeight: 1.5 }}>
              <div style={{ fontSize: '10px', fontWeight: 600, color: evDelta >= 0 ? '#1B7A4A' : rk.crimson, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>
                ◆ {overrideCount === 0 ? 'Baseline' : 'What-If'} Summary
              </div>
              {overrideCount === 0
                ? 'Toggle risks as "Mitigated" or "Materialized" to see how scenario probabilities and expected case value shift. This helps prioritize which risks to address first.'
                : `With ${Object.values(overrides).filter(v => v === 'mitigated').length} risks mitigated and ${Object.values(overrides).filter(v => v === 'materialized').length} materialized, the expected case value ${evDelta >= 0 ? 'increases' : 'decreases'} by $${Math.abs(evDelta / 1e6).toFixed(1)}M. ${evDelta >= 0 ? 'This mitigation strategy improves the overall case outlook.' : 'These risk materializations significantly impact case valuation.'}`
              }
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { RiskTimeline, RiskGraph, RiskWhatIf });
