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

// ── RISK REPORT / EXPORT VIEW (#11) ──
function RiskReport({ data }) {
  const [format, setFormat] = useState('executive');
  const reg = data.register;
  const mits = data.mitigations;
  const mc = data.monteCarlo;
  const scenarios = data.scenarios;

  const critical = reg.filter(r => r.score >= 15);
  const high = reg.filter(r => r.score >= 10 && r.score < 15);
  const rising = reg.filter(r => r.trend === 'rising');
  const avgScore = (reg.reduce((s, r) => s + r.score, 0) / reg.length).toFixed(1);
  const avgResidual = (reg.reduce((s, r) => s + r.residualScore, 0) / reg.length).toFixed(1);
  const mitComplete = mits.filter(m => m.status === 'Complete').length;
  const mitInProgress = mits.filter(m => m.status !== 'Complete' && m.status !== 'Not Started').length;

  return (
    <div>
      <div style={{ display: 'flex', gap: '8px', marginBottom: '16px', alignItems: 'center' }}>
        <span style={{ fontSize: '12px', fontWeight: 600, color: T.color.text.primary }}>Report Format:</span>
        {['executive', 'detailed', 'client'].map(f => (
          <button key={f} style={{ ...rk.filterBtn, ...(format === f ? rk.filterBtnActive : {}), textTransform: 'capitalize' }} onClick={() => setFormat(f)}>{f}</button>
        ))}
        <div style={{ flex: 1 }} />
        <button style={{ ...rk.filterBtn, color: rk.crimson, borderColor: `${rk.crimson}40` }}> Print</button>
      </div>

      {/* Report card */}
      <div style={{ ...rk.card, padding: '32px 40px', maxWidth: '800px' }}>
        {/* Header */}
        <div style={{ borderBottom: `2px solid ${T.color.text.primary}`, paddingBottom: '16px', marginBottom: '24px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div>
              <div style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '4px' }}>Arbiter — Risk Assessment</div>
              <div style={{ fontSize: '22px', fontWeight: 700, color: T.color.text.primary, letterSpacing: '-0.02em' }}>
                {format === 'executive' ? 'Executive Risk Summary' : format === 'client' ? 'Client Risk Report' : 'Detailed Risk Assessment'}
              </div>
              <div style={{ fontSize: '12px', color: T.color.text.tertiary, marginTop: '4px' }}>Prepared by M. Kirkland · April 20, 2026</div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: '4px' }}>
              <div style={{ fontSize: '32px', fontWeight: 700, color: scoreColor(parseFloat(avgScore)), fontFamily: T.font.mono }}>{avgScore}</div>
              <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>Avg Risk Score</div>
            </div>
          </div>
        </div>

        {/* Portfolio overview */}
        <div style={{ marginBottom: '24px' }}>
          <div style={{ fontSize: '14px', fontWeight: 700, color: T.color.text.primary, marginBottom: '12px' }}>Portfolio Overview</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '12px' }}>
            {[
              { label: 'Total Risks', value: reg.length, color: T.color.text.primary },
              { label: 'Critical (≥15)', value: critical.length, color: '#C23030' },
              { label: 'High (10–14)', value: high.length, color: '#D97706' },
              { label: 'Rising Trend', value: rising.length, color: '#C23030' },
            ].map((s, i) => (
              <div key={i} style={{ padding: '12px', background: T.color.bg.secondary, borderRadius: '6px', border: `1px solid ${T.color.border.light}` }}>
                <div style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>{s.label}</div>
                <div style={{ fontSize: '24px', fontWeight: 700, color: s.color, fontFamily: T.font.mono }}>{s.value}</div>
              </div>
            ))}
          </div>
          <div style={{ fontSize: '12px', color: T.color.text.secondary, lineHeight: 1.6 }}>
            The portfolio contains {reg.length} tracked risks across {data.categories.length} categories. {critical.length} risks are rated critical, with {rising.length} risks trending upward since last assessment. Average inherent score is {avgScore}; average residual score after controls is {avgResidual}, representing a {((1 - parseFloat(avgResidual) / parseFloat(avgScore)) * 100).toFixed(0)}% risk reduction through current mitigations.
          </div>
        </div>

        {/* Critical risks */}
        <div style={{ marginBottom: '24px' }}>
          <div style={{ fontSize: '14px', fontWeight: 700, color: T.color.text.primary, marginBottom: '12px' }}>Critical & High-Priority Risks</div>
          {[...critical, ...high].slice(0, format === 'executive' ? 5 : 10).map((r, i) => (
            <div key={r.id} style={{ padding: '10px 0', borderBottom: `1px solid ${T.color.border.light}` }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>
                <span style={{ fontFamily: T.font.mono, fontSize: '10px', color: T.color.text.tertiary }}>{r.id}</span>
                <span style={{ fontWeight: 600, fontSize: '13px', color: T.color.text.primary }}>{r.name}</span>
                <span style={{ fontSize: '10px', fontWeight: 700, color: trendColor(r.trend), marginLeft: 'auto' }}>{trendIcon(r.trend)}</span>
                <span style={{ fontFamily: T.font.mono, fontSize: '12px', fontWeight: 700, color: scoreColor(r.score) }}>{r.score}</span>
              </div>
              <div style={{ fontSize: '11px', color: T.color.text.tertiary, marginBottom: '4px' }}>{r.category} · {r.matter} · Owner: {r.owner}</div>
              {format !== 'executive' && (
                <div style={{ fontSize: '11px', color: T.color.text.secondary, lineHeight: 1.5 }}>
                  <strong>Mitigation:</strong> {r.mitigation}
                </div>
              )}
            </div>
          ))}
        </div>

        {/* Scenario summary */}
        <div style={{ marginBottom: '24px' }}>
          <div style={{ fontSize: '14px', fontWeight: 700, color: T.color.text.primary, marginBottom: '12px' }}>Case Valuation — Scenario Analysis</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '12px' }}>
            <div style={{ padding: '12px', background: T.color.bg.secondary, borderRadius: '6px', border: `1px solid ${T.color.border.light}` }}>
              <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginBottom: '2px' }}>Expected Value</div>
              <div style={{ fontSize: '20px', fontWeight: 700, fontFamily: T.font.mono }}>${(mc.expectedValue / 1e6).toFixed(1)}M</div>
            </div>
            <div style={{ padding: '12px', background: T.color.bg.secondary, borderRadius: '6px', border: `1px solid ${T.color.border.light}` }}>
              <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginBottom: '2px' }}>Range (P10–P90)</div>
              <div style={{ fontSize: '20px', fontWeight: 700, fontFamily: T.font.mono }}>${(mc.p10 / 1e6).toFixed(1)}M – ${(mc.p90 / 1e6).toFixed(1)}M</div>
            </div>
          </div>
          {scenarios.map(sc => (
            <div key={sc.id} style={{ display: 'flex', alignItems: 'center', gap: '10px', padding: '6px 0', borderBottom: `1px solid ${T.color.border.light}`, fontSize: '12px' }}>
              <span style={{ fontWeight: 600, color: T.color.text.primary, flex: 1 }}>{sc.name}</span>
              <span style={{ fontFamily: T.font.mono, fontWeight: 700, color: T.color.text.primary }}>{sc.damages}</span>
              <span style={{ fontFamily: T.font.mono, fontSize: '11px', color: T.color.text.tertiary }}>{sc.probability}%</span>
            </div>
          ))}
        </div>

        {/* Mitigation status */}
        <div style={{ marginBottom: '24px' }}>
          <div style={{ fontSize: '14px', fontWeight: 700, color: T.color.text.primary, marginBottom: '12px' }}>Mitigation Actions Summary</div>
          <div style={{ fontSize: '12px', color: T.color.text.secondary, lineHeight: 1.6 }}>
            {mits.length} mitigation actions tracked: {mitComplete} complete, {mitInProgress} in progress, {mits.length - mitComplete - mitInProgress} not started. Average progress across all actions: {Math.round(mits.reduce((s, m) => s + m.progress, 0) / mits.length)}%.
          </div>
        </div>

        {/* Footer */}
        <div style={{ borderTop: `1px solid ${T.color.border.light}`, paddingTop: '12px', fontSize: '10px', color: T.color.text.tertiary, display: 'flex', justifyContent: 'space-between' }}>
          <span>Arbiter Legal Case Management — Confidential</span>
          <span>Generated April 20, 2026</span>
        </div>
      </div>
    </div>
  );
}

