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

// ── MITIGATION TRACKER ──
function RiskMitigations({ data }) {
  const [statusFilter, setStatusFilter] = useState('All');
  const [hovered, setHovered] = useState(null);
  const mits = data.mitigations;
  const reg = data.register;

  const statuses = ['All', 'In Progress', 'Drafting', 'Not Started', 'Complete'];
  const filtered = statusFilter === 'All' ? mits : mits.filter(m => m.status === statusFilter);

  const priorityColor = { critical: '#C23030', high: '#D97706', medium: '#3B82F6', low: '#6E7D9E' };

  const dueSoon = mits.filter(m => { const d = Math.ceil((new Date(m.dueDate) - new Date('2026-04-20')) / 86400000); return m.status !== 'Complete' && d >= 0 && d <= 5; }).length;
  const avgProgress = Math.round(mits.reduce((s, m) => s + m.progress, 0) / mits.length);

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={rk.stat}><span style={rk.statLabel}>Total Actions</span><span style={rk.statValue}>{mits.length}</span></div>
        <div style={rk.stat}><span style={rk.statLabel}>Complete</span><span style={{ ...rk.statValue, color: '#1B7A4A' }}>{mits.filter(m => m.status === 'Complete').length}</span></div>
        <div style={rk.stat}><span style={rk.statLabel}>In Progress</span><span style={{ ...rk.statValue, color: '#D97706' }}>{mits.filter(m => m.status === 'In Progress' || m.status === 'Drafting').length}</span></div>
        <div style={rk.stat}><span style={rk.statLabel}>Due ≤5 Days</span><span style={{ ...rk.statValue, color: '#C23030' }}>{dueSoon}</span></div>
        <div style={rk.stat}><span style={rk.statLabel}>Avg Progress</span><span style={{ ...rk.statValue, color: rk.crimson }}>{avgProgress}%</span></div>
      </div>

      <div style={{ display: 'flex', gap: '8px', marginBottom: '12px' }}>
        {statuses.map(s => (
          <button key={s} style={{ ...rk.filterBtn, ...(statusFilter === s ? rk.filterBtnActive : {}) }} onClick={() => setStatusFilter(s)}>{s}</button>
        ))}
      </div>

      <div style={rk.card}>
        <div style={{ display: 'grid', gridTemplateColumns: '70px 1fr 90px 80px 70px 80px 100px', 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: '8px' }}>
          <span>ID</span><span>Action</span><span>Risk</span><span>Assignee</span><span>Priority</span><span>Due</span><span>Progress</span>
        </div>
        {filtered.map((m, i) => {
          const daysUntil = Math.ceil((new Date(m.dueDate) - new Date('2026-04-20')) / 86400000);
          const isOverdue = m.status !== 'Complete' && daysUntil < 0;
          const isDueSoon = m.status !== 'Complete' && daysUntil >= 0 && daysUntil <= 3;
          return (
            <div key={m.id} style={{ display: 'grid', gridTemplateColumns: '70px 1fr 90px 80px 70px 80px 100px', padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, alignItems: 'center', gap: '8px', fontSize: '12px', background: hovered === i ? T.color.bg.hover : 'transparent' }}
              onMouseEnter={() => setHovered(i)} onMouseLeave={() => setHovered(null)}>
              <span style={{ fontFamily: T.font.mono, fontSize: '10px', color: T.color.text.tertiary }}>{m.id}</span>
              <div>
                <div style={{ fontWeight: 500, color: T.color.text.primary }}>{m.action}</div>
                <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginTop: '1px' }}>{m.notes}</div>
              </div>
              <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: rk.crimson }}>{m.riskId}</span>
              <span style={{ fontSize: '11px', color: T.color.text.secondary }}>{m.assignee}</span>
              <span style={{ fontSize: '9px', padding: '2px 6px', borderRadius: '8px', background: `${priorityColor[m.priority]}10`, color: priorityColor[m.priority], fontWeight: 600 }}>{m.priority}</span>
              <span style={{ fontSize: '10px', fontWeight: 500, color: isOverdue ? '#C23030' : isDueSoon ? '#D97706' : T.color.text.secondary }}>
                {m.dueDate.slice(5)}
                {isOverdue && <span style={{ fontSize: '9px', color: '#C23030' }}> overdue</span>}
              </span>
              <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                <div style={{ flex: 1, height: '6px', borderRadius: '3px', background: T.color.border.light }}>
                  <div style={{ width: `${m.progress}%`, height: '100%', borderRadius: '3px', background: m.progress === 100 ? '#1B7A4A' : m.progress >= 50 ? '#D97706' : '#6E7D9E' }} />
                </div>
                <span style={{ fontFamily: T.font.mono, fontSize: '10px', fontWeight: 600, color: T.color.text.secondary, minWidth: '28px' }}>{m.progress}%</span>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ── SCENARIO ANALYSIS with interactive Monte Carlo (#7) ──
function RiskScenarios({ data }) {
  const [expanded, setExpanded] = useState(null);
  const [hoveredBucket, setHoveredBucket] = useState(null);
  const [confidenceRange, setConfidenceRange] = useState([25, 75]); // percentile range
  const scenarios = data.scenarios;
  const reg = data.register;
  const mc = data.monteCarlo;

  const probColor = (p) => p >= 40 ? '#1B7A4A' : p >= 20 ? '#D97706' : '#6E7D9E';

  // Map confidence range to dollar values
  const pctToValue = (pct) => {
    if (pct <= 10) return mc.p10;
    if (pct <= 25) return mc.p25;
    if (pct <= 50) return mc.median;
    if (pct <= 75) return mc.p75;
    return mc.p90;
  };
  const confLow = pctToValue(confidenceRange[0]);
  const confHigh = pctToValue(confidenceRange[1]);

  return (
    <div>
      {/* Monte Carlo summary with interactivity */}
      <div style={rk.card}>
        <div style={rk.cardH}><span>Monte Carlo Simulation — Case Valuation</span><span style={{ fontSize: '9px', color: T.color.text.tertiary }}>{mc.iterations.toLocaleString()} iterations</span></div>
        <div style={{ padding: '16px' }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: '12px', marginBottom: '16px' }}>
            <div style={{ textAlign: 'center' }}><div style={{ fontSize: '10px', color: T.color.text.tertiary, marginBottom: '2px' }}>Expected Value</div><div style={{ fontSize: '18px', fontWeight: 700, color: T.color.text.primary }}>${(mc.expectedValue / 1e6).toFixed(1)}M</div></div>
            <div style={{ textAlign: 'center' }}><div style={{ fontSize: '10px', color: T.color.text.tertiary, marginBottom: '2px' }}>Median</div><div style={{ fontSize: '18px', fontWeight: 700 }}>${(mc.median / 1e6).toFixed(1)}M</div></div>
            <div style={{ textAlign: 'center' }}><div style={{ fontSize: '10px', color: T.color.text.tertiary, marginBottom: '2px' }}>P10</div><div style={{ fontSize: '18px', fontWeight: 700, color: '#C23030' }}>${(mc.p10 / 1e6).toFixed(1)}M</div></div>
            <div style={{ textAlign: 'center' }}><div style={{ fontSize: '10px', color: T.color.text.tertiary, marginBottom: '2px' }}>P25</div><div style={{ fontSize: '18px', fontWeight: 700, color: '#D97706' }}>${(mc.p25 / 1e6).toFixed(1)}M</div></div>
            <div style={{ textAlign: 'center' }}><div style={{ fontSize: '10px', color: T.color.text.tertiary, marginBottom: '2px' }}>P75</div><div style={{ fontSize: '18px', fontWeight: 700, color: '#1B7A4A' }}>${(mc.p75 / 1e6).toFixed(1)}M</div></div>
            <div style={{ textAlign: 'center' }}><div style={{ fontSize: '10px', color: T.color.text.tertiary, marginBottom: '2px' }}>P90</div><div style={{ fontSize: '18px', fontWeight: 700, color: '#1B7A4A' }}>${(mc.p90 / 1e6).toFixed(1)}M</div></div>
          </div>

          {/* Interactive distribution bars */}
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: '3px', height: '120px', marginBottom: '4px' }}>
            {mc.distribution.map((d, i) => {
              const isHovered = hoveredBucket === i;
              const isMedian = i === 5;
              // Highlight confidence interval buckets
              const bucketPctStart = mc.distribution.slice(0, i).reduce((s, b) => s + b.pct, 0);
              const bucketPctEnd = bucketPctStart + d.pct;
              const inConfidence = bucketPctStart < confidenceRange[1] && bucketPctEnd > confidenceRange[0];
              return (
                <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '2px', height: '100%', justifyContent: 'flex-end', position: 'relative' }}
                  onMouseEnter={() => setHoveredBucket(i)} onMouseLeave={() => setHoveredBucket(null)}>
                  {isHovered && (
                    <div style={{ position: 'absolute', bottom: `${d.pct * 5 + 20}px`, background: T.color.navy900, color: T.color.ivory100, padding: '4px 8px', borderRadius: '4px', fontSize: '10px', whiteSpace: 'nowrap', zIndex: 5, boxShadow: T.shadow.md }}>
                      {d.bucket}: {d.pct}% probability
                      <br />≈ {Math.round(mc.iterations * d.pct / 100).toLocaleString()} iterations
                    </div>
                  )}
                  <span style={{ fontSize: '8px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>{d.pct}%</span>
                  <div style={{
                    width: '100%', height: `${d.pct * 5}px`, borderRadius: '2px 2px 0 0',
                    background: inConfidence
                      ? (isMedian ? rk.crimson : i < 3 ? 'rgba(194,48,48,0.5)' : i < 7 ? 'rgba(59,130,246,0.5)' : 'rgba(27,122,74,0.5)')
                      : (isMedian ? `${rk.crimson}60` : i < 3 ? 'rgba(194,48,48,0.15)' : i < 7 ? 'rgba(59,130,246,0.15)' : 'rgba(27,122,74,0.15)'),
                    transition: 'all 0.2s',
                    cursor: 'pointer',
                    transform: isHovered ? 'scaleY(1.05)' : 'scaleY(1)',
                    transformOrigin: 'bottom',
                  }} />
                </div>
              );
            })}
          </div>
          <div style={{ display: 'flex', gap: '3px' }}>
            {mc.distribution.map((d, i) => (
              <div key={i} style={{ flex: 1, textAlign: 'center', fontSize: '8px', color: T.color.text.tertiary }}>{d.bucket}</div>
            ))}
          </div>

          {/* Confidence interval selector */}
          <div style={{ marginTop: '12px', padding: '10px 12px', background: T.color.bg.secondary, borderRadius: '6px', border: `1px solid ${T.color.border.light}` }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '6px' }}>
              <span style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Confidence Interval</span>
              <span style={{ fontSize: '11px', fontFamily: T.font.mono, fontWeight: 600, color: rk.crimson }}>
                P{confidenceRange[0]}–P{confidenceRange[1]}: ${(confLow / 1e6).toFixed(1)}M – ${(confHigh / 1e6).toFixed(1)}M
              </span>
            </div>
            <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
              <span style={{ fontSize: '10px', color: T.color.text.tertiary }}>Low</span>
              <input type="range" min="5" max="45" step="5" value={confidenceRange[0]}
                onChange={e => setConfidenceRange([parseInt(e.target.value), Math.max(parseInt(e.target.value) + 10, confidenceRange[1])])}
                style={{ flex: 1, accentColor: rk.crimson }} />
              <span style={{ fontSize: '10px', fontFamily: T.font.mono, width: '28px' }}>P{confidenceRange[0]}</span>
              <span style={{ fontSize: '10px', color: T.color.text.tertiary }}>High</span>
              <input type="range" min="55" max="95" step="5" value={confidenceRange[1]}
                onChange={e => setConfidenceRange([Math.min(parseInt(e.target.value) - 10, confidenceRange[0]), parseInt(e.target.value)])}
                style={{ flex: 1, accentColor: rk.crimson }} />
              <span style={{ fontSize: '10px', fontFamily: T.font.mono, width: '28px' }}>P{confidenceRange[1]}</span>
            </div>
          </div>
        </div>
      </div>

      {/* Scenario cards */}
      {scenarios.map((sc, i) => (
        <div key={sc.id} style={rk.card}>
          <div style={{ ...rk.cardH, cursor: 'pointer' }} onClick={() => setExpanded(expanded === i ? null : i)}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
              <span style={{ fontFamily: T.font.mono, fontSize: '10px', color: T.color.text.tertiary }}>{sc.id}</span>
              <span style={{ fontWeight: 600 }}>{sc.name}</span>
              <span style={{ fontSize: '10px', padding: '2px 8px', borderRadius: '8px', background: `${probColor(sc.probability)}10`, color: probColor(sc.probability), fontWeight: 700 }}>{sc.probability}%</span>
            </div>
            <div style={{ display: 'flex', gap: '12px', fontSize: '11px' }}>
              <span style={{ fontWeight: 700, color: T.color.text.primary }}>{sc.damages}</span>
              <span style={{ color: T.color.text.tertiary }}>{sc.timeline}</span>
            </div>
          </div>
          {expanded === i && (
            <div style={{ padding: '12px 16px', fontSize: '12px' }}>
              <div style={{ color: T.color.text.secondary, lineHeight: 1.5, marginBottom: '12px' }}>{sc.outcome}</div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
                <div>
                  <div style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.primary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '6px' }}>Key Assumptions</div>
                  {sc.assumptions.map((a, j) => (
                    <div key={j} style={{ display: 'flex', gap: '6px', marginBottom: '2px', fontSize: '11px', color: T.color.text.secondary }}>
                      <span style={{ color: '#3B82F6' }}>•</span> {a}
                    </div>
                  ))}
                </div>
                <div>
                  <div style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.primary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '6px' }}>Key Risks</div>
                  {sc.risks.map((rId, j) => {
                    const risk = reg.find(r => r.id === rId);
                    return risk ? (
                      <div key={j} style={{ display: 'flex', gap: '6px', marginBottom: '3px', fontSize: '11px', alignItems: 'center' }}>
                        <span style={{ fontFamily: T.font.mono, fontSize: '9px', color: rk.crimson }}>{rId}</span>
                        <span style={{ color: T.color.text.secondary }}>{risk.name}</span>
                      </div>
                    ) : null;
                  })}
                </div>
              </div>
            </div>
          )}
        </div>
      ))}
    </div>
  );
}

