// RISK OPPORTUNITY COMPONENTS — 25 modules + 5 group hubs
(function () {
  const { useState, useMemo } = React;
  const T = window.ArbiterTokens;
  const rk = window.rk;

  const fmtMoney = (n) => n == null ? '—' : '$' + (n >= 1e6 ? (n / 1e6).toFixed(1) + 'M' : n >= 1e3 ? (n / 1e3).toFixed(0) + 'K' : String(n));
  const pct = (a, b) => b === 0 ? 0 : Math.round((a / b) * 100);
  const statusColor = (s) => {
    const m = { within: '#1B7A4A', 'at-limit': '#D97706', breach: '#C23030', effective: '#1B7A4A', partial: '#D97706', ineffective: '#C23030', active: '#1B7A4A', tracking: '#3B82F6', analysis: '#D97706', complied: '#6E7D9E', closed: '#6E7D9E' };
    return m[s] || T.color.text.secondary;
  };

  // Shared sub-tabs segmented control
  function RkSubTabs({ tabs, active, onChange }) {
    return (
      <div style={{ display: 'flex', gap: '0', borderBottom: `1px solid ${T.color.border.light}`, marginBottom: '16px' }}>
        {tabs.map(t => {
          const isActive = active === t.id;
          return (
            <button key={t.id} onClick={() => onChange(t.id)} style={{
              padding: '8px 14px', border: 'none', background: 'none', cursor: 'pointer',
              fontSize: '12px', fontWeight: isActive ? 600 : 500,
              color: isActive ? rk.crimson : T.color.text.tertiary,
              borderBottom: `2px solid ${isActive ? rk.crimson : 'transparent'}`,
              marginBottom: '-1px', fontFamily: T.font.family,
            }}>
              {t.label}
              {typeof t.count === 'number' && <span style={{ marginLeft: '6px', fontFamily: T.font.mono, fontSize: '10px', color: T.color.text.tertiary }}>{t.count}</span>}
            </button>
          );
        })}
      </div>
    );
  }
  window.RkSubTabs = RkSubTabs;

  // Card primitive
  const Card = ({ title, right, children }) => (
    <div style={rk.card}>
      <div style={rk.cardH}><span>{title}</span>{right}</div>
      <div style={{ padding: '12px 16px' }}>{children}</div>
    </div>
  );

  const TH = ({ children, width }) => (
    <th style={{ textAlign: 'left', padding: '6px 10px', fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em', borderBottom: `1px solid ${T.color.border.light}`, width }}>{children}</th>
  );
  const TD = ({ children, mono, align, color }) => (
    <td style={{ padding: '8px 10px', fontSize: '12px', color: color || T.color.text.primary, borderBottom: `1px solid ${T.color.border.light}`, fontFamily: mono ? T.font.mono : T.font.family, textAlign: align || 'left' }}>{children}</td>
  );

  const Pill = ({ children, color }) => (
    <span style={{ display: 'inline-flex', padding: '2px 8px', borderRadius: '10px', fontSize: '10px', fontWeight: 600, background: (color || T.color.text.tertiary) + '22', color: color || T.color.text.secondary }}>{children}</span>
  );

  // ═══════════════════════════════════════════════════════════════
  // 1. RISK APPETITE THRESHOLDS
  // ═══════════════════════════════════════════════════════════════
  function RkAppetite() {
    const s = window.useRiskStore(['risk.updated', 'appetite.checked']);
    return (
      <Card title="Risk Appetite · Tolerance Thresholds">
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr><TH>Category</TH><TH>Target</TH><TH>Tolerance</TH><TH>Current</TH><TH>Max Loss</TH><TH>Status</TH></tr></thead>
          <tbody>
            {s.appetiteThresholds.map(a => (
              <tr key={a.category}>
                <TD>{a.category}</TD>
                <TD mono>{a.target}</TD>
                <TD mono>{a.tolerance}</TD>
                <TD mono color={a.currentAvg > a.tolerance ? '#C23030' : T.color.text.primary}>{a.currentAvg}</TD>
                <TD mono>{fmtMoney(a.maxLoss)}</TD>
                <TD><Pill color={statusColor(a.status)}>{a.status}</Pill></TD>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 2. CONTROL EFFECTIVENESS (test results)
  // ═══════════════════════════════════════════════════════════════
  function RkControls() {
    const s = window.useRiskStore(['control.tested']);
    return (
      <Card title="Control Effectiveness · Test Evidence">
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr><TH>ID</TH><TH>Control</TH><TH>Risk</TH><TH>Last</TH><TH>Result</TH><TH>Owner</TH></tr></thead>
          <tbody>
            {s.controlTests.map(c => (
              <tr key={c.id}>
                <TD mono>{c.id}</TD>
                <TD>{c.control}</TD>
                <TD mono>{c.riskId}</TD>
                <TD mono>{c.lastTested}</TD>
                <TD><Pill color={statusColor(c.result)}>{c.result}</Pill></TD>
                <TD>{c.owner}</TD>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 3. TREATMENT DECISIONS LOG
  // ═══════════════════════════════════════════════════════════════
  function RkTreatments() {
    const s = window.useRiskStore(['treatment.recorded']);
    const strategyColor = (s) => ({ mitigate: '#3B82F6', transfer: '#7C3AED', accept: '#6E7D9E', avoid: '#C23030' }[s] || T.color.text.secondary);
    return (
      <Card title="Treatment Decision Log (4T · mitigate/transfer/accept/avoid)">
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr><TH>ID</TH><TH>Risk</TH><TH>Strategy</TH><TH>Date</TH><TH>Cost</TH><TH>Residual</TH><TH>Rationale</TH></tr></thead>
          <tbody>
            {s.treatmentDecisions.map(t => (
              <tr key={t.id}>
                <TD mono>{t.id}</TD>
                <TD mono>{t.riskId}</TD>
                <TD><Pill color={strategyColor(t.strategy)}>{t.strategy}</Pill></TD>
                <TD mono>{t.date}</TD>
                <TD mono>{fmtMoney(t.cost)}</TD>
                <TD mono>{t.residualScore}</TD>
                <TD>{t.rationale}</TD>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 4. INSURANCE COVERAGE MAPPER
  // ═══════════════════════════════════════════════════════════════
  function RkInsurance() {
    const s = window.useRiskStore(['insurance.noticed']);
    const totalLimit = s.insurancePolicies.reduce((sum, p) => sum + (p.limit || 0), 0);
    return (
      <Card title={`Insurance Coverage · Total Limits: ${fmtMoney(totalLimit)}`}>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr><TH>Carrier</TH><TH>Type</TH><TH>Limit</TH><TH>Retention</TH><TH>Premium</TH><TH>Expires</TH><TH>Risks</TH></tr></thead>
          <tbody>
            {s.insurancePolicies.map(p => (
              <tr key={p.id}>
                <TD>{p.carrier}</TD>
                <TD>{p.type}</TD>
                <TD mono>{fmtMoney(p.limit)}</TD>
                <TD mono>{fmtMoney(p.retention)}</TD>
                <TD mono>{fmtMoney(p.annualPremium)}</TD>
                <TD mono>{p.expires}</TD>
                <TD mono style={{ fontSize: '10px' }}>{(p.coveredRisks || []).join(', ') || '—'}</TD>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 5. KRI DASHBOARD
  // ═══════════════════════════════════════════════════════════════
  function RkKRI() {
    const s = window.useRiskStore(['kri.checked', 'risk.updated']);
    return (
      <Card title="Key Risk Indicators · Threshold Monitoring">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: '10px' }}>
          {s.kriIndicators.map(k => {
            const breached = k.current > k.threshold;
            return (
              <div key={k.id} style={{ padding: '12px', border: `1px solid ${breached ? '#C2303040' : T.color.border.light}`, borderRadius: '6px', background: breached ? 'rgba(194,48,48,0.04)' : T.color.bg.card }}>
                <div style={{ fontSize: '11px', color: T.color.text.tertiary, fontWeight: 600, textTransform: 'uppercase' }}>{k.name}</div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: '6px', marginTop: '4px' }}>
                  <span style={{ fontSize: '22px', fontWeight: 700, color: breached ? '#C23030' : T.color.text.primary, fontFamily: T.font.mono }}>{k.current}</span>
                  <span style={{ fontSize: '11px', color: T.color.text.tertiary, fontFamily: T.font.mono }}>/ {k.threshold}</span>
                  <span style={{ fontSize: '11px', color: k.trend === 'rising' ? '#C23030' : k.trend === 'declining' ? '#1B7A4A' : '#6E7D9E', marginLeft: 'auto' }}>{k.trend === 'rising' ? '↑' : k.trend === 'declining' ? '↓' : '→'}</span>
                </div>
                <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginTop: '4px' }}>{k.window}{k.related.length ? ` · ${k.related.join(', ')}` : ''}</div>
              </div>
            );
          })}
        </div>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 6. EARLY WARNING TRIGGER RULES
  // ═══════════════════════════════════════════════════════════════
  function RkTriggers() {
    const s = window.useRiskStore(['trigger.fired']);
    return (
      <Card title="Early Warning Trigger Rules">
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr><TH>ID</TH><TH>Name</TH><TH>Condition</TH><TH>Action</TH><TH>Enabled</TH><TH>Fired</TH></tr></thead>
          <tbody>
            {s.triggerRules.map(t => (
              <tr key={t.id}>
                <TD mono>{t.id}</TD>
                <TD>{t.name}</TD>
                <TD mono style={{ fontSize: '10px' }}>{t.condition}</TD>
                <TD>{t.action}</TD>
                <TD><Pill color={t.enabled ? '#1B7A4A' : '#6E7D9E'}>{t.enabled ? 'on' : 'off'}</Pill></TD>
                <TD mono>{t.triggered}</TD>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 7. REGULATORY HORIZON
  // ═══════════════════════════════════════════════════════════════
  function RkRegWatch() {
    const s = window.useRiskStore();
    return (
      <Card title="Regulatory Horizon · Rules Ahead">
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr><TH>Rule</TH><TH>Effective</TH><TH>Jurisdiction</TH><TH>Impact</TH><TH>Area</TH><TH>Status</TH></tr></thead>
          <tbody>
            {s.regulatoryWatch.map(r => (
              <tr key={r.id}>
                <TD>{r.rule}</TD>
                <TD mono>{r.effective}</TD>
                <TD>{r.jurisdiction}</TD>
                <TD><Pill color={r.impact === 'high' ? '#C23030' : r.impact === 'medium' ? '#D97706' : '#6E7D9E'}>{r.impact}</Pill></TD>
                <TD>{r.area}</TD>
                <TD><Pill color={statusColor(r.status)}>{r.status}</Pill></TD>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 8. INCIDENTS / NEAR-MISS
  // ═══════════════════════════════════════════════════════════════
  function RkIncidents() {
    const s = window.useRiskStore(['incident.logged']);
    return (
      <Card title="Incidents & Near-Miss Log">
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr><TH>ID</TH><TH>Date</TH><TH>Type</TH><TH>Severity</TH><TH>Description</TH><TH>Lessons</TH></tr></thead>
          <tbody>
            {s.incidents.map(i => (
              <tr key={i.id}>
                <TD mono>{i.id}</TD>
                <TD mono>{i.date}</TD>
                <TD><Pill color={i.type === 'incident' ? '#C23030' : '#D97706'}>{i.type}</Pill></TD>
                <TD><Pill color={i.severity === 'high' ? '#C23030' : i.severity === 'medium' ? '#D97706' : '#6E7D9E'}>{i.severity}</Pill></TD>
                <TD>{i.description}</TD>
                <TD style={{ fontSize: '10px', fontStyle: 'italic' }}>{i.lessons}</TD>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 9. CYBER REGISTER
  // ═══════════════════════════════════════════════════════════════
  function RkCyber() {
    const s = window.useRiskStore();
    return (
      <Card title="Cyber Asset Register · Breach Exposure">
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr><TH>Asset</TH><TH>Classification</TH><TH>Vendor</TH><TH>Last Pen-Test</TH><TH>Exposure</TH><TH>Score</TH></tr></thead>
          <tbody>
            {s.cyberRegister.map(c => (
              <tr key={c.id}>
                <TD>{c.asset}</TD>
                <TD><Pill color={c.classification === 'AEO' ? '#C23030' : c.classification === 'Confidential' ? '#D97706' : '#6E7D9E'}>{c.classification}</Pill></TD>
                <TD>{c.vendor}</TD>
                <TD mono>{c.lastPenTest}</TD>
                <TD><Pill color={c.exposure === 'high' ? '#C23030' : c.exposure === 'medium' ? '#D97706' : '#1B7A4A'}>{c.exposure}</Pill></TD>
                <TD mono>{c.breachScore}</TD>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 10. PORTFOLIO / CLIENT AGGREGATION
  // ═══════════════════════════════════════════════════════════════
  function RkPortfolio() {
    const s = window.useRiskStore(['risk.updated']);
    return (
      <Card title="Client Portfolio · Aggregate Risk Exposure">
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr><TH>Client</TH><TH>Matters</TH><TH>Active Risks</TH><TH>Agg Score</TH><TH>Expected Loss</TH><TH>Concentration</TH></tr></thead>
          <tbody>
            {s.clientPortfolios.map(c => (
              <tr key={c.id}>
                <TD>{c.client}</TD>
                <TD mono>{c.matters}</TD>
                <TD mono>{c.activeRisks}</TD>
                <TD mono color={c.aggregateScore > 60 ? '#C23030' : T.color.text.primary}>{c.aggregateScore}</TD>
                <TD mono>{fmtMoney(c.expectedLoss)}</TD>
                <TD><Pill color={c.concentration === 'high' ? '#C23030' : c.concentration === 'medium' ? '#D97706' : '#1B7A4A'}>{c.concentration}</Pill></TD>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 11. RISK COMMITTEE
  // ═══════════════════════════════════════════════════════════════
  function RkCommittee() {
    const s = window.useRiskStore(['committee.closed']);
    return (
      <Card title="Risk Committee · Meeting Cadence">
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr><TH>Date</TH><TH>Chair</TH><TH>Attendees</TH><TH>Agenda</TH><TH>Decisions</TH></tr></thead>
          <tbody>
            {s.riskCommittee.map(m => (
              <tr key={m.id}>
                <TD mono>{m.date}</TD>
                <TD>{m.chair}</TD>
                <TD style={{ fontSize: '10px' }}>{m.attendees.join(', ')}</TD>
                <TD style={{ fontSize: '10px' }}>{m.agenda.join(' · ')}</TD>
                <TD style={{ fontSize: '10px', fontStyle: m.decisions.length ? 'normal' : 'italic', color: m.decisions.length ? T.color.text.primary : T.color.text.tertiary }}>{m.decisions.length ? m.decisions.join('; ') : 'pending'}</TD>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 12. BOARD / CLIENT REPORTER
  // ═══════════════════════════════════════════════════════════════
  function RkReporter() {
    const s = window.useRiskStore();
    return (
      <Card title="Report Templates · Audience & Cadence">
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr><TH>Template</TH><TH>Audience</TH><TH>Cadence</TH><TH>Sections</TH><TH>Last Used</TH></tr></thead>
          <tbody>
            {s.reportTemplates.map(r => (
              <tr key={r.id}>
                <TD>{r.name}</TD>
                <TD><Pill color="#3B82F6">{r.audience}</Pill></TD>
                <TD>{r.cadence}</TD>
                <TD style={{ fontSize: '10px' }}>{r.sections.join(' · ')}</TD>
                <TD mono>{r.lastUsed}</TD>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 13. ERM MATURITY
  // ═══════════════════════════════════════════════════════════════
  function RkMaturity() {
    const s = window.useRiskStore();
    return (
      <Card title="ERM Maturity · COSO / ISO 31000 Gap Analysis">
        <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
          {s.ermMaturity.map(d => {
            const gap = d.target - d.current;
            return (
              <div key={d.dimension} style={{ padding: '10px 12px', background: T.color.bg.secondary, borderRadius: '6px', border: `1px solid ${T.color.border.light}` }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                  <div style={{ flex: 1, fontSize: '12px', fontWeight: 600 }}>{d.dimension}</div>
                  <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>{d.framework}</div>
                  <div style={{ display: 'flex', gap: '3px' }}>
                    {[1, 2, 3, 4, 5].map(n => (
                      <div key={n} style={{ width: '20px', height: '8px', borderRadius: '2px', background: n <= d.current ? rk.crimson : n <= d.target ? '#D9770640' : T.color.border.light }} />
                    ))}
                  </div>
                  <div style={{ fontSize: '11px', fontFamily: T.font.mono, color: gap > 0 ? '#D97706' : '#1B7A4A', width: '40px', textAlign: 'right' }}>{d.current}/{d.target}</div>
                </div>
                {d.gap && <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginTop: '4px', fontStyle: 'italic' }}>{d.gap}</div>}
              </div>
            );
          })}
        </div>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 14. ETHICAL WALLS
  // ═══════════════════════════════════════════════════════════════
  function RkEthicalWalls() {
    const s = window.useRiskStore();
    return (
      <Card title="Ethical Walls · Conflict Screening">
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr><TH>Name</TH><TH>Matter</TH><TH>Screened</TH><TH>Reason</TH><TH>Status</TH><TH>Last Audit</TH></tr></thead>
          <tbody>
            {s.ethicalWalls.map(w => (
              <tr key={w.id}>
                <TD>{w.name}</TD>
                <TD>{w.matter}</TD>
                <TD mono>{w.screenedAttorneys.join(', ')}</TD>
                <TD>{w.reason}</TD>
                <TD><Pill color={statusColor(w.status)}>{w.status}</Pill></TD>
                <TD mono>{w.lastAudit}</TD>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 15. VENDOR / PANEL MANAGEMENT
  // ═══════════════════════════════════════════════════════════════
  function RkVendors() {
    const s = window.useRiskStore();
    return (
      <Card title="Vendor & Panel · Third-Party Risk">
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr><TH>Name</TH><TH>Type</TH><TH>Specialty</TH><TH>Rating</TH><TH>Engagements</TH><TH>Flags</TH></tr></thead>
          <tbody>
            {s.vendorPanel.map(v => (
              <tr key={v.id}>
                <TD>{v.name}</TD>
                <TD>{v.type}</TD>
                <TD>{v.specialty}</TD>
                <TD mono>{v.rating}</TD>
                <TD mono>{v.engagements}</TD>
                <TD style={{ fontSize: '10px', color: v.risks.length ? '#D97706' : T.color.text.tertiary }}>{v.risks.join(', ') || '—'}</TD>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 16. CLIENT RATING / AML
  // ═══════════════════════════════════════════════════════════════
  function RkClientRatings() {
    const s = window.useRiskStore();
    return (
      <Card title="Client Risk Ratings · Intake & AML">
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr><TH>Client</TH><TH>Payment</TH><TH>Disputes</TH><TH>Concentration</TH><TH>AML</TH><TH>Composite</TH><TH>Flags</TH></tr></thead>
          <tbody>
            {s.clientRatings.map(c => (
              <tr key={c.id}>
                <TD>{c.client}</TD>
                <TD mono align="center">{c.payment}</TD>
                <TD mono align="center">{c.disputes}</TD>
                <TD mono align="center">{c.concentration}</TD>
                <TD mono align="center">{c.aml}</TD>
                <TD mono align="center"><Pill color={c.composite.startsWith('A') ? '#1B7A4A' : c.composite.startsWith('B') ? '#D97706' : '#6E7D9E'}>{c.composite}</Pill></TD>
                <TD style={{ fontSize: '10px' }}>{c.flags.join(', ') || '—'}</TD>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 17. ATTORNEY PROFESSIONAL RISK
  // ═══════════════════════════════════════════════════════════════
  function RkAttorneyProfiles() {
    const s = window.useRiskStore();
    return (
      <Card title="Attorney Professional Risk Profile">
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr><TH>Name</TH><TH>Role</TH><TH>Util %</TH><TH>Real %</TH><TH>Win %</TH><TH>CLE</TH><TH>Cyber Tng</TH></tr></thead>
          <tbody>
            {s.attorneyProfiles.map(a => (
              <tr key={a.id}>
                <TD>{a.name}</TD>
                <TD>{a.role}</TD>
                <TD mono color={a.utilization > 100 ? '#C23030' : a.utilization > 95 ? '#D97706' : T.color.text.primary}>{a.utilization}</TD>
                <TD mono>{a.realization}</TD>
                <TD mono>{a.winRate ?? '—'}</TD>
                <TD><Pill color={a.cleSuffiencies ? '#1B7A4A' : '#C23030'}>{a.cleSuffiencies ? 'current' : 'lapsed'}</Pill></TD>
                <TD mono>{a.cyberTraining}</TD>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 18. SETTLEMENT DECISION TREE
  // ═══════════════════════════════════════════════════════════════
  function RkSettlementTree() {
    const s = window.useRiskStore();
    const tree = s.settlementTrees[0];
    if (!tree) return <Card title="Settlement Decision Tree"><div style={{ fontSize: '12px', color: T.color.text.tertiary }}>No trees configured.</div></Card>;
    return (
      <Card title={`Settlement Decision Tree · ${tree.matter}`}>
        <div style={{ padding: '10px 12px', background: T.color.bg.secondary, borderRadius: '6px', marginBottom: '12px', border: `1px solid ${T.color.border.light}` }}>
          <div style={{ fontSize: '11px', color: T.color.text.tertiary, fontWeight: 600, textTransform: 'uppercase' }}>Expected Value (reject)</div>
          <div style={{ fontSize: '22px', fontWeight: 700, fontFamily: T.font.mono, color: rk.crimson }}>{fmtMoney(tree.ev)}</div>
          <div style={{ fontSize: '11px', color: T.color.text.secondary, marginTop: '4px' }}>Recommendation: <strong style={{ color: rk.crimson }}>{tree.recommendation}</strong></div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr><TH>Branch</TH><TH>Label</TH><TH>Value</TH><TH>Probability</TH><TH>EV</TH></tr></thead>
          <tbody>
            {tree.nodes.filter(n => n.type === 'outcome').map(n => (
              <tr key={n.id}>
                <TD mono>{n.parent}</TD>
                <TD>{n.label || n.choice}</TD>
                <TD mono>{fmtMoney(n.value)}</TD>
                <TD mono>{(n.probability * 100).toFixed(0)}%</TD>
                <TD mono color={n.ev >= 0 ? '#1B7A4A' : '#C23030'}>{fmtMoney(n.ev)}</TD>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 19. TORNADO CHART (sensitivity)
  // ═══════════════════════════════════════════════════════════════
  function RkTornado() {
    const s = window.useRiskStore();
    const sorted = s.sensitivityFactors.slice().sort((a, b) => b.range - a.range);
    const max = Math.max(...sorted.map(f => f.range)) || 1;
    return (
      <Card title="Sensitivity Tornado · Factors Sorted by Impact Range">
        <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
          {sorted.map(f => {
            const width = (f.range / max) * 100;
            return (
              <div key={f.id} style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <div style={{ width: '180px', fontSize: '12px' }}>{f.factor}</div>
                <div style={{ flex: 1, height: '20px', background: T.color.bg.secondary, borderRadius: '3px', position: 'relative' }}>
                  <div style={{ height: '100%', width: width + '%', background: `linear-gradient(90deg, ${rk.crimson}, ${rk.crimsonLight})`, borderRadius: '3px' }} />
                </div>
                <div style={{ width: '140px', fontSize: '10px', fontFamily: T.font.mono, textAlign: 'right', color: T.color.text.tertiary }}>{fmtMoney(f.low)} – {fmtMoney(f.high)}</div>
              </div>
            );
          })}
        </div>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 20. VaR / CVaR
  // ═══════════════════════════════════════════════════════════════
  function RkVaR() {
    const s = window.useRiskStore();
    const v = s.varResults || {};
    return (
      <Card title={`Value-at-Risk · ${v.confidence ? (v.confidence * 100).toFixed(0) : '95'}% · ${v.horizon || '12 months'}`}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: '12px' }}>
          {[
            { label: 'VaR 95%',  v: v.var95 },
            { label: 'CVaR 95%', v: v.cvar95 },
            { label: 'Expected Loss', v: v.ead },
          ].map(item => (
            <div key={item.label} style={rk.stat}>
              <div style={rk.statLabel}>{item.label}</div>
              <div style={{ ...rk.statValue, color: rk.crimson }}>{fmtMoney(item.v)}</div>
            </div>
          ))}
        </div>
        <div style={{ fontSize: '11px', color: T.color.text.tertiary, marginTop: '12px' }}>
          Method: {v.method || '—'} · Last run: {v.lastRun || '—'}
        </div>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 21. ASC 450 RESERVES
  // ═══════════════════════════════════════════════════════════════
  function RkReserves() {
    const s = window.useRiskStore(['reserve.updated']);
    const total = s.reserves.filter(r => r.ascCategory === 'probable').reduce((sum, r) => sum + (r.estimate || 0), 0);
    return (
      <Card title={`ASC 450 Loss Reserves · Probable Total: ${fmtMoney(total)}`}>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr><TH>Matter</TH><TH>Probability</TH><TH>Estimate</TH><TH>Range</TH><TH>Disclosure</TH><TH>Reviewed</TH></tr></thead>
          <tbody>
            {s.reserves.map(r => (
              <tr key={r.id}>
                <TD>{r.matter}</TD>
                <TD><Pill color={r.ascCategory === 'probable' ? '#C23030' : r.ascCategory === 'reasonably-possible' ? '#D97706' : '#6E7D9E'}>{r.probability}</Pill></TD>
                <TD mono>{fmtMoney(r.estimate)}</TD>
                <TD mono>{r.range}</TD>
                <TD>{r.disclosure}</TD>
                <TD mono>{r.lastReviewed}</TD>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 22. BOW-TIE
  // ═══════════════════════════════════════════════════════════════
  function RkBowTie() {
    const s = window.useRiskStore();
    const [idx, setIdx] = useState(0);
    const bt = s.bowTies[idx];
    if (!bt) return <Card title="Bow-Tie Analysis"><div style={{ fontSize: '12px', color: T.color.text.tertiary }}>No bow-ties configured.</div></Card>;
    return (
      <Card title={`Bow-Tie · ${bt.event}`} right={
        <div style={{ display: 'flex', gap: '4px' }}>
          {s.bowTies.map((b, i) => (
            <button key={b.id} onClick={() => setIdx(i)} style={{ padding: '2px 8px', fontSize: '10px', border: `1px solid ${T.color.border.light}`, borderRadius: '4px', background: i === idx ? rk.crimson : T.color.bg.card, color: i === idx ? '#fff' : T.color.text.secondary, cursor: 'pointer' }}>{b.id}</button>
          ))}
        </div>
      }>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', gap: '16px', alignItems: 'start' }}>
          <div>
            <div style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', marginBottom: '8px' }}>Causes (Preventive)</div>
            {bt.causes.map((c, i) => (
              <div key={i} style={{ padding: '8px', background: T.color.bg.secondary, borderRadius: '4px', marginBottom: '6px', border: `1px solid ${T.color.border.light}` }}>
                <div style={{ fontSize: '12px', fontWeight: 500 }}>{c.cause}</div>
                <div style={{ fontSize: '10px', color: '#1B7A4A', marginTop: '2px' }}>→ {c.control}</div>
              </div>
            ))}
          </div>
          <div style={{ padding: '14px', background: rk.crimson, color: '#fff', borderRadius: '8px', fontWeight: 700, fontSize: '12px', alignSelf: 'center', textAlign: 'center', minWidth: '140px' }}>{bt.event}</div>
          <div>
            <div style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', marginBottom: '8px' }}>Consequences (Reactive)</div>
            {bt.consequences.map((c, i) => (
              <div key={i} style={{ padding: '8px', background: T.color.bg.secondary, borderRadius: '4px', marginBottom: '6px', border: `1px solid ${T.color.border.light}` }}>
                <div style={{ fontSize: '12px', fontWeight: 500 }}>{c.consequence}</div>
                <div style={{ fontSize: '10px', color: '#3B82F6', marginTop: '2px' }}>→ {c.control}</div>
              </div>
            ))}
          </div>
        </div>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 23. STRESS TESTING
  // ═══════════════════════════════════════════════════════════════
  function RkStress() {
    const s = window.useRiskStore(['stress.ran']);
    return (
      <Card title="Stress Test Scenarios">
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr><TH>ID</TH><TH>Scenario</TH><TH>Impacted</TH><TH>Baseline</TH><TH>Stressed</TH><TH>ΔLoss</TH><TH>Ran</TH></tr></thead>
          <tbody>
            {s.stressTests.map(t => (
              <tr key={t.id}>
                <TD mono>{t.id}</TD>
                <TD>{t.scenario}</TD>
                <TD mono style={{ fontSize: '10px' }}>{t.impactedRisks.join(', ')}</TD>
                <TD mono>{t.baselineScore}</TD>
                <TD mono color="#C23030">{t.newScore}</TD>
                <TD mono color="#C23030">{fmtMoney(t.deltaLoss)}</TD>
                <TD mono>{t.ran}</TD>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 24. RISK-WEIGHTED PRIORITIZATION
  // ═══════════════════════════════════════════════════════════════
  function RkPriority() {
    const s = window.useRiskStore(['risk.updated']);
    const queue = window.RiskStore.priorityQueue();
    return (
      <Card title="Risk-Weighted Priority Queue">
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr><TH>#</TH><TH>ID</TH><TH>Name</TH><TH>Matter</TH><TH>Owner</TH><TH>Score</TH><TH>Days → Review</TH><TH>Priority Idx</TH></tr></thead>
          <tbody>
            {queue.slice(0, 15).map((q, i) => (
              <tr key={q.id}>
                <TD mono>{i + 1}</TD>
                <TD mono>{q.id}</TD>
                <TD>{q.name}</TD>
                <TD>{q.matter}</TD>
                <TD>{q.owner}</TD>
                <TD mono>{q.score}</TD>
                <TD mono color={q.urgencyDays <= 3 ? '#C23030' : q.urgencyDays <= 7 ? '#D97706' : T.color.text.primary}>{q.urgencyDays}</TD>
                <TD mono color={rk.crimson}>{q.priorityIndex.toFixed(1)}</TD>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // 25. MITIGATION EFFECTIVENESS
  // ═══════════════════════════════════════════════════════════════
  function RkMitigationEffect() {
    const s = window.useRiskStore(['mitigation.updated']);
    const summary = useMemo(() => {
      const byStatus = {};
      s.mitigations.forEach(m => { byStatus[m.status] = (byStatus[m.status] || 0) + 1; });
      return byStatus;
    }, [s.mitigations.length]);
    return (
      <Card title="Mitigation Effectiveness · Inherent vs. Residual">
        <div style={{ display: 'flex', gap: '8px', marginBottom: '12px' }}>
          {Object.entries(summary).map(([status, n]) => (
            <div key={status} style={rk.stat}>
              <div style={rk.statLabel}>{status}</div>
              <div style={rk.statValue}>{n}</div>
            </div>
          ))}
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr><TH>Risk</TH><TH>Inherent</TH><TH>Residual</TH><TH>Reduction</TH></tr></thead>
          <tbody>
            {s.register.filter(r => r.residualScore != null).map(r => {
              const red = r.score - r.residualScore;
              const reductionPct = r.score > 0 ? pct(red, r.score) : 0;
              return (
                <tr key={r.id}>
                  <TD mono>{r.id} · {r.name}</TD>
                  <TD mono>{r.score}</TD>
                  <TD mono color={r.residualScore < r.score ? '#1B7A4A' : '#C23030'}>{r.residualScore}</TD>
                  <TD mono color={red > 0 ? '#1B7A4A' : '#6E7D9E'}>{reductionPct}%</TD>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>
    );
  }

  // ═══════════════════════════════════════════════════════════════
  // GROUP HUBS
  // ═══════════════════════════════════════════════════════════════

  function RiskQuantHub() {
    const [sub, setSub] = useState('tornado');
    const tabs = [
      { id: 'tornado',  label: 'Tornado' },
      { id: 'var',      label: 'VaR / CVaR' },
      { id: 'reserves', label: 'ASC 450' },
      { id: 'bowtie',   label: 'Bow-Tie' },
      { id: 'stress',   label: 'Stress Tests' },
    ];
    return (
      <div>
        <RkSubTabs tabs={tabs} active={sub} onChange={setSub} />
        {sub === 'tornado'  && <RkTornado />}
        {sub === 'var'      && <RkVaR />}
        {sub === 'reserves' && <RkReserves />}
        {sub === 'bowtie'   && <RkBowTie />}
        {sub === 'stress'   && <RkStress />}
      </div>
    );
  }

  function RiskTreatmentHub() {
    const [sub, setSub] = useState('appetite');
    const tabs = [
      { id: 'appetite',   label: 'Appetite' },
      { id: 'controls',   label: 'Controls' },
      { id: 'treatments', label: 'Treatments' },
      { id: 'insurance',  label: 'Insurance' },
      { id: 'effect',     label: 'Effectiveness' },
    ];
    return (
      <div>
        <RkSubTabs tabs={tabs} active={sub} onChange={setSub} />
        {sub === 'appetite'   && <RkAppetite />}
        {sub === 'controls'   && <RkControls />}
        {sub === 'treatments' && <RkTreatments />}
        {sub === 'insurance'  && <RkInsurance />}
        {sub === 'effect'     && <RkMitigationEffect />}
      </div>
    );
  }

  function RiskIndicatorsHub() {
    const [sub, setSub] = useState('kri');
    const tabs = [
      { id: 'kri',       label: 'KRIs' },
      { id: 'triggers',  label: 'Triggers' },
      { id: 'regwatch',  label: 'Regulatory' },
      { id: 'incidents', label: 'Incidents' },
      { id: 'cyber',     label: 'Cyber' },
      { id: 'priority',  label: 'Priority Queue' },
    ];
    return (
      <div>
        <RkSubTabs tabs={tabs} active={sub} onChange={setSub} />
        {sub === 'kri'       && <RkKRI />}
        {sub === 'triggers'  && <RkTriggers />}
        {sub === 'regwatch'  && <RkRegWatch />}
        {sub === 'incidents' && <RkIncidents />}
        {sub === 'cyber'     && <RkCyber />}
        {sub === 'priority'  && <RkPriority />}
      </div>
    );
  }

  function RiskReportingHub() {
    const [sub, setSub] = useState('portfolio');
    const tabs = [
      { id: 'portfolio', label: 'Portfolio' },
      { id: 'committee', label: 'Committee' },
      { id: 'templates', label: 'Templates' },
      { id: 'maturity',  label: 'ERM Maturity' },
    ];
    return (
      <div>
        <RkSubTabs tabs={tabs} active={sub} onChange={setSub} />
        {sub === 'portfolio' && <RkPortfolio />}
        {sub === 'committee' && <RkCommittee />}
        {sub === 'templates' && <RkReporter />}
        {sub === 'maturity'  && <RkMaturity />}
      </div>
    );
  }

  function RiskGovernanceHub() {
    const [sub, setSub] = useState('walls');
    const tabs = [
      { id: 'walls',      label: 'Ethical Walls' },
      { id: 'vendors',    label: 'Vendors' },
      { id: 'clients',    label: 'Client Ratings' },
      { id: 'attorneys',  label: 'Attorney Profiles' },
      { id: 'settlement', label: 'Settlement Tree' },
    ];
    return (
      <div>
        <RkSubTabs tabs={tabs} active={sub} onChange={setSub} />
        {sub === 'walls'      && <RkEthicalWalls />}
        {sub === 'vendors'    && <RkVendors />}
        {sub === 'clients'    && <RkClientRatings />}
        {sub === 'attorneys'  && <RkAttorneyProfiles />}
        {sub === 'settlement' && <RkSettlementTree />}
      </div>
    );
  }

  // Window exports
  Object.assign(window, {
    RkAppetite, RkControls, RkTreatments, RkInsurance, RkKRI, RkTriggers,
    RkRegWatch, RkIncidents, RkCyber, RkPortfolio, RkCommittee, RkReporter,
    RkMaturity, RkEthicalWalls, RkVendors, RkClientRatings, RkAttorneyProfiles,
    RkSettlementTree, RkTornado, RkVaR, RkReserves, RkBowTie, RkStress,
    RkPriority, RkMitigationEffect,
    RiskQuantHub, RiskTreatmentHub, RiskIndicatorsHub, RiskReportingHub, RiskGovernanceHub,
  });
})();