// ── RISK CREATION MODAL (#4) ──
function RiskCreateModal({ onClose, data }) {
  const [name, setName] = useState('');
  const [category, setCategory] = useState('Litigation');
  const [subcategory, setSubcategory] = useState('');
  const [matter, setMatter] = useState('Redstone v. Meridian');
  const [likelihood, setLikelihood] = useState(3);
  const [impact, setImpact] = useState(3);
  const [owner, setOwner] = useState('M. Kirkland');
  const [mitigation, setMitigation] = useState('');
  const [triggers, setTriggers] = useState('');

  const score = likelihood * impact;
  const categories = [...new Set(data.register.map(r => r.category))];
  const matters = [...new Set(data.register.map(r => r.matter))];
  const owners = [...new Set(data.register.map(r => r.owner))];

  const inputStyle = { width: '100%', padding: '6px 10px', borderRadius: T.radius.md, border: `1px solid ${T.color.border.light}`, fontSize: '12px', fontFamily: T.font.family, background: T.color.bg.primary, color: T.color.text.primary, outline: 'none' };
  const labelStyle = { display: 'block', marginBottom: '12px' };
  const labelText = { display: 'block', fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' };

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(10,22,40,0.5)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={onClose}>
      <div style={{ width: '560px', maxHeight: '85vh', overflow: 'auto', background: T.color.bg.card, borderRadius: '12px', boxShadow: '0 16px 48px rgba(10,22,40,0.25)', padding: '24px' }} onClick={e => e.stopPropagation()}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
          <div style={{ fontSize: '16px', fontWeight: 700, color: T.color.text.primary }}>New Risk</div>
          <button onClick={onClose} style={{ border: 'none', background: 'none', fontSize: '18px', color: T.color.text.tertiary, cursor: 'pointer' }}>×</button>
        </div>

        <label style={labelStyle}>
          <span style={labelText}>Risk Name</span>
          <input style={inputStyle} placeholder="e.g. Adverse Summary Judgment Ruling" value={name} onChange={e => setName(e.target.value)} />
        </label>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
          <label style={labelStyle}>
            <span style={labelText}>Category</span>
            <select style={inputStyle} value={category} onChange={e => setCategory(e.target.value)}>
              {categories.map(c => <option key={c}>{c}</option>)}
            </select>
          </label>
          <label style={labelStyle}>
            <span style={labelText}>Subcategory</span>
            <input style={inputStyle} placeholder="e.g. Dispositive Motion" value={subcategory} onChange={e => setSubcategory(e.target.value)} />
          </label>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
          <label style={labelStyle}>
            <span style={labelText}>Matter</span>
            <select style={inputStyle} value={matter} onChange={e => setMatter(e.target.value)}>
              {matters.map(m => <option key={m}>{m}</option>)}
            </select>
          </label>
          <label style={labelStyle}>
            <span style={labelText}>Owner</span>
            <select style={inputStyle} value={owner} onChange={e => setOwner(e.target.value)}>
              {owners.map(o => <option key={o}>{o}</option>)}
            </select>
          </label>
        </div>

        {/* Likelihood / Impact sliders */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr auto', gap: '12px', marginBottom: '12px' }}>
          <label style={labelStyle}>
            <span style={labelText}>Likelihood (1–5)</span>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
              <input type="range" min="1" max="5" step="1" value={likelihood} onChange={e => setLikelihood(parseInt(e.target.value))} style={{ flex: 1, accentColor: rk.crimson }} />
              <span style={{ fontFamily: T.font.mono, fontSize: '14px', fontWeight: 700, color: T.color.text.primary, width: '20px', textAlign: 'center' }}>{likelihood}</span>
            </div>
          </label>
          <label style={labelStyle}>
            <span style={labelText}>Impact (1–5)</span>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
              <input type="range" min="1" max="5" step="1" value={impact} onChange={e => setImpact(parseInt(e.target.value))} style={{ flex: 1, accentColor: rk.crimson }} />
              <span style={{ fontFamily: T.font.mono, fontSize: '14px', fontWeight: 700, color: T.color.text.primary, width: '20px', textAlign: 'center' }}>{impact}</span>
            </div>
          </label>
          <div style={{ paddingTop: '18px' }}>
            <div style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, marginBottom: '4px' }}>SCORE</div>
            <div style={{ fontSize: '28px', fontWeight: 700, color: scoreColor(score), fontFamily: T.font.mono, textAlign: 'center' }}>{score}</div>
          </div>
        </div>

        <label style={labelStyle}>
          <span style={labelText}>Mitigation Strategy</span>
          <textarea style={{ ...inputStyle, height: '64px', resize: 'vertical' }} placeholder="Describe mitigation approach..." value={mitigation} onChange={e => setMitigation(e.target.value)} />
        </label>

        <label style={labelStyle}>
          <span style={labelText}>Triggers (comma-separated)</span>
          <input style={inputStyle} placeholder="e.g. Weak testimony, Missing records" value={triggers} onChange={e => setTriggers(e.target.value)} />
        </label>

        <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end', marginTop: '8px' }}>
          <button onClick={onClose} style={{ ...rk.filterBtn, padding: '8px 16px' }}>Cancel</button>
          <button onClick={onClose} style={{ padding: '8px 20px', borderRadius: T.radius.md, background: rk.crimson, border: 'none', color: '#fff', fontSize: '12px', fontWeight: 700, cursor: 'pointer', fontFamily: T.font.family, opacity: name ? 1 : 0.5 }}>
            Create Risk
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { RiskReport, RiskCreateModal });
