// demo-exam.jsx — simulacro de demostración modo estudio (réplica exacta del examen real)

const { useState, useMemo, useEffect } = React;

// ── Deterministic shuffle (same as ExamPlayer) ───────────────────────────────
function seededShuffle(arr, seed) {
  const result = [...arr];
  let h = 0;
  for (let i = 0; i < seed.length; i++) h = (Math.imul(31, h) + seed.charCodeAt(i)) | 0;
  for (let i = result.length - 1; i > 0; i--) {
    h = (Math.imul(h, 1664525) + 1013904223) | 0;
    const j = Math.abs(h) % (i + 1);
    [result[i], result[j]] = [result[j], result[i]];
  }
  return result;
}

// ── SINALEVI URL map (same as lib/utils/sinalevi.ts) ────────────────────────
const SINALEVI_URLS = {
  'código civil': 'https://pgrweb.go.cr/scij/Busqueda/Normativa/Normas/nrm_texto_completo.aspx?nValor1=1&nValor2=15437',
  'codigo civil': 'https://pgrweb.go.cr/scij/Busqueda/Normativa/Normas/nrm_texto_completo.aspx?nValor1=1&nValor2=15437',
  'código penal': 'https://pgrweb.go.cr/scij/Busqueda/Normativa/Normas/nrm_texto_completo.aspx?nValor1=1&nValor2=5027',
  'codigo penal': 'https://pgrweb.go.cr/scij/Busqueda/Normativa/Normas/nrm_texto_completo.aspx?nValor1=1&nValor2=5027',
  'código de trabajo': 'https://pgrweb.go.cr/scij/Busqueda/Normativa/normas/nrm_texto_completo.aspx?nValor1=1&nValor2=8045',
  'codigo de trabajo': 'https://pgrweb.go.cr/scij/Busqueda/Normativa/normas/nrm_texto_completo.aspx?nValor1=1&nValor2=8045',
  'código de comercio': 'https://pgrweb.go.cr/scij/Busqueda/Normativa/normas/nrm_texto_completo.aspx?nValor1=1&nValor2=6239',
  'codigo de comercio': 'https://pgrweb.go.cr/scij/Busqueda/Normativa/normas/nrm_texto_completo.aspx?nValor1=1&nValor2=6239',
  'código de comercio de la república de costa rica': 'https://pgrweb.go.cr/scij/Busqueda/Normativa/normas/nrm_texto_completo.aspx?nValor1=1&nValor2=6239',
  'código de familia': 'https://pgrweb.go.cr/scij/busqueda/normativa/normas/nrm_texto_completo.aspx?nValor1=1&nValor2=970',
  'codigo de familia': 'https://pgrweb.go.cr/scij/busqueda/normativa/normas/nrm_texto_completo.aspx?nValor1=1&nValor2=970',
  'constitución política': 'https://pgrweb.go.cr/scij/Busqueda/Normativa/normas/nrm_texto_completo.aspx?nValor1=1&nValor2=871',
  'constitucion politica': 'https://pgrweb.go.cr/scij/Busqueda/Normativa/normas/nrm_texto_completo.aspx?nValor1=1&nValor2=871',
  'constitución política de costa rica': 'https://pgrweb.go.cr/scij/Busqueda/Normativa/normas/nrm_texto_completo.aspx?nValor1=1&nValor2=871',
  'ley general de la administración pública': 'https://pgrweb.go.cr/scij/Busqueda/Normativa/Normas/nrm_texto_completo.aspx?nValor1=1&nValor2=13231',
  'ley general de la administracion publica': 'https://pgrweb.go.cr/scij/Busqueda/Normativa/Normas/nrm_texto_completo.aspx?nValor1=1&nValor2=13231',
  'código procesal contencioso-administrativo': 'https://pgrweb.go.cr/scij/Busqueda/Normativa/Normas/nrm_texto_completo.aspx?nValor1=1&nValor2=60446',
  'código procesal penal': 'https://pgrweb.go.cr/scij/Busqueda/Normativa/Normas/nrm_texto_completo.aspx?nValor1=1&nValor2=16426',
};

function norm(s) { return s.toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '').trim(); }

