// simulator.jsx — prototipo funcional del simulacro de examen

const { useState, useEffect, useRef, useCallback } = React;

function fmt(t) {
  const m = Math.floor(t / 60).toString().padStart(2, "0");
  const s = Math.floor(t % 60).toString().padStart(2, "0");
  return `${m}:${s}`;
}

function Simulator({ open, onClose, questions, secondsPerQ = 75 }) {
  const total = questions.length;
  const totalTime = total * secondsPerQ;
  const [phase, setPhase] = useState("intro"); // intro | run | done
  const [idx, setIdx] = useState(0);
  const [answers, setAnswers] = useState(() => Array(total).fill(null));
  const [time, setTime] = useState(totalTime);
  const tick = useRef(null);

  const reset = useCallback(() => {
    setPhase("intro"); setIdx(0);
    setAnswers(Array(total).fill(null)); setTime(totalTime);
  }, [total, totalTime]);

  // bloquear scroll del fondo cuando está abierto
  useEffect(() => {
    if (open) document.body.style.overflow = "hidden";
    else document.body.style.overflow = "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  // temporizador
  useEffect(() => {
    if (phase !== "run") return;
    tick.current = setInterval(() => {
      setTime((t) => {
        if (t <= 1) { clearInterval(tick.current); setPhase("done"); return 0; }
        return t - 1;
      });
    }, 1000);
    return () => clearInterval(tick.current);
  }, [phase]);

  // teclado: Esc cierra, flechas navegan
  useEffect(() => {
    if (!open) return;
    const h = (e) => {
      if (e.key === "Escape") onClose();
      if (phase === "run") {
        if (e.key === "ArrowRight" && idx < total - 1) setIdx(idx + 1);
        if (e.key === "ArrowLeft" && idx > 0) setIdx(idx - 1);
      }
    };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [open, phase, idx, total, onClose]);

  if (!open) return null;

  const choose = (qi, oi) => {
    setAnswers((a) => { const n = [...a]; n[qi] = oi; return n; });
  };

  const correctCount = answers.reduce(
    (acc, a, i) => acc + (a === questions[i].correct ? 1 : 0), 0);
  const score = Math.round((correctCount / total) * 100);
  const answeredCount = answers.filter((a) => a !== null).length;
  const lowTime = time <= 30 && phase === "run";

  return (
    <div className="sim" role="dialog" aria-modal="true"
         onMouseDown={(e) => { if (e.target === e.currentTarget && phase !== "run") onClose(); }}>
      <div className="sim__card">

        {/* Encabezado */}
        <div className="sim__bar">
          <div className="sim__brand">
            <span className="sim__mark" />
            <span>Excelencia Legal CR · Simulacro</span>
          </div>
          {phase === "run" && (
            <div className={"sim__timer" + (lowTime ? " sim__timer--low" : "")}>
              <span className="sim__timerDot" />
              {fmt(time)}
            </div>
          )}
          <button className="sim__close" onClick={onClose} aria-label="Cerrar">✕</button>
        </div>

        {/* INTRO */}
        {phase === "intro" && (
          <div className="sim__intro">
            <div className="sim__introEyebrow mono">SIMULACRO DE DEMOSTRACIÓN · GRATUITO</div>
            <h2 className="sim__introTitle">Examen de incorporación · muestra real</h2>
            <p className="sim__introSub">
              {total} preguntas tipo examen, 2 por cada materia evaluada.
              Tendrás <strong>{fmt(totalTime)}</strong> en el cronómetro, igual que en la prueba real.
              Al finalizar verás la respuesta correcta, la justificación y el artículo que la fundamenta.
            </p>
            <div className="sim__introGrid">
              <div className="sim__introItem"><span className="sim__introNum">{total}</span><span>preguntas</span></div>
              <div className="sim__introItem"><span className="sim__introNum">{fmt(totalTime)}</span><span>tiempo total</span></div>
              <div className="sim__introItem"><span className="sim__introNum">7</span><span>materias</span></div>
            </div>
            <button className="btn btn--primary btn--lg" onClick={() => setPhase("run")}>
              Comenzar simulacro gratuito
            </button>
            <p className="sim__introNote">Contenido con fines de práctica. No es material oficial del Colegio de Abogados.</p>
          </div>
        )}

        {/* RUN */}
        {phase === "run" && (() => {
          const q = questions[idx];
          return (
            <div className="sim__run">
              <div className="sim__progress">
                <div className="sim__dots">
                  {questions.map((_, i) => (
                    <button key={i}
                      className={"sim__dot" +
                        (i === idx ? " sim__dot--active" : "") +
                        (answers[i] !== null ? " sim__dot--done" : "")}
                      onClick={() => setIdx(i)} aria-label={`Ir a la pregunta ${i + 1}`} />
                  ))}
                </div>
                <span className="sim__count">Pregunta {idx + 1} / {total}</span>
              </div>

              <div className="sim__qsubject mono">{q.subject}</div>
              <h3 className="sim__qtext">{q.text}</h3>

              <div className="sim__options">
                {q.options.map((opt, oi) => (
                  <button key={oi}
                    className={"sim__opt" + (answers[idx] === oi ? " sim__opt--sel" : "")}
                    onClick={() => choose(idx, oi)}>
                    <span className="sim__optLetter">{String.fromCharCode(65 + oi)}</span>
                    <span>{opt}</span>
                  </button>
                ))}
              </div>

              <div className="sim__nav">
                <button className="btn btn--ghost" disabled={idx === 0}
                        onClick={() => setIdx(idx - 1)}>Anterior</button>
                <span className="sim__navMeta">{answeredCount} de {total} respondidas</span>
                {idx < total - 1
                  ? <button className="btn btn--primary" onClick={() => setIdx(idx + 1)}>Siguiente</button>
                  : <button className="btn btn--primary" onClick={() => setPhase("done")}>Finalizar</button>}
              </div>
            </div>
          );
        })()}

        {/* DONE */}
        {phase === "done" && (
          <div className="sim__done">
            <div className="sim__scoreWrap">
              <div className="sim__scoreRing" style={{
                background: `conic-gradient(var(--accent) ${score * 3.6}deg, var(--line) 0deg)`,
              }}>
                <div className="sim__scoreInner">
                  <span className="sim__scoreNum">{score}<span className="sim__scorePct">%</span></span>
                  <span className="sim__scoreLbl mono">PUNTAJE</span>
                </div>
              </div>
              <div className="sim__scoreText">
                <h2 className="sim__introTitle">{score >= 70 ? "¡Vas por buen camino!" : "Buen comienzo"}</h2>
                <p className="sim__introSub">
                  Acertaste <strong>{correctCount} de {total}</strong> preguntas en esta muestra.
                  {score >= 70
                    ? " Estás por encima del estándar de aprobación."
                    : " Repasa la fundamentación y vuelve a intentarlo."}
                </p>
                <div style={{
                  marginTop: "20px", padding: "20px 22px", borderRadius: "10px",
                  background: "var(--bg-alt)", border: "1px solid var(--line)",
                }}>
                  <div className="mono" style={{ marginBottom: "8px", fontSize: "10px" }}>ACCESO COMPLETO</div>
                  <p style={{ fontSize: "14.5px", color: "var(--text-soft)", lineHeight: 1.55, marginBottom: "16px" }}>
                    En la plataforma tenés acceso a <strong style={{ color: "var(--text)" }}>+1 900 preguntas</strong> en las 8 materias,
                    simulacros completos cronometrados y tu diagnóstico detallado por materia.
                  </p>
                  <a href="/register" className="btn btn--primary" style={{ width: "100%", justifyContent: "center" }}>
                    Crear mi cuenta gratis
                  </a>
                </div>
                <div className="sim__doneBtns">
                  <button className="btn btn--ghost" onClick={reset}>Reintentar muestra</button>
                  <button className="btn btn--ghost" onClick={onClose}>Cerrar</button>
                </div>
              </div>
            </div>

            <div className="sim__review">
              {questions.map((q, i) => {
                const ok = answers[i] === q.correct;
                return (
                  <div key={i} className={"sim__rev" + (ok ? " sim__rev--ok" : " sim__rev--no")}>
                    <div className="sim__revTop">
                      <span className={"sim__revBadge" + (ok ? " sim__revBadge--ok" : " sim__revBadge--no")}>
                        {ok ? "✓" : "✕"}
                      </span>
                      <div>
                        <div className="sim__revSubject mono">{q.subject}</div>
                        <div className="sim__revQ">{q.text}</div>
                      </div>
                    </div>
                    <div className="sim__revAns">
                      Respuesta correcta: <strong>{String.fromCharCode(65 + q.correct)}. {q.options[q.correct]}</strong>
                    </div>
                    <div className="sim__revRat">{q.rationale}</div>
                    {q.law && (
                      <div style={{ marginTop: "10px", display: "flex", alignItems: "center", gap: "8px", flexWrap: "wrap" }}>
                        <span style={{
                          fontFamily: "'IBM Plex Mono', monospace", fontSize: "10.5px",
                          letterSpacing: ".12em", textTransform: "uppercase",
                          color: "var(--accent)", opacity: 0.85,
                        }}>{q.law}</span>
                        {q.article && (
                          <span style={{
                            fontFamily: "'IBM Plex Mono', monospace", fontSize: "10.5px",
                            padding: "2px 7px", borderRadius: "4px",
                            border: "1px solid var(--line-strong)", color: "var(--text-soft)",
                          }}>Art. {q.article}</span>
                        )}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Simulator });