// ── COMPLIANCE with countdown & heatmap (#12) ──
function RiskCompliance({ data }) {
  const [hovered, setHovered] = useState(null);
  const comp = data.compliance;
  const now = new Date('2026-04-20');

  const statusColor = { Active: '#1B7A4A', Upcoming: '#3B82F6', 'At Risk': '#C23030', Pending: '#D97706' };
  const atRisk = comp.filter(c => c.status === 'At Risk').length;
  const upcoming = comp.filter(c => c.status === 'Upcoming').length;

  // Build deadline heatmap for next 30 days
  const deadlineMap = {};
  comp.forEach(c => {
    if (c.dueDate) {
      const day = c.dueDate.slice(8, 10);
      if (!deadlineMap[c.dueDate]) deadlineMap[c.dueDate] = [];
      deadlineMap[c.dueDate].push(c);
    }
    if (c.nextVerification) {
      if (!deadlineMap[c.nextVerification]) deadlineMap[c.nextVerification] = [];
      deadlineMap[c.nextVerification].push({ ...c, isVerification: true });
    }
  });

  // Generate next 30 days
  const days30 = Array.from({ length: 30 }, (_, i) => {
    const d = new Date('2026-04-20');
    d.setDate(d.getDate() + i);
    return d.toISOString().slice(0, 10);
  });

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={rk.stat}><span style={rk.statLabel}>Total Obligations</span><span style={rk.statValue}>{comp.length}</span></div>
        <div style={rk.stat}><span style={rk.statLabel}>Active</span><span style={{ ...rk.statValue, color: '#1B7A4A' }}>{comp.filter(c => c.status === 'Active').length}</span></div>
        <div style={rk.stat}><span style={rk.statLabel}>At Risk</span><span style={{ ...rk.statValue, color: '#C23030' }}>{atRisk}</span></div>
        <div style={rk.stat}><span style={rk.statLabel}>Upcoming</span><span style={{ ...rk.statValue, color: '#3B82F6' }}>{upcoming}</span></div>
      </div>

      {/* Countdown widgets for urgent items */}
      {(() => {
        const urgent = comp.filter(c => c.dueDate && c.status !== 'Active').filter(c => {
          const d = Math.ceil((new Date(c.dueDate) - now) / 86400000);
          return d >= 0 && d <= 14;
        }).sort((a, b) => a.dueDate.localeCompare(b.dueDate));
        if (urgent.length === 0) return null;
        return (
          <div style={{ display: 'grid', gridTemplateColumns: `repeat(${Math.min(urgent.length, 4)}, 1fr)`, gap: '12px', marginBottom: '16px' }}>
            {urgent.map(c => {
              const daysLeft = Math.ceil((new Date(c.dueDate) - now) / 86400000);
              const urgencyColor = daysLeft <= 3 ? '#C23030' : daysLeft <= 7 ? '#D97706' : '#3B82F6';
              return (
                <div key={c.id} style={{ ...rk.card, marginBottom: 0, padding: '14px 16px', borderLeft: `3px solid ${urgencyColor}` }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                    <div>
                      <div style={{ fontSize: '12px', fontWeight: 600, color: T.color.text.primary }}>{c.obligation}</div>
                      <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginTop: '2px' }}>{c.matter} · {c.owner}</div>
                    </div>
                    <div style={{ textAlign: 'right' }}>
                      <div style={{ fontSize: '24px', fontWeight: 700, color: urgencyColor, fontFamily: T.font.mono, lineHeight: 1 }}>{daysLeft}</div>
                      <div style={{ fontSize: '9px', color: urgencyColor, fontWeight: 600 }}>days left</div>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        );
      })()}

      {/* Deadline heatmap - next 30 days */}
      <div style={rk.card}>
        <div style={rk.cardH}><span>Deadline Heatmap — Next 30 Days</span></div>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(15, 1fr)', gap: '3px' }}>
            {days30.map((day, i) => {
              const items = deadlineMap[day] || [];
              const hasAtRisk = items.some(c => c.status === 'At Risk');
              const hasItems = items.length > 0;
              const isToday = i === 0;
              const dayNum = day.slice(8, 10);
              const monthChange = i > 0 && day.slice(5, 7) !== days30[i - 1].slice(5, 7);
              return (
                <div key={day} style={{ position: 'relative' }}>
                  {monthChange && <div style={{ position: 'absolute', top: '-14px', left: 0, fontSize: '8px', color: T.color.text.tertiary, fontWeight: 600 }}>May</div>}
                  <div style={{
                    height: '32px', borderRadius: '3px', display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column',
                    background: hasAtRisk ? 'rgba(194,48,48,0.15)' : hasItems ? 'rgba(59,130,246,0.08)' : T.color.bg.secondary,
                    border: isToday ? `2px solid ${rk.crimson}` : `1px solid ${T.color.border.light}`,
                    cursor: hasItems ? 'pointer' : 'default',
                  }}>
                    <span style={{ fontSize: '9px', fontFamily: T.font.mono, color: hasAtRisk ? '#C23030' : hasItems ? '#3B82F6' : T.color.text.tertiary, fontWeight: hasItems ? 700 : 400 }}>{dayNum}</span>
                    {hasItems && <div style={{ display: 'flex', gap: '1px', marginTop: '1px' }}>
                      {items.slice(0, 3).map((_, j) => (
                        <div key={j} style={{ width: '3px', height: '3px', borderRadius: '50%', background: hasAtRisk ? '#C23030' : '#3B82F6' }} />
                      ))}
                    </div>}
                  </div>
                </div>
              );
            })}
          </div>
          <div style={{ display: 'flex', gap: '12px', marginTop: '8px', justifyContent: 'center' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}><div style={{ width: '8px', height: '8px', borderRadius: '2px', background: 'rgba(194,48,48,0.15)', border: '1px solid rgba(194,48,48,0.3)' }} /><span style={{ fontSize: '9px', color: T.color.text.tertiary }}>At Risk</span></div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}><div style={{ width: '8px', height: '8px', borderRadius: '2px', background: 'rgba(59,130,246,0.08)', border: '1px solid rgba(59,130,246,0.2)' }} /><span style={{ fontSize: '9px', color: T.color.text.tertiary }}>Scheduled</span></div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}><div style={{ width: '8px', height: '8px', borderRadius: '2px', border: `2px solid ${rk.crimson}` }} /><span style={{ fontSize: '9px', color: T.color.text.tertiary }}>Today</span></div>
          </div>
        </div>
      </div>

      {/* Table */}
      <div style={rk.card}>
        <div style={rk.cardH}><span>Compliance Tracker</span></div>
        <div style={{ display: 'grid', gridTemplateColumns: '60px 1fr 120px 70px 80px 80px 80px', 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: '8px' }}>
          <span>ID</span><span>Obligation</span><span>Matter</span><span>Status</span><span>Owner</span><span>Due</span><span>Next Check</span>
        </div>
        {comp.map((c, i) => {
          const dueDays = c.dueDate ? Math.ceil((new Date(c.dueDate) - now) / 86400000) : null;
          const isUrgent = dueDays !== null && dueDays <= 5 && dueDays >= 0;
          return (
            <div key={c.id} style={{ display: 'grid', gridTemplateColumns: '60px 1fr 120px 70px 80px 80px 80px', padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, alignItems: 'center', gap: '8px', fontSize: '12px', background: hovered === i ? T.color.bg.hover : 'transparent' }}
              onMouseEnter={() => setHovered(i)} onMouseLeave={() => setHovered(null)}>
              <span style={{ fontFamily: T.font.mono, fontSize: '10px', color: T.color.text.tertiary }}>{c.id}</span>
              <div>
                <div style={{ fontWeight: 500, color: T.color.text.primary }}>{c.obligation}</div>
                <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginTop: '1px' }}>{c.notes}</div>
              </div>
              <span style={{ fontSize: '10px', color: T.color.text.secondary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.matter}</span>
              <span style={{ fontSize: '9px', padding: '2px 6px', borderRadius: '8px', background: `${statusColor[c.status]}10`, color: statusColor[c.status], fontWeight: 600 }}>{c.status}</span>
              <span style={{ fontSize: '11px', color: T.color.text.secondary }}>{c.owner}</span>
              <span style={{ fontSize: '10px', fontWeight: isUrgent ? 600 : 400, color: isUrgent ? '#C23030' : c.dueDate ? T.color.text.secondary : T.color.text.tertiary }}>{c.dueDate ? c.dueDate.slice(5) : '—'}</span>
              <span style={{ fontSize: '10px', color: T.color.text.tertiary }}>{c.nextVerification ? c.nextVerification.slice(5) : '—'}</span>
            </div>
          );
        })}
      </div>

      {/* AI compliance 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 Compliance Alert</div>
          Insurance carrier supplemental notice (CO-06) due in 5 days — high risk of coverage denial if missed. Q1 client reports (CO-07) due April 30 across all matters. Conflict check for Whitfield referral (CO-08) should be prioritized before engagement letter deadline.
        </div>
      </div>
    </div>
  );
}

// ── RISK ANALYTICS ──
function RiskAnalytics({ data }) {
  const reg = data.register;
  const mits = data.mitigations;

  const matterExposure = {};
  reg.forEach(r => {
    if (!matterExposure[r.matter]) matterExposure[r.matter] = { count: 0, totalScore: 0, maxScore: 0 };
    matterExposure[r.matter].count++;
    matterExposure[r.matter].totalScore += r.score;
    matterExposure[r.matter].maxScore = Math.max(matterExposure[r.matter].maxScore, r.score);
  });

  const ownerLoad = {};
  reg.forEach(r => {
    if (!ownerLoad[r.owner]) ownerLoad[r.owner] = { risks: 0, criticalRisks: 0, mitigations: 0 };
    ownerLoad[r.owner].risks++;
    if (r.score >= 15) ownerLoad[r.owner].criticalRisks++;
  });
  mits.forEach(m => {
    if (!ownerLoad[m.assignee]) ownerLoad[m.assignee] = { risks: 0, criticalRisks: 0, mitigations: 0 };
    ownerLoad[m.assignee].mitigations++;
  });

  const avgReduction = (reg.reduce((s, r) => s + (r.score - r.residualScore), 0) / reg.length).toFixed(1);
  const mitigationRate = Math.round((mits.filter(m => m.progress > 0).length / mits.length) * 100);

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={rk.stat}><span style={rk.statLabel}>Portfolio Score</span><span style={rk.statValue}>{reg.reduce((s, r) => s + r.score, 0)}</span></div>
        <div style={rk.stat}><span style={rk.statLabel}>Residual Score</span><span style={{ ...rk.statValue, color: '#1B7A4A' }}>{reg.reduce((s, r) => s + r.residualScore, 0)}</span></div>
        <div style={rk.stat}><span style={rk.statLabel}>Avg Reduction</span><span style={{ ...rk.statValue, color: '#1B7A4A' }}>-{avgReduction}</span></div>
        <div style={rk.stat}><span style={rk.statLabel}>Mitigation Rate</span><span style={{ ...rk.statValue, color: rk.crimson }}>{mitigationRate}%</span></div>
        <div style={rk.stat}><span style={rk.statLabel}>Risk Velocity</span><span style={{ ...rk.statValue, color: '#C23030' }}>+{reg.filter(r => r.trend === 'rising').length}</span></div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '16px' }}>
        <div style={rk.card}>
          <div style={rk.cardH}><span>Exposure by Matter</span></div>
          {Object.entries(matterExposure).sort((a, b) => b[1].totalScore - a[1].totalScore).map(([matter, exp]) => (
            <div key={matter} style={{ padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', alignItems: 'center', gap: '10px', fontSize: '12px' }}>
              <span style={{ flex: 1, fontWeight: 500, color: T.color.text.primary }}>{matter}</span>
              <span style={{ fontFamily: T.font.mono, fontSize: '10px', color: T.color.text.tertiary }}>{exp.count} risks</span>
              <div style={{ display: 'flex', alignItems: 'center', gap: '4px', width: '80px' }}>
                <div style={{ flex: 1, ...rk.barTrack }}>
                  <div style={{ ...rk.barFill, width: `${(exp.totalScore / 50) * 100}%`, background: scoreColor(exp.maxScore) }} />
                </div>
                <span style={{ fontFamily: T.font.mono, fontSize: '10px', fontWeight: 700, color: scoreColor(exp.maxScore) }}>{exp.totalScore}</span>
              </div>
            </div>
          ))}
        </div>

        <div style={rk.card}>
          <div style={rk.cardH}><span>Risk Owner Workload</span></div>
          {Object.entries(ownerLoad).map(([owner, load]) => (
            <div key={owner} style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}` }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
                <span style={{ fontWeight: 600, fontSize: '12px', color: T.color.text.primary }}>{owner}</span>
                <div style={{ display: 'flex', gap: '12px', fontSize: '10px' }}>
                  <span style={{ color: T.color.text.tertiary }}>{load.risks} risks</span>
                  <span style={{ color: '#C23030' }}>{load.criticalRisks} critical</span>
                  <span style={{ color: rk.crimson }}>{load.mitigations} actions</span>
                </div>
              </div>
              <div style={{ display: 'flex', gap: '4px' }}>
                <div style={{ flex: load.risks, height: '6px', borderRadius: '3px', background: '#3B82F6', opacity: 0.4 }} />
                <div style={{ flex: Math.max(load.criticalRisks, 0.3), height: '6px', borderRadius: '3px', background: '#C23030', opacity: 0.6 }} />
                <div style={{ flex: Math.max(load.mitigations, 0.3), height: '6px', borderRadius: '3px', background: rk.crimson, opacity: 0.4 }} />
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Inherent vs Residual */}
      <div style={rk.card}>
        <div style={rk.cardH}><span>Inherent vs. Residual Risk — All Items</span></div>
        {[...reg].sort((a, b) => b.score - a.score).map((r) => (
          <div key={r.id} style={{ padding: '6px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', alignItems: 'center', gap: '10px', fontSize: '11px' }}>
            <span style={{ fontFamily: T.font.mono, fontSize: '9px', color: T.color.text.tertiary, width: '52px' }}>{r.id}</span>
            <span style={{ width: '200px', color: T.color.text.primary, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.name}</span>
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: '4px', position: 'relative', height: '12px' }}>
              <div style={{ position: 'absolute', left: 0, top: 0, width: `${(r.score / 25) * 100}%`, height: '5px', borderRadius: '3px', background: `${scoreColor(r.score)}40` }} />
              <div style={{ position: 'absolute', left: 0, top: '7px', width: `${(r.residualScore / 25) * 100}%`, height: '5px', borderRadius: '3px', background: scoreColor(r.residualScore) }} />
            </div>
            <span style={{ fontFamily: T.font.mono, fontSize: '10px', fontWeight: 700, color: scoreColor(r.score), minWidth: '18px' }}>{r.score}</span>
            <span style={{ color: T.color.text.tertiary, fontSize: '10px' }}>→</span>
            <span style={{ fontFamily: T.font.mono, fontSize: '10px', fontWeight: 700, color: scoreColor(r.residualScore), minWidth: '18px' }}>{r.residualScore}</span>
          </div>
        ))}
        <div style={{ padding: '8px 16px', display: 'flex', gap: '16px', justifyContent: 'center', borderTop: `1px solid ${T.color.border.light}` }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}><div style={{ width: '12px', height: '5px', borderRadius: '3px', background: 'rgba(194,48,48,0.25)' }} /><span style={{ fontSize: '10px', color: T.color.text.tertiary }}>Inherent</span></div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}><div style={{ width: '12px', height: '5px', borderRadius: '3px', background: '#C23030' }} /><span style={{ fontSize: '10px', color: T.color.text.tertiary }}>Residual</span></div>
        </div>
      </div>
    </div>
  );
}