function sinaleviUrl(ley) {
  const n = norm(ley);
  if (SINALEVI_URLS[n]) return SINALEVI_URLS[n];
  for (const [k, url] of Object.entries(SINALEVI_URLS)) {
    if (n.includes(k) || k.includes(n)) return url;
  }
  return `https://www.pgrweb.go.cr/scij/Busqueda/Normativa/Normas/nrm_busqueda.aspx?param1=NRB&txtNBuscar=${encodeURIComponent(ley)}&btnNBuscar=Buscar&strSW=SI&strB=SI`;
}

function parseArticulos(articulo) {
  if (!articulo || !articulo.trim()) return [];
  return articulo
    .replace(/\bArt[íi]culos?\b\.?\s*/gi, '')
    .split(/\s+y\s+|,\s*|;\s*/)
    .map(a => a.trim())
    .filter(Boolean);
}

// ── Letter remap (same as ExamPlayer) ───────────────────────────────────────
// La explicación se escribió usando las letras originales de la BD (A-E), pero las
// opciones se barajan por sesión. Sin esto, la justificación puede referirse a una
// letra distinta de la que el alumno ve marcada en pantalla.
function remapExplicacionLetters(text, shuffledOrder) {
  if (!text) return text;
  const mapping = {};
  shuffledOrder.forEach((original, idx) => { mapping[original] = LETTERS[idx]; });
  return text.replace(
    /(opci[oó]n|alternativa|respuesta)((?:\s+[a-zA-ZñÑáéíóúÁÉÍÓÚ]+){0,4})\s+([A-E])\b/gi,
    (match, word, filler, letter) => {
      const mapped = mapping[letter.toUpperCase()];
      return mapped ? `${word}${filler} ${mapped}` : match;
    }
  );
}

