const { useState, useMemo } = React;

// ── WAR ROOM: Case Theory & Argument Map ──
function WarTheoryTab({ data }) {
  const [expanded, setExpanded] = useState(data.theories[0]?.id || null);
  const [hovered, setHovered] = useState(null);

  const strengthColor = (s) => s >= 80 ? W.green : s >= 60 ? W.amber : W.red;

  return (
    <div>
      {/* Strength overview */}
      <div style={{ display: 'grid', gridTemplateColumns: `repeat(${data.theories.length}, 1fr)`, gap: '12px', marginBottom: '20px' }}>
        {data.theories.map(t => {
          const c = strengthColor(t.strength);
          return (
            <div key={t.id} style={{ ...wr.stat, cursor: 'pointer', border: `1px solid ${expanded === t.id ? c.base : W.border.subtle}`, transition: 'border-color 0.2s' }} onClick={() => setExpanded(expanded === t.id ? null : t.id)}>
              <span style={wr.statLabel}>{t.status}</span>
              <span style={{ ...wr.statValue, color: c.text }}>{t.strength}%</span>
              <span style={{ fontSize: '12px', fontWeight: 600, color: W.text.primary, marginTop: '2px' }}>{t.label}</span>
            </div>
          );
        })}
      </div>

      {/* Theory cards */}
      {data.theories.map(t => {
        const c = strengthColor(t.strength);
        const isOpen = expanded === t.id;
        return (
          <div key={t.id} style={{ ...wr.card, borderColor: isOpen ? c.base + '40' : W.border.subtle }}>
            <div style={{ ...wr.cardH, cursor: 'pointer' }} onClick={() => setExpanded(isOpen ? null : t.id)}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <div style={wr.confidenceDot(t.strength)} />
                <span style={{ color: W.text.primary, fontWeight: 700, fontSize: '12px' }}>{t.label}</span>
                <span style={{ ...wr.tag, background: c.bg, color: c.text }}>{t.strength}% Confidence</span>
              </div>
              <span style={{ fontSize: '14px', color: W.text.tertiary, transition: 'transform 0.2s', transform: isOpen ? 'rotate(180deg)' : 'rotate(0)' }}>▾</span>
            </div>
            {isOpen && (
              <div style={wr.cardBody}>
                {/* Thesis */}
                <div style={{ fontSize: '13px', color: W.text.primary, lineHeight: 1.6, marginBottom: '16px', padding: '10px 12px', background: W.bg.tertiary, borderRadius: '6px', borderLeft: `3px solid ${c.base}` }}>
                  {t.thesis}
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px' }}>
                  {/* Key Facts */}
                  <div>
                    <div style={{ fontSize: '10px', fontWeight: 600, color: W.green.text, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '8px' }}>▲ Key Facts</div>
                    {t.keyFacts.map((f, i) => (
                      <div key={i} style={{ fontSize: '12px', color: W.text.secondary, marginBottom: '6px', paddingLeft: '10px', borderLeft: `2px solid ${W.green.base}30`, lineHeight: 1.4 }}>{f}</div>
                    ))}
                  </div>
                  {/* Attacks / Vulnerabilities */}
                  <div>
                    <div style={{ fontSize: '10px', fontWeight: 600, color: W.red.text, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '8px' }}>▼ Vulnerabilities</div>
                    {t.attacks.map((a, i) => (
                      <div key={i} style={{ fontSize: '12px', color: W.text.secondary, marginBottom: '6px', paddingLeft: '10px', borderLeft: `2px solid ${W.red.base}30`, lineHeight: 1.4 }}>{a}</div>
                    ))}
                  </div>
                  {/* Evidence Links */}
                  <div>
                    <div style={{ fontSize: '10px', fontWeight: 600, color: W.blue.text, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '8px' }}>◆ Evidence</div>
                    {t.evidence.map((e, i) => (
                      <div key={i} style={{ fontSize: '12px', color: W.blue.text, marginBottom: '6px', paddingLeft: '10px', borderLeft: `2px solid ${W.blue.base}30`, lineHeight: 1.4, cursor: 'pointer' }}>{e}</div>
                    ))}
                  </div>
                </div>
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

// ── WAR ROOM: Witness Strategy ──
function WarWitnessTab({ data }) {
  const [expandedWitness, setExpandedWitness] = useState(null);
  const w = data.witnesses;

  const WitnessRow = ({ witness, type }) => {
    const isOpen = expandedWitness === witness.name;
    const riskColor = { low: W.green, medium: W.amber, high: W.red }[witness.risk];
    const credColor = witness.credibility >= 75 ? W.green : witness.credibility >= 50 ? W.amber : W.red;

    return (
      <div style={{ ...wr.card, borderColor: isOpen ? (type === 'adverse' ? W.red.base : W.blue.base) + '30' : W.border.subtle }}>
        <div style={{ ...wr.row, cursor: 'pointer', padding: '10px 16px' }} onClick={() => setExpandedWitness(isOpen ? null : witness.name)}>
          <div style={{ width: '28px', height: '28px', borderRadius: '50%', background: type === 'adverse' ? W.red.bg : W.blue.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '11px', fontWeight: 700, color: type === 'adverse' ? W.red.text : W.blue.text, flexShrink: 0, border: `1px solid ${type === 'adverse' ? W.red.base : W.blue.base}30` }}>
            {witness.name.split(' ').map(w => w[0]).join('')}
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 600, color: W.text.primary, fontSize: '13px' }}>{witness.name}</div>
            <div style={{ fontSize: '11px', color: W.text.tertiary }}>{witness.role}</div>
          </div>
          <span style={{ ...wr.tag, background: credColor.bg, color: credColor.text }}>Cred {witness.credibility}%</span>
          <span style={{ ...wr.tag, background: riskColor.bg, color: riskColor.text }}>{witness.risk} risk</span>
          <span style={{ ...wr.tag, background: W.bg.tertiary, color: W.text.secondary }}>{witness.examTime}</span>
          <StatusTag status={witness.status} />
        </div>
        {isOpen && (
          <div style={{ ...wr.cardBody, borderTop: `1px solid ${W.border.subtle}` }}>
            <div style={{ fontSize: '12px', color: W.text.secondary, lineHeight: 1.5, marginBottom: '12px' }}>{witness.notes}</div>
            {witness.crossPlan && (
              <div>
                <div style={{ fontSize: '10px', fontWeight: 600, color: W.red.text, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '6px' }}>x Cross-Examination Plan</div>
                {witness.crossPlan.map((p, i) => (
                  <div key={i} style={{ display: 'flex', gap: '8px', alignItems: 'baseline', marginBottom: '4px' }}>
                    <span style={{ fontSize: '10px', fontFamily: W.font.mono, color: W.red.text, minWidth: '16px' }}>{i + 1}.</span>
                    <span style={{ fontSize: '12px', color: W.text.secondary, lineHeight: 1.4 }}>{p}</span>
                  </div>
                ))}
              </div>
            )}
            {witness.topics && (
              <div>
                <div style={{ fontSize: '10px', fontWeight: 600, color: W.green.text, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '6px' }}>◆ Examination Topics</div>
                <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
                  {witness.topics.map((t, i) => (
                    <span key={i} style={{ ...wr.tag, background: W.green.bg, color: W.green.text }}>{t}</span>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    );
  };

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
        <div>
          <div style={{ fontSize: '10px', fontWeight: 600, color: W.blue.text, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: '10px', display: 'flex', alignItems: 'center', gap: '6px' }}>
            <span style={{ width: '6px', height: '6px', borderRadius: '50%', background: W.blue.base }} /> Our Witnesses ({w.friendly.length})
          </div>
          {w.friendly.map(witness => <WitnessRow key={witness.name} witness={witness} type="friendly" />)}
        </div>
        <div>
          <div style={{ fontSize: '10px', fontWeight: 600, color: W.red.text, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: '10px', display: 'flex', alignItems: 'center', gap: '6px' }}>
            <span style={{ width: '6px', height: '6px', borderRadius: '50%', background: W.red.base }} /> Adverse Witnesses ({w.adverse.length})
          </div>
          {w.adverse.map(witness => <WitnessRow key={witness.name} witness={witness} type="adverse" />)}
        </div>
      </div>
    </div>
  );
}

// ── WAR ROOM: Evidence Matrix ──
function WarEvidenceTab({ data }) {
  const [hovered, setHovered] = useState(null);
  const theories = data.theories;
  const evidence = data.evidenceMatrix;

  return (
    <div>
      {/* Matrix grid */}
      <div style={wr.card}>
        <div style={wr.cardH}><span>Evidence ↔ Claims Matrix</span><span style={{ fontSize: '10px', color: W.text.muted }}>{evidence.length} items</span></div>
        <div style={{ overflowX: 'auto' }}>
          {/* Header */}
          <div style={{ display: 'grid', gridTemplateColumns: `200px 80px repeat(${theories.length}, 80px) 80px 100px`, padding: '6px 16px', borderBottom: `1px solid ${W.border.subtle}`, fontSize: '10px', fontWeight: 600, color: W.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', gap: '4px', minWidth: '700px' }}>
            <span>Evidence</span>
            <span>Strength</span>
            {theories.map(t => <span key={t.id} style={{ textAlign: 'center' }}>{t.label.split(' ')[0]}</span>)}
            <span>Status</span>
            <span>Type</span>
          </div>
          {evidence.map((e, i) => {
            const sColor = e.strength >= 85 ? W.green : e.strength >= 70 ? W.amber : W.red;
            return (
              <div key={e.id} style={{ display: 'grid', gridTemplateColumns: `200px 80px repeat(${theories.length}, 80px) 80px 100px`, padding: '8px 16px', borderBottom: `1px solid ${W.border.subtle}`, fontSize: '12px', alignItems: 'center', gap: '4px', background: hovered === i ? W.bg.tertiary : 'transparent', transition: 'background 0.1s', minWidth: '700px' }}
                onMouseEnter={() => setHovered(i)} onMouseLeave={() => setHovered(null)}>
                <div>
                  <div style={{ fontWeight: 600, color: W.text.primary }}>{e.name}</div>
                  <div style={{ fontSize: '10px', color: W.text.tertiary, marginTop: '1px' }}>{e.notes.slice(0, 60)}...</div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                  <div style={{ width: '36px', height: '4px', borderRadius: '2px', background: 'rgba(255,255,255,0.06)' }}>
                    <div style={{ width: `${e.strength}%`, height: '100%', borderRadius: '2px', background: sColor.base }} />
                  </div>
                  <span style={{ fontSize: '10px', fontFamily: W.font.mono, color: sColor.text }}>{e.strength}</span>
                </div>
                {theories.map(t => (
                  <div key={t.id} style={{ textAlign: 'center' }}>
                    {e.claims.includes(t.id) ? (
                      <span style={{ display: 'inline-block', width: '14px', height: '14px', borderRadius: '3px', background: W.green.bg, border: `1px solid ${W.green.base}40`, lineHeight: '14px', fontSize: '9px', color: W.green.text }}><Icons.Check size={11}/></span>
                    ) : (
                      <span style={{ color: W.text.muted, fontSize: '10px' }}>—</span>
                    )}
                  </div>
                ))}
                <StatusTag status={e.status} />
                <span style={{ ...wr.tag, background: W.bg.tertiary, color: W.text.secondary }}>{e.type}</span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { WarTheoryTab, WarWitnessTab, WarEvidenceTab });
