const { useState, useMemo } = React;

function fmtWar(val) {
  if (val >= 1000000) return '$' + (val/1e6).toFixed(1) + 'M';
  if (val >= 1000) return '$' + Math.round(val/1000) + 'K';
  return '$' + val;
}

// ── RISK HEAT MAP (enhances Theory tab — standalone section) ──
function RiskHeatMap({ extra }) {
  const rm = extra?.riskMatrix;
  if (!rm) return null;

  const cellColor = (score) => {
    if (score >= 85) return { bg: W.green.bg, text: W.green.text, border: W.green.base + '30' };
    if (score >= 70) return { bg: W.amber.bg, text: W.amber.text, border: W.amber.base + '30' };
    if (score >= 50) return { bg: 'rgba(239,68,68,0.05)', text: '#FCA5A5', border: W.red.base + '20' };
    return { bg: W.red.bg, text: W.red.text, border: W.red.base + '30' };
  };

  return (
    <div style={wr.card}>
      <div style={wr.cardH}><span>Risk Heat Map — Claims × Risk Factors</span></div>
      <div style={{ overflowX: 'auto' }}>
        {/* Header */}
        <div style={{ display: 'grid', gridTemplateColumns: `160px repeat(${rm.claims.length}, 1fr)`, padding: '6px 16px', borderBottom: `1px solid ${W.border.subtle}`, fontSize: '10px', fontWeight: 600, color: W.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', gap: '6px' }}>
          <span>Risk Factor</span>
          {rm.claims.map((c, i) => <span key={i} style={{ textAlign: 'center' }}>{c}</span>)}
        </div>
        {rm.risks.map((r, ri) => (
          <div key={ri} style={{ display: 'grid', gridTemplateColumns: `160px repeat(${rm.claims.length}, 1fr)`, padding: '0 16px', borderBottom: `1px solid ${W.border.subtle}`, gap: '6px', alignItems: 'stretch' }}>
            <div style={{ padding: '8px 0', fontSize: '11px', fontWeight: 600, color: W.text.primary, display: 'flex', alignItems: 'center' }}>{r.factor}</div>
            {r.scores.map((score, ci) => {
              const c = cellColor(score);
              return (
                <div key={ci} style={{ padding: '6px 8px', background: c.bg, borderLeft: `1px solid ${W.border.subtle}`, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: '2px' }}>
                  <span style={{ fontSize: '14px', fontWeight: 700, fontFamily: W.font.mono, color: c.text }}>{score}</span>
                  <span style={{ fontSize: '9px', color: W.text.tertiary, textAlign: 'center', lineHeight: 1.2 }}>{r.notes[ci]}</span>
                </div>
              );
            })}
          </div>
        ))}
      </div>
    </div>
  );
}

// ── DAMAGES BREAKDOWN VISUALIZATION ──
function DamagesBreakdown({ extra }) {
  const d = extra?.damagesBreakdown;
  if (!d) return null;
  const totalLow = d.reduce((s, x) => s + x.low, 0);
  const totalMid = d.reduce((s, x) => s + x.mid, 0);
  const totalHigh = d.reduce((s, x) => s + x.high, 0);
  const maxHigh = totalHigh;

  return (
    <div style={wr.card}>
      <div style={wr.cardH}><span>Damages Composition — Waterfall</span></div>
      <div style={{ padding: '16px' }}>
        {/* Totals row */}
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '16px' }}>
          <div style={wr.stat}><span style={wr.statLabel}>Low Estimate</span><span style={{ ...wr.statValue, color: W.amber.text, fontSize: '18px' }}>{fmtWar(totalLow)}</span></div>
          <div style={wr.stat}><span style={wr.statLabel}>Mid Estimate</span><span style={{ ...wr.statValue, color: W.green.text, fontSize: '18px' }}>{fmtWar(totalMid)}</span></div>
          <div style={wr.stat}><span style={wr.statLabel}>High Estimate</span><span style={{ ...wr.statValue, color: W.blue.text, fontSize: '18px' }}>{fmtWar(totalHigh)}</span></div>
        </div>
        {/* Stacked bars */}
        {d.map((cat, i) => (
          <div key={i} style={{ marginBottom: '10px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px' }}>
              <span style={{ fontSize: '11px', fontWeight: 600, color: W.text.primary }}>{cat.category}</span>
              <span style={{ fontSize: '10px', fontFamily: W.font.mono, color: W.text.secondary }}>
                {fmtWar(cat.low)} — {fmtWar(cat.mid)} — {fmtWar(cat.high)}
              </span>
            </div>
            <div style={{ position: 'relative', height: '12px', borderRadius: '6px', background: 'rgba(255,255,255,0.04)' }}>
              {/* High range */}
              <div style={{ position: 'absolute', left: 0, top: 0, height: '100%', width: `${(cat.high / maxHigh) * 100}%`, borderRadius: '6px', background: cat.color + '15' }} />
              {/* Mid range */}
              <div style={{ position: 'absolute', left: 0, top: 0, height: '100%', width: `${(cat.mid / maxHigh) * 100}%`, borderRadius: '6px', background: cat.color + '40' }} />
              {/* Low range */}
              <div style={{ position: 'absolute', left: 0, top: 0, height: '100%', width: `${(cat.low / maxHigh) * 100}%`, borderRadius: '6px', background: cat.color }} />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── SETTLEMENT NEGOTIATION TIMELINE ──
function NegotiationTimeline({ extra }) {
  const h = extra?.negotiationHistory;
  if (!h) return null;
  const maxAmount = Math.max(...h.map(x => x.amount));

  return (
    <div style={wr.card}>
      <div style={wr.cardH}><span>Negotiation History</span></div>
      {/* Visual timeline */}
      <div style={{ padding: '16px', display: 'flex', alignItems: 'flex-end', gap: '0', height: '140px', borderBottom: `1px solid ${W.border.subtle}` }}>
        {h.map((entry, i) => {
          const isPlaintiff = entry.party === 'Plaintiff';
          const color = isPlaintiff ? W.blue : W.red;
          const pct = (entry.amount / maxAmount) * 100;
          return (
            <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '4px', position: 'relative' }}>
              <span style={{ fontSize: '9px', fontFamily: W.font.mono, color: color.text, fontWeight: 700 }}>{fmtWar(entry.amount)}</span>
              <div style={{ width: '24px', borderRadius: '3px 3px 0 0', height: `${Math.max(pct * 0.8, 4)}px`, background: color.base, transition: 'height 0.5s' }} />
              <span style={{ fontSize: '9px', color: W.text.tertiary }}>{entry.date.split(', ')[0].replace('2026','').trim()}</span>
            </div>
          );
        })}
      </div>
      {/* Log */}
      {h.map((entry, i) => {
        const isPlaintiff = entry.party === 'Plaintiff';
        const color = isPlaintiff ? W.blue : W.red;
        return (
          <div key={i} style={{ padding: '8px 16px', borderBottom: `1px solid ${W.border.subtle}`, display: 'flex', alignItems: 'center', gap: '10px', fontSize: '12px' }}>
            <span style={{ fontSize: '10px', fontFamily: W.font.mono, color: W.text.tertiary, minWidth: '70px' }}>{entry.date.split(', ')[0]}</span>
            <span style={{ ...wr.tag, background: color.bg, color: color.text }}>{entry.party}</span>
            <span style={{ ...wr.tag, background: W.bg.tertiary, color: W.text.secondary }}>{entry.type}</span>
            <span style={{ fontFamily: W.font.mono, fontWeight: 700, color: color.text, minWidth: '70px' }}>{fmtWar(entry.amount)}</span>
            <span style={{ flex: 1, color: W.text.secondary }}>{entry.note}</span>
          </div>
        );
      })}
    </div>
  );
}

// ── IMPEACHMENT BANK ──
function ImpeachmentBank({ extra }) {
  const bank = extra?.impeachmentBank;
  if (!bank) return null;
  const [expanded, setExpanded] = useState(null);

  const sevColor = { critical: W.red, high: W.amber, medium: W.blue };

  return (
    <div style={wr.card}>
      <div style={{ ...wr.cardH, background: W.red.bg }}>
        <span style={{ color: W.red.text }}>x Impeachment Bank — Deposition Clips</span>
        <span style={{ fontSize: '10px', color: W.text.tertiary }}>{bank.length} clips</span>
      </div>
      {bank.map((clip, i) => {
        const c = sevColor[clip.severity] || W.amber;
        const isOpen = expanded === i;
        return (
          <div key={i} style={{ borderBottom: `1px solid ${W.border.subtle}` }}>
            <div style={{ padding: '10px 16px', display: 'flex', alignItems: 'flex-start', gap: '10px', cursor: 'pointer' }} onClick={() => setExpanded(isOpen ? null : i)}>
              <div style={{ minWidth: '60px' }}>
                <div style={{ fontSize: '10px', fontFamily: W.font.mono, fontWeight: 700, color: W.text.tertiary }}>p.{clip.page}</div>
                <div style={{ fontSize: '9px', fontFamily: W.font.mono, color: W.text.muted }}>ln {clip.line}</div>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: '12px', color: W.text.primary, fontStyle: 'italic', lineHeight: 1.4, marginBottom: '4px' }}>"{clip.quote}"</div>
                <div style={{ fontSize: '10px', color: W.text.tertiary }}>— {clip.witness}</div>
              </div>
              <span style={{ ...wr.tag, background: c.bg, color: c.text }}>{clip.severity}</span>
              <span style={{ ...wr.tag, background: W.bg.tertiary, color: W.text.secondary }}>{clip.tag}</span>
            </div>
            {isOpen && (
              <div style={{ padding: '8px 16px 12px 86px', fontSize: '12px' }}>
                <div style={{ fontSize: '10px', fontWeight: 600, color: W.red.text, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>Impeach With:</div>
                <div style={{ color: W.text.secondary, lineHeight: 1.5, padding: '8px 12px', background: W.red.bg, borderRadius: '6px', borderLeft: `3px solid ${W.red.base}` }}>{clip.impeachWith}</div>
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

// ── COUNTER-OFFENSE BOARD ──
function CounterOffenseBoard({ extra }) {
  const actions = extra?.counterOffense;
  if (!actions) return null;
  const [hovered, setHovered] = useState(null);

  return (
    <div style={wr.card}>
      <div style={{ ...wr.cardH, background: W.amber.bg }}>
        <span style={{ color: W.amber.text }}> Counter-Offense Action Board</span>
        <span style={{ fontSize: '10px', color: W.text.tertiary }}>{actions.length} actions</span>
      </div>
      {actions.map((a, i) => {
        const pColor = { high: W.red, medium: W.amber, low: W.blue }[a.priority];
        const sColor = a.status === 'Ready to File' ? W.green : a.status === 'Drafted' || a.status === 'Notice Served' ? W.amber : W.blue;
        return (
          <div key={i} style={{ padding: '10px 16px', borderBottom: `1px solid ${W.border.subtle}`, background: hovered === i ? W.bg.tertiary : 'transparent', transition: 'background 0.1s' }} onMouseEnter={() => setHovered(i)} onMouseLeave={() => setHovered(null)}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>
              <span style={{ ...wr.tag, background: pColor.bg, color: pColor.text }}>{a.priority}</span>
              <span style={{ fontWeight: 700, fontSize: '12px', color: W.text.primary, flex: 1 }}>{a.action}</span>
              <span style={{ ...wr.tag, background: sColor.bg, color: sColor.text }}>{a.status}</span>
              <span style={{ fontSize: '10px', color: W.text.tertiary }}>{a.assignee}</span>
            </div>
            <div style={{ display: 'flex', gap: '16px', fontSize: '11px', color: W.text.secondary, paddingLeft: '4px' }}>
              <span><span style={{ color: W.text.tertiary }}>Timing:</span> {a.timing}</span>
              <span><span style={{ color: W.text.tertiary }}>Impact:</span> {a.impact}</span>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ── TRIAL CHECKLIST WITH COUNTDOWN ──
function TrialChecklist({ extra, trialDate }) {
  const items = extra?.trialChecklist;
  if (!items) return null;

  const now = new Date('2026-04-20');
  const trial = new Date(trialDate || '2026-07-15');
  const daysUntil = Math.ceil((trial - now) / (1000 * 60 * 60 * 24));
  const done = items.filter(i => i.done).length;
  const total = items.length;
  const categories = [...new Set(items.map(i => i.category))];

  return (
    <div style={wr.card}>
      <div style={{ ...wr.cardH }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
          <span>Pre-Trial Checklist</span>
          <span style={{ ...wr.tag, background: W.green.bg, color: W.green.text }}>{done}/{total} complete</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <span style={{ fontSize: '10px', color: W.text.tertiary }}>Trial in</span>
          <span style={{ fontSize: '16px', fontWeight: 700, fontFamily: W.font.mono, color: daysUntil <= 30 ? W.red.text : daysUntil <= 60 ? W.amber.text : W.green.text }}>{daysUntil}</span>
          <span style={{ fontSize: '10px', color: W.text.tertiary }}>days</span>
        </div>
      </div>
      {/* Progress bar */}
      <div style={{ padding: '8px 16px', borderBottom: `1px solid ${W.border.subtle}` }}>
        <div style={wr.meterContainer}>
          <div style={{ width: `${(done / total) * 100}%`, height: '100%', borderRadius: '4px', background: W.green.base, transition: 'width 0.5s' }} />
        </div>
      </div>
      {categories.map(cat => (
        <div key={cat}>
          <div style={{ padding: '6px 16px', fontSize: '10px', fontWeight: 600, color: W.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em', background: W.bg.tertiary }}>{cat}</div>
          {items.filter(i => i.category === cat).map((item, i) => {
            const overdue = !item.done && new Date(item.due + ', 2026') < now;
            return (
              <div key={i} style={{ padding: '6px 16px', borderBottom: `1px solid ${W.border.subtle}`, display: 'flex', alignItems: 'center', gap: '8px', fontSize: '12px' }}>
                <span style={{ fontSize: '14px', color: item.done ? W.green.base : overdue ? W.red.base : W.text.muted }}>{item.done ? 'ok' : ''}</span>
                <span style={{ flex: 1, color: item.done ? W.text.tertiary : W.text.primary, textDecoration: item.done ? 'line-through' : 'none' }}>{item.item}</span>
                <span style={{ fontSize: '10px', fontFamily: W.font.mono, color: overdue ? W.red.text : W.text.tertiary }}>{item.due}</span>
                {overdue && <span style={{ ...wr.tag, background: W.red.bg, color: W.red.text }}>Overdue</span>}
              </div>
            );
          })}
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { RiskHeatMap, DamagesBreakdown, NegotiationTimeline, ImpeachmentBank, CounterOffenseBoard, TrialChecklist });