// ── Inline Antología source modal (same pattern as components/PdfSourceModal.tsx) ──
function PdfSourcePopup({ ley, pagina, fragmento, onClose }) {
  useEffect(() => {
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, []);

  return (
    <div
      style={{
        position: 'fixed', inset: 0, zIndex: 200,
        background: 'rgba(0,0,0,.6)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '16px',
      }}
      onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}
    >
      <div style={{
        width: 'min(640px, 96vw)', maxHeight: '80vh', display: 'flex', flexDirection: 'column',
        background: '#fff', borderRadius: '12px',
        boxShadow: '0 24px 80px -20px rgba(0,0,0,.6)',
      }}>
        <div style={{
          padding: '16px 20px', borderBottom: '1px solid #e5e7eb',
          display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: '16px',
          flexShrink: 0,
        }}>
          <div>
            <p style={{
              fontSize: '11px', fontWeight: 600, letterSpacing: '.1em', textTransform: 'uppercase',
              color: '#6b7280', marginBottom: '4px', fontFamily: 'var(--font-body)',
            }}>{ley}</p>
            <h3 style={{ fontSize: '17px', fontWeight: 700, color: '#111827', margin: 0 }}>
              {pagina}
            </h3>
          </div>
          <button onClick={onClose} style={{
            width: 32, height: 32, border: 'none', background: 'transparent',
            cursor: 'pointer', fontSize: '22px', color: '#9ca3af', lineHeight: 1, flexShrink: 0,
          }}>×</button>
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: '18px 20px' }}>
          {fragmento ? (
            <div style={{ fontSize: '14px', color: '#1f2937', lineHeight: 1.7 }}>
              <div style={{ background: '#fffbeb', borderLeft: '4px solid #fbbf24', padding: '12px 16px', borderRadius: '0 8px 8px 0' }}>
                <pre style={{ whiteSpace: 'pre-wrap', fontFamily: 'inherit', margin: 0 }}>{fragmento}</pre>
              </div>
              <p style={{ fontSize: '12px', color: '#9ca3af', marginTop: '12px' }}>Fuente: {ley} — {pagina}</p>
            </div>
          ) : (
            <div style={{ textAlign: 'center', padding: '40px 0', color: '#9ca3af', fontSize: '14px' }}>
              No hay fragmento disponible para esta pregunta.
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ── Inline Article Modal ─────────────────────────────────────────────────────
function ArticlePopup({ ley, articulo, onClose }) {
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState(null);

  useEffect(() => {
    setLoading(true);
    fetch(`/api/article?ley=${encodeURIComponent(ley)}&articulo=${encodeURIComponent(articulo)}`)
      .then(r => r.json())
      .then(d => setData(d))
      .catch(() => setData({ found: false }))
      .finally(() => setLoading(false));
  }, [ley, articulo]);

  // Close on Escape
  useEffect(() => {
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, []);

  return (
    <div
      style={{
        position: 'fixed', inset: 0, zIndex: 200,
        background: 'rgba(0,0,0,.6)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '16px',
      }}
      onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}
    >
      <div style={{
        width: 'min(640px, 96vw)', maxHeight: '80vh', display: 'flex', flexDirection: 'column',
        background: '#fff', borderRadius: '12px',
        boxShadow: '0 24px 80px -20px rgba(0,0,0,.6)',
      }}>
        {/* Header */}
        <div style={{
          padding: '16px 20px', borderBottom: '1px solid #e5e7eb',
          display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: '16px',
          flexShrink: 0,
        }}>
          <div>
            <p style={{
              fontSize: '11px', fontWeight: 600, letterSpacing: '.1em', textTransform: 'uppercase',
              color: '#6b7280', marginBottom: '4px', fontFamily: 'var(--font-body)',
            }}>{ley}</p>
            <h3 style={{ fontSize: '17px', fontWeight: 700, color: '#111827', margin: 0 }}>
              Artículo {articulo}
            </h3>
            {data?.sinaleviUrl && (
              <a href={data.sinaleviUrl} target="_blank" rel="noopener noreferrer"
                 style={{ fontSize: '12px', color: '#2563eb', textDecoration: 'none', marginTop: '4px', display: 'inline-block' }}>
                Ver en SINALEVI ↗
              </a>
            )}
          </div>
          <button onClick={onClose} style={{
            width: 32, height: 32, border: 'none', background: 'transparent',
            cursor: 'pointer', fontSize: '22px', color: '#9ca3af', lineHeight: 1, flexShrink: 0,
          }}>×</button>
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '18px 20px' }}>
          {loading && (
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '48px 0', gap: '12px', color: '#9ca3af' }}>
              <div style={{
                width: 20, height: 20, border: '2px solid #e5e7eb', borderTopColor: '#2563eb',
                borderRadius: '50%', animation: 'spin 1s linear infinite',
              }} />
              <span style={{ fontSize: '14px' }}>Cargando artículo…</span>
            </div>
          )}
          {!loading && !data?.found && (
            <div style={{ textAlign: 'center', padding: '40px 0' }}>
              <p style={{ fontSize: '14px', color: '#9ca3af', marginBottom: '12px' }}>
                Artículo no encontrado en la base de datos local.
              </p>
              <a href={sinaleviUrl(ley)} target="_blank" rel="noopener noreferrer"
                 style={{ fontSize: '13px', color: '#2563eb' }}>
                Buscar en SINALEVI ↗
              </a>
            </div>
          )}
          {!loading && data?.found && data?.text && (
            <div style={{ fontSize: '14px', color: '#1f2937', lineHeight: 1.7 }}>
              {data.title && (
                <p style={{ fontWeight: 700, marginBottom: '12px' }}>{data.title}</p>
              )}
              <pre style={{ whiteSpace: 'pre-wrap', fontFamily: 'inherit', margin: 0 }}>{data.text}</pre>
            </div>
          )}
        </div>
      </div>
      <style>{`@keyframes spin{to{transform:rotate(360deg)}}`}</style>
    </div>
  );
}

// ── Main DemoExam ────────────────────────────────────────────────────────────
const LETTERS = ['A', 'B', 'C', 'D', 'E'];