// ── AUDIT LOG with filters + diff view (#13) ──
function RiskAuditLog({ data }) {
  const [userFilter, setUserFilter] = useState('All');
  const [riskFilter, setRiskFilter] = useState('');
  const [dateFrom, setDateFrom] = useState('');
  const log = data.auditLog;

  const users = ['All', ...new Set(log.map(l => l.user))];

  const filtered = useMemo(() => {
    let items = log;
    if (userFilter !== 'All') items = items.filter(l => l.user === userFilter);
    if (riskFilter) {
      const q = riskFilter.toLowerCase();
      items = items.filter(l => l.action.toLowerCase().includes(q) || l.detail.toLowerCase().includes(q));
    }
    if (dateFrom) items = items.filter(l => l.date >= dateFrom);
    return items;
  }, [userFilter, riskFilter, dateFrom, log]);

  // Parse score diffs from detail strings
  const parseDiff = (detail) => {
    const match = detail.match(/(\d+)\s*→\s*(\d+)/);
    if (match) return { from: parseInt(match[1]), to: parseInt(match[2]) };
    return null;
  };

  return (
    <div>
      {/* Filters */}
      <div style={{ display: 'flex', gap: '8px', marginBottom: '16px', 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: '200px' }}
          placeholder="Search by risk ID or text..." value={riskFilter} onChange={e => setRiskFilter(e.target.value)} />
        {users.map(u => (
          <button key={u} style={{ ...rk.filterBtn, ...(userFilter === u ? rk.filterBtnActive : {}) }} onClick={() => setUserFilter(u)}>{u}</button>
        ))}
        <div style={{ flex: 1 }} />
        <label style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '11px', color: T.color.text.tertiary }}>
          From:
          <input type="date" style={{ ...rk.filterBtn, padding: '3px 8px', fontSize: '10px' }} value={dateFrom} onChange={e => setDateFrom(e.target.value)} />
        </label>
        <span style={{ fontSize: '11px', color: T.color.text.tertiary }}>{filtered.length} of {log.length} entries</span>
      </div>

      <div style={rk.card}>
        <div style={rk.cardH}><span>Risk Assessment Audit Trail</span></div>
        {filtered.map((l, i) => {
          const diff = parseDiff(l.detail);
          return (
            <div key={i} style={{ padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', gap: '12px', alignItems: 'flex-start', fontSize: '12px' }}>
              <span style={{ fontFamily: T.font.mono, fontSize: '10px', color: T.color.text.tertiary, minWidth: '76px' }}>{l.date}</span>
              <div style={{ width: '80px' }}>
                <span style={{ fontSize: '11px', fontWeight: 600, color: T.color.text.primary }}>{l.user}</span>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 500, color: T.color.text.primary }}>{l.action}</div>
                <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginTop: '1px' }}>{l.detail}</div>
              </div>
              {/* Diff visualization */}
              {diff && (
                <div style={{ display: 'flex', alignItems: 'center', gap: '4px', flexShrink: 0 }}>
                  <span style={{ fontFamily: T.font.mono, fontSize: '12px', fontWeight: 700, color: scoreColor(diff.from) }}>{diff.from}</span>
                  <span style={{ color: T.color.text.tertiary }}>→</span>
                  <span style={{ fontFamily: T.font.mono, fontSize: '12px', fontWeight: 700, color: scoreColor(diff.to) }}>{diff.to}</span>
                  <span style={{ fontSize: '10px', fontWeight: 600, color: diff.to > diff.from ? '#C23030' : diff.to < diff.from ? '#1B7A4A' : T.color.text.tertiary }}>
                    {diff.to > diff.from ? `+${diff.to - diff.from}` : diff.to < diff.from ? `${diff.to - diff.from}` : '='}
                  </span>
                </div>
              )}
            </div>
          );
        })}
        {filtered.length === 0 && (
          <div style={{ padding: '24px', textAlign: 'center', color: T.color.text.tertiary, fontSize: '12px' }}>No matching audit entries.</div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { RiskMitigations, RiskScenarios, RiskCompliance, RiskAnalytics, RiskAuditLog });