function DemoExam({ open, onClose }) {
  const questions = window.__DEMO_QUESTIONS__ || [];
  const total = questions.length;
  const stats = window.__QUESTION_STATS__ || { total: 0, byMateria: {} };
  const bankTotal = stats.total || 0;
  const materiaCount = Object.keys(stats.byMateria || {}).length;

  const [phase, setPhase] = useState('intro'); // intro | run | done
  const [idx, setIdx] = useState(0);
  const [answers, setAnswers] = useState({});
  const [articleModal, setArticleModal] = useState(null); // { ley, articulo }

  const optionOrders = useMemo(() => {
    const map = {};
    for (const q of questions) {
      const keys = Object.keys(q.opciones || {}).filter(k => q.opciones[k]);
      map[q.id] = seededShuffle(keys, q.id);
    }
    return map;
  }, [total]);

  useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (e.key === 'Escape' && phase !== 'run' && !articleModal) onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [open, phase, articleModal]);

  if (!open) return null;

  const q = questions[idx];
  const selectedKey = q ? answers[q.id] : null;
  const answered = selectedKey != null;
  const isCorrect = answered && selectedKey === q.respuesta_correcta;
  const correctCount = questions.filter(q2 => answers[q2.id] === q2.respuesta_correcta).length;
  const score = total > 0 ? Math.round((correctCount / total) * 100) : 0;

  // Visual label (A/B/C/D/E as shown to student) for the correct answer after shuffle
  const shuffledOrder = q ? (optionOrders[q.id] || LETTERS) : LETTERS;
  const correctVisualLabel = q ? (LETTERS[shuffledOrder.indexOf(q.respuesta_correcta)] ?? q.respuesta_correcta) : null;

  function openArticleModal(ley, articulo, fuenteUrl) {
    setArticleModal({ ley, articulo, antologia: !!ley?.includes('Antología'), fragmento: fuenteUrl });
  }

  function handleSelect(key) {
    if (answered) return;
    setAnswers(prev => ({ ...prev, [q.id]: key }));
  }

  function handleNext() {
    if (idx < total - 1) setIdx(idx + 1);
    else setPhase('done');
  }

  function handleReset() {
    setPhase('intro');
    setIdx(0);
    setAnswers({});
  }

  // Option button rendering (matches ExamPlayer exactly)
  function optBg(key) {
    if (!answered) return 'var(--bg-elev)';
    if (key === q.respuesta_correcta) return '#f0fdf4';
    if (key === selectedKey) return '#fef2f2';
    return 'var(--bg-elev)';
  }
  function optBorder(key) {
    if (!answered) return 'var(--line)';
    if (key === q.respuesta_correcta) return '#22c55e';
    if (key === selectedKey) return '#ef4444';
    return 'var(--line)';
  }
  function optColor(key) {
    if (!answered) return 'var(--text)';
    if (key === q.respuesta_correcta) return '#14532d';
    if (key === selectedKey) return '#7f1d1d';
    return 'var(--text-soft)';
  }

  return (
    <>
      <div
        role="dialog" aria-modal="true"
        style={{
          position: 'fixed', inset: 0, zIndex: 120,
          display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '16px',
          background: 'color-mix(in oklab, var(--brand) 60%, rgba(0,0,0,.55))',
          backdropFilter: 'blur(6px)',
        }}
        onMouseDown={(e) => { if (e.target === e.currentTarget && phase !== 'run') onClose(); }}
      >
        <div style={{
          width: 'min(680px, 96vw)', maxHeight: '92vh', display: 'flex', flexDirection: 'column',
          background: 'var(--bg)', border: '1px solid var(--line-strong)', borderRadius: '12px',
          boxShadow: '0 40px 120px -40px rgba(0,0,0,.7)',
          animation: 'simPop .24s cubic-bezier(.2,.8,.2,1)', overflow: 'hidden',
        }}>

          {/* ── Header ── */}
          <div style={{
            display: 'flex', alignItems: 'center', gap: '12px',
            padding: '12px 18px', borderBottom: '1px solid var(--line)',
            background: 'var(--bg-elev)', flexShrink: 0,
          }}>
            <div style={{
              display: 'flex', alignItems: 'center', gap: '8px',
              fontFamily: 'var(--font-display)', fontSize: '13px', color: 'var(--text-soft)', flex: 1,
            }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--accent)', flexShrink: 0 }} />
              Simulacro de demostración
            </div>
            {phase === 'run' && (
              <div style={{
                flex: 1, display: 'flex', flexDirection: 'column',
                alignItems: 'center', textAlign: 'center', minWidth: 0,
              }}>
                <span style={{ fontSize: '13px', fontWeight: 600, color: 'var(--text)', lineHeight: 1.25 }}>
                  Pregunta {idx + 1} de {total}
                </span>
                <span style={{
                  fontSize: '11px', color: 'var(--text-soft)', lineHeight: 1.2,
                  overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '200px',
                }}>{q.materia}</span>
              </div>
            )}
            <button onClick={onClose} style={{
              width: 28, height: 28, border: 'none', background: 'transparent',
              cursor: 'pointer', fontSize: '15px', color: 'var(--text-soft)', borderRadius: '6px',
              display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
            }}>✕</button>
          </div>

          {/* ── Progress bar ── */}
          {phase === 'run' && (
            <div style={{ height: 3, background: 'var(--line)', flexShrink: 0 }}>
              <div style={{
                height: '100%', background: 'var(--accent)',
                width: `${((idx + (answered ? 1 : 0)) / total) * 100}%`,
                transition: 'width .3s ease',
              }} />
            </div>
          )}

          {/* ── Body ── */}
          <div style={{ flex: 1, overflowY: 'auto', padding: '26px 26px 34px' }}>

            {/* ━━ INTRO ━━ */}
            {phase === 'intro' && (
              <div>
                <div className="mono" style={{ marginBottom: '12px' }}>SIMULACRO GRATUITO · MODO ESTUDIO</div>
                <h2 style={{
                  fontFamily: 'var(--font-display)', fontSize: '27px',
                  lineHeight: 1.1, marginBottom: '13px', color: 'var(--title)',
                }}>
                  Probá el examen real
                </h2>
                <p style={{ fontSize: '15px', color: 'var(--text-soft)', lineHeight: 1.6, marginBottom: '26px' }}>
                  {total} preguntas del banco real, 2 por cada materia evaluada. Respondé cada pregunta
                  y al instante verás si es correcta, la justificación y el artículo de ley
                  que podés abrir directamente.
                </p>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: '10px', marginBottom: '26px' }}>
                  {[
                    { n: total, label: 'preguntas reales' },
                    { n: materiaCount || 8, label: 'materias evaluadas' },
                    { n: '100%', label: 'con artículo de ley' },
                  ].map((s, i) => (
                    <div key={i} style={{
                      padding: '16px 12px', background: 'var(--bg-elev)',
                      border: '1px solid var(--line)', borderRadius: '8px', textAlign: 'center',
                    }}>
                      <div style={{
                        fontFamily: 'var(--font-display)', fontSize: '28px',
                        color: 'var(--accent)', lineHeight: 1, marginBottom: '6px',
                      }}>{s.n}</div>
                      <div style={{ fontSize: '12px', color: 'var(--text-soft)' }}>{s.label}</div>
                    </div>
                  ))}
                </div>
                <button className="btn btn--primary btn--lg" style={{ width: '100%' }}
                        onClick={() => setPhase('run')}>
                  Comenzar simulacro gratuito
                </button>
                <p style={{ marginTop: '12px', fontSize: '11.5px', color: 'var(--text-soft)', fontStyle: 'italic' }}>
                  Preguntas del banco real. No es material oficial del Colegio de Abogados y Abogadas de Costa Rica.
                </p>
              </div>
            )}

            {/* ━━ RUN ━━ */}
            {phase === 'run' && q && (
              <div>
                {/* Dot nav */}
                <div style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  marginBottom: '20px', gap: '10px',
                }}>
                  <div style={{ display: 'flex', gap: '5px', flex: 1 }}>
                    {questions.map((_, i) => (
                      <div key={i} style={{
                        width: '22px', height: '4px', borderRadius: '3px',
                        background: answers[questions[i].id] != null
                          ? 'var(--accent-soft)'
                          : i === idx ? 'var(--accent)' : 'var(--line-strong)',
                        transform: i === idx ? 'scaleY(1.4)' : 'none',
                        transition: 'all .15s',
                      }} />
                    ))}
                  </div>
                  <span style={{
                    fontFamily: "'IBM Plex Mono',monospace", fontSize: '11px',
                    color: 'var(--text-soft)', flexShrink: 0,
                  }}>
                    {Object.keys(answers).length}/{total}
                  </span>
                </div>

                {/* Badges */}
                <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap', marginBottom: '12px' }}>
                  <span style={{
                    padding: '3px 10px', borderRadius: '20px', fontSize: '12px', fontWeight: 500,
                    background: 'var(--bg-elev)', border: '1px solid var(--line)', color: 'var(--text-soft)',
                  }}>{q.materia}</span>
                </div>

                {/* Question card */}
                <div style={{
                  padding: '18px 20px', background: 'var(--bg-elev)',
                  border: '1px solid var(--line)', borderRadius: '10px', marginBottom: '14px',
                }}>
                  <p style={{ fontSize: '15px', lineHeight: 1.65, color: 'var(--text)', margin: 0 }}>
                    {q.enunciado}
                  </p>
                </div>

                {/* Options */}
                <div style={{ display: 'flex', flexDirection: 'column', gap: '9px', marginBottom: '14px' }}>
                  {(optionOrders[q.id] || []).map((key, i) => (
                    <button
                      key={key}
                      onClick={() => handleSelect(key)}
                      style={{
                        display: 'flex', alignItems: 'flex-start', gap: '0', textAlign: 'left',
                        width: '100%', padding: '13px 16px', borderRadius: '10px',
                        border: `1px solid ${optBorder(key)}`,
                        background: optBg(key), color: optColor(key),
                        cursor: answered ? 'default' : 'pointer',
                        fontSize: '14px', lineHeight: '1.55', fontFamily: 'inherit',
                        transition: 'all .14s',
                        opacity: answered && key !== q.respuesta_correcta && key !== selectedKey ? 0.55 : 1,
                      }}
                    >
                      <span style={{ fontWeight: 600, marginRight: '10px', flexShrink: 0 }}>
                        {LETTERS[i]}.
                      </span>
                      <span>{q.opciones[key]}</span>
                    </button>
                  ))}
                </div>

                {/* Feedback (shown immediately after selecting) */}
                {answered && (
                  <div style={{
                    padding: '18px 20px', borderRadius: '10px',
                    background: isCorrect ? '#f0fdf4' : '#fef2f2',
                    border: `1px solid ${isCorrect ? '#86efac' : '#fca5a5'}`,
                  }}>
                    {/* Badge */}
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px', flexWrap: 'wrap' }}>
                      <span style={{
                        display: 'inline-flex', alignItems: 'center',
                        padding: '3px 12px', borderRadius: '20px', fontSize: '12.5px', fontWeight: 700,
                        background: isCorrect ? '#22c55e' : '#ef4444', color: '#fff',
                      }}>{isCorrect ? '✓ Correcto' : '✕ Incorrecto'}</span>
                      {!isCorrect && (
                        <span style={{ fontSize: '13px', color: '#1f2937' }}>
                          Respuesta correcta:{' '}
                          <strong>
                            {correctVisualLabel}. {q.opciones[q.respuesta_correcta]}
                          </strong>
                        </span>
                      )}
                    </div>

                    {/* Justification */}
                    {q.explicacion && (
                      <p style={{
                        fontSize: '13.5px', lineHeight: 1.65, color: '#374151',
                        marginBottom: q.ley ? '14px' : '0',
                      }}>
                        {remapExplicacionLetters(q.explicacion, shuffledOrder)}
                      </p>
                    )}

                    {/* Law link + article badges */}
                    {q.ley && (
                      <div style={{
                        display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap',
                        paddingTop: '12px', paddingBottom: '4px',
                        borderTop: '1px solid rgba(0,0,0,.08)',
                      }}>
                        {!q.ley.includes('Antología') && (
                          <a
                            href={sinaleviUrl(q.ley)} target="_blank" rel="noopener noreferrer"
                            style={{
                              fontSize: '12.5px', color: 'var(--accent)',
                              textDecoration: 'none', fontWeight: 500,
                            }}
                            onClick={(e) => e.stopPropagation()}
                          >
                            {q.ley} ↗
                          </a>
                        )}
                        {q.ley.includes('Antología') ? (
                          q.articulo && (
                            <button
                              onClick={() => openArticleModal(q.ley, q.articulo, q.fuente_url)}
                              style={{
                                fontFamily: "'IBM Plex Mono',monospace", fontSize: '11px',
                                padding: '2px 8px', borderRadius: '4px', cursor: 'pointer',
                                border: '1px solid', borderColor: '#fcd34d',
                                background: '#fffbeb', color: '#b45309',
                                transition: 'all .12s',
                              }}
                            >
                              {q.articulo} 📄
                            </button>
                          )
                        ) : (
                          parseArticulos(q.articulo).map(art => (
                            <button
                              key={art}
                              onClick={() => openArticleModal(q.ley, art)}
                              style={{
                                fontFamily: "'IBM Plex Mono',monospace", fontSize: '11px',
                                padding: '2px 8px', borderRadius: '4px', cursor: 'pointer',
                                border: '1px solid', borderColor: 'var(--line-strong)',
                                background: 'var(--bg-elev)', color: 'var(--accent)',
                                transition: 'all .12s',
                              }}
                            >
                              Art. {art} 📄
                            </button>
                          ))
                        )}
                      </div>
                    )}

                    {/* Next button */}
                    <button
                      onClick={handleNext}
                      style={{
                        width: '100%', marginTop: '16px', padding: '14px',
                        background: 'var(--btn-bg)', color: 'var(--btn-fg)',
                        border: 'none', borderRadius: '8px', cursor: 'pointer',
                        fontSize: '15px', fontWeight: 600, fontFamily: 'inherit',
                        letterSpacing: '.02em', transition: 'opacity .15s',
                      }}
                    >
                      {idx < total - 1 ? 'Siguiente pregunta' : 'Ver mis resultados'}
                    </button>
                  </div>
                )}
              </div>
            )}

            {/* ━━ DONE ━━ */}
            {phase === 'done' && (
              <div>
                {/* Score */}
                <div style={{ display: 'flex', gap: '22px', alignItems: 'center', marginBottom: '26px', flexWrap: 'wrap' }}>
                  <div style={{
                    width: 108, height: 108, borderRadius: '50%', flexShrink: 0,
                    background: `conic-gradient(var(--accent) ${score * 3.6}deg, var(--line) 0deg)`,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    <div style={{
                      width: 86, height: 86, borderRadius: '50%', background: 'var(--bg)',
                      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: '1px',
                    }}>
                      <span style={{ fontFamily: 'var(--font-display)', fontSize: '32px', lineHeight: 1, color: 'var(--text)' }}>
                        {score}<span style={{ fontSize: '15px', color: 'var(--text-soft)' }}>%</span>
                      </span>
                      <span style={{ fontFamily: "'IBM Plex Mono',monospace", fontSize: '8.5px', color: 'var(--text-soft)', letterSpacing: '.1em' }}>PUNTAJE</span>
                    </div>
                  </div>
                  <div style={{ flex: 1, minWidth: '200px' }}>
                    <h2 style={{ fontFamily: 'var(--font-display)', fontSize: '23px', lineHeight: 1.1, marginBottom: '9px' }}>
                      {score >= 70 ? '¡Buen resultado!' : 'Seguí practicando'}
                    </h2>
                    <p style={{ fontSize: '14.5px', color: 'var(--text-soft)', lineHeight: 1.55 }}>
                      Acertaste{' '}
                      <strong style={{ color: 'var(--text)' }}>{correctCount} de {total}</strong>{' '}
                      preguntas.{' '}
                      {score >= 70
                        ? 'Estás por encima del estándar de aprobación.'
                        : 'Con práctica constante mejorarás tu resultado.'}
                    </p>
                  </div>
                </div>

                {/* CTA */}
                <div style={{
                  padding: '22px 24px', borderRadius: '10px', marginBottom: '26px',
                  background: 'var(--brand)', color: 'var(--on-brand)',
                  position: 'relative', overflow: 'hidden',
                }}>
                  <div style={{
                    position: 'absolute', inset: 0, pointerEvents: 'none',
                    background: 'radial-gradient(400px 200px at 90% -20%,color-mix(in oklab,var(--accent) 25%,transparent),transparent 70%)',
                  }} />
                  <div style={{ position: 'relative', zIndex: 1 }}>
                    <div className="mono" style={{ color: 'var(--accent-soft)', marginBottom: '8px', fontSize: '10px' }}>
                      ACCESO COMPLETO
                    </div>
                    <p style={{ fontSize: '14.5px', lineHeight: 1.6, marginBottom: '18px', color: 'color-mix(in oklab,var(--on-brand) 85%,transparent)' }}>
                      Esta fue una muestra de <strong style={{ color: 'var(--on-brand)' }}>{total} preguntas</strong>.
                      En la plataforma tenés acceso a más de{' '}
                      <strong style={{ color: 'var(--on-brand)' }}>{bankTotal ? bankTotal.toLocaleString('es-CR') : '1 900'} preguntas</strong> reales
                      en las {materiaCount || 8} materias, con artículos de ley consultables, simulacros cronometrados
                      y diagnóstico por materia.
                    </p>
                    <a href="/register" className="btn" style={{
                      display: 'flex', justifyContent: 'center',
                      background: 'var(--accent)', color: '#11243C',
                      fontSize: '16px', padding: '14px 22px', width: '100%',
                    }}>
                      Crear mi cuenta gratis →
                    </a>
                  </div>
                </div>

                {/* Review */}
                <div className="mono" style={{ fontSize: '10px', marginBottom: '12px' }}>REVISIÓN DE RESPUESTAS</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: '9px' }}>
                  {questions.map((q2, i) => {
                    const ok = answers[q2.id] === q2.respuesta_correcta;
                    const order2 = optionOrders[q2.id] || LETTERS;
                    const correctLabel2 = LETTERS[order2.indexOf(q2.respuesta_correcta)] ?? q2.respuesta_correcta;
                    return (
                      <div key={i} style={{
                        padding: '14px 16px', borderRadius: '8px', background: 'var(--bg-elev)',
                        border: '1px solid', borderLeftWidth: '3px',
                        borderColor: ok ? '#22c55e' : '#ef4444',
                      }}>
                        <div style={{ display: 'flex', gap: '10px', alignItems: 'flex-start' }}>
                          <span style={{
                            flexShrink: 0, width: 20, height: 20, borderRadius: '50%',
                            display: 'flex', alignItems: 'center', justifyContent: 'center',
                            background: ok ? '#22c55e' : '#ef4444', color: '#fff',
                            fontSize: '11px', marginTop: '1px',
                          }}>{ok ? '✓' : '✕'}</span>
                          <div style={{ flex: 1, minWidth: 0 }}>
                            <div className="mono" style={{ fontSize: '9px', marginBottom: '4px' }}>{q2.materia}</div>
                            <div style={{ fontSize: '13px', fontWeight: 600, color: 'var(--text)', lineHeight: 1.4, marginBottom: '6px' }}>
                              {q2.enunciado.length > 120 ? q2.enunciado.slice(0, 120) + '…' : q2.enunciado}
                            </div>
                            <div style={{ fontSize: '12.5px', color: 'var(--text-soft)' }}>
                              Correcto: <strong style={{ color: 'var(--text)' }}>
                                {correctLabel2}. {q2.opciones[q2.respuesta_correcta]}
                              </strong>
                            </div>
                            {q2.ley && (
                              <div style={{ marginTop: '6px', display: 'flex', gap: '6px', flexWrap: 'wrap', alignItems: 'center' }}>
                                <span style={{ fontFamily: "'IBM Plex Mono',monospace", fontSize: '9.5px', color: 'var(--accent)', textTransform: 'uppercase', letterSpacing: '.06em' }}>{q2.ley}</span>
                                {q2.articulo && (
                                  <button
                                    onClick={() => openArticleModal(q2.ley, parseArticulos(q2.articulo)[0] || q2.articulo, q2.fuente_url)}
                                    style={{
                                      fontFamily: "'IBM Plex Mono',monospace", fontSize: '9.5px',
                                      padding: '1px 6px', border: '1px solid var(--line-strong)',
                                      borderRadius: '3px', background: 'var(--bg)', color: 'var(--accent)',
                                      cursor: 'pointer',
                                    }}
                                  >
                                    Art. {q2.ley.includes('Antología') ? q2.articulo : (parseArticulos(q2.articulo)[0] || q2.articulo)} 📄
                                  </button>
                                )}
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>

                <div style={{ display: 'flex', gap: '10px', marginTop: '20px' }}>
                  <button className="btn btn--outline" onClick={handleReset} style={{ flex: 1 }}>Reintentar</button>
                  <button className="btn btn--ghost" onClick={onClose} style={{ flex: 1 }}>Cerrar</button>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Article modal rendered outside the exam card */}
      {articleModal && (
        articleModal.antologia ? (
          <PdfSourcePopup
            ley={articleModal.ley}
            pagina={articleModal.articulo}
            fragmento={articleModal.fragmento || ''}
            onClose={() => setArticleModal(null)}
          />
        ) : (
          <ArticlePopup
            ley={articleModal.ley}
            articulo={articleModal.articulo}
            onClose={() => setArticleModal(null)}
          />
        )
      )}
    </>
  );
}

Object.assign(window, { DemoExam });
