/* play.jsx — the learner's playable gamified course experience */

const TOTAL_LIVES = 3;
const QTIME = 22; // seconds per question

function HexPip({ filled }) {
  return (
    <div className="hex-flat" style={{ width: 20, height: 22, clipPath: "polygon(50% 0,93% 25%,93% 75%,50% 100%,7% 75%,7% 25%)",
      background: filled ? "var(--vh-orange)" : "var(--surface-3)", display: "grid", placeItems: "center" }}>
      <Icon name="heart" size={11} style={{ color: filled ? "#fff" : "var(--ink-3)" }} />
    </div>
  );
}

function PlayGame({ course, back, toast }) {
  const bank = QUIZ_BANK;
  const N = bank.length;
  const [stage, setStage] = useState("intro"); // intro | quiz | done
  const [qi, setQi] = useState(0);
  const [pick, setPick] = useState(null);
  const [lives, setLives] = useState(TOTAL_LIVES);
  const [xp, setXp] = useState(0);
  const [combo, setCombo] = useState(0);
  const [maxCombo, setMaxCombo] = useState(0);
  const [correct, setCorrect] = useState(0);
  const [time, setTime] = useState(QTIME);
  const [pop, setPop] = useState(null); // floating +xp
  const timerRef = useRef(null);

  const q = bank[qi];
  const answered = pick !== null;

  /* countdown */
  useEffect(() => {
    if (stage !== "quiz" || answered) return;
    setTime(QTIME);
    timerRef.current = setInterval(() => {
      setTime(t => {
        if (t <= 1) { clearInterval(timerRef.current); handleAnswer(-1); return 0; }
        return t - 1;
      });
    }, 1000);
    return () => clearInterval(timerRef.current);
  }, [qi, stage]);

  function handleAnswer(idx) {
    if (pick !== null) return;
    clearInterval(timerRef.current);
    setPick(idx);
    const right = idx === q.answer;
    if (right) {
      const gained = 40 + combo * 15 + Math.round((time / QTIME) * 30);
      setXp(x => x + gained);
      setCombo(c => { const n = c + 1; setMaxCombo(m => Math.max(m, n)); return n; });
      setCorrect(c => c + 1);
      setPop({ v: "+" + gained, ok: true, key: Date.now() });
    } else {
      setLives(l => l - 1);
      setCombo(0);
      setPop({ v: idx === -1 ? "Time!" : "Miss", ok: false, key: Date.now() });
    }
    setTimeout(() => {
      const outOfLives = !right && lives - 1 <= 0;
      if (qi + 1 >= N || outOfLives) { setStage("done"); }
      else { setQi(i => i + 1); setPick(null); }
    }, right ? 1100 : 1700);
  }

  /* ---- intro ---- */
  if (stage === "intro") {
    return (
      <div className="vh-in" style={{ maxWidth: 720, margin: "0 auto" }}>
        <button className="btn btn-ghost" onClick={back} style={{ marginBottom: 18 }}><Icon name="chevL" size={16} />Exit game</button>
        <div className="card" style={{ padding: 0, overflow: "hidden", textAlign: "center" }}>
          <div style={{ padding: "44px 32px 36px", position: "relative", background: `linear-gradient(135deg, ${course.color}, color-mix(in oklab, ${course.color}, #0b1c3a 58%))`, color: "#fff" }}>
            <div className="hexfield" style={{ opacity: .4 }} />
            <div style={{ position: "relative" }}>
              <div className="hex-flat" style={{ width: 88, height: 96, margin: "0 auto 18px", clipPath: "polygon(50% 0,93% 25%,93% 75%,50% 100%,7% 75%,7% 25%)", background: "rgba(255,255,255,.16)", display: "grid", placeItems: "center" }}>
                <Icon name="dice" size={44} style={{ color: "#fff" }} />
              </div>
              <div className="eyebrow" style={{ color: "rgba(255,255,255,.85)" }}>Gamified course</div>
              <h1 style={{ fontSize: 30, fontWeight: 700, color: "#fff", marginTop: 6 }}>{course.title}</h1>
              <p style={{ color: "rgba(255,255,255,.85)", fontSize: 15, marginTop: 8 }}>Answer fast, keep your combo, protect your lives.</p>
            </div>
          </div>
          <div style={{ padding: "26px 32px 30px" }}>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 14, marginBottom: 24 }}>
              {[["target", N + " questions", "from your slides"], ["heart", TOTAL_LIVES + " lives", "don't run out"], ["bolt", "Combo XP", "speed + streak bonus"]].map(([ic, a, b]) => (
                <div key={a} style={{ padding: "16px 12px", borderRadius: 14, background: "var(--surface-2)", border: "1px solid var(--line)" }}>
                  <Icon name={ic} size={22} style={{ color: "var(--accent)" }} />
                  <div style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 15, marginTop: 7 }}>{a}</div>
                  <div className="dim" style={{ fontSize: 12 }}>{b}</div>
                </div>
              ))}
            </div>
            <button className="btn btn-acc" style={{ width: "100%", fontSize: 16, padding: "15px" }} onClick={() => setStage("quiz")}><Icon name="play" size={19} />Start playing</button>
          </div>
        </div>
      </div>
    );
  }

  /* ---- results ---- */
  if (stage === "done") {
    const acc = Math.round((correct / N) * 100);
    const passed = correct >= Math.ceil(N * 0.6);
    return (
      <div className="vh-in" style={{ maxWidth: 660, margin: "0 auto" }}>
        <div className="card" style={{ padding: 0, overflow: "hidden", textAlign: "center" }}>
          <div style={{ padding: "40px 32px 30px", position: "relative", background: passed ? "linear-gradient(135deg,var(--vh-blue-500),var(--vh-navy))" : "linear-gradient(135deg,#5a6b86,#384358)", color: "#fff" }}>
            <div className="hexfield" style={{ opacity: .35 }} />
            <div style={{ position: "relative" }}>
              <div className="hex-flat" style={{ width: 92, height: 100, margin: "0 auto 16px", clipPath: "polygon(50% 0,93% 25%,93% 75%,50% 100%,7% 75%,7% 25%)", background: "var(--accent)", display: "grid", placeItems: "center" }}>
                <Icon name={passed ? "trophy" : "flag"} size={46} style={{ color: "#231f20" }} />
              </div>
              <h1 style={{ fontSize: 28, fontWeight: 700, color: "#fff" }}>{passed ? "Level cleared!" : "Good effort!"}</h1>
              <p style={{ color: "rgba(255,255,255,.85)", fontSize: 15, marginTop: 6 }}>{passed ? "You earned a new badge and moved up the board." : "Replay to clear the level and earn the badge."}</p>
            </div>
          </div>
          <div style={{ padding: "26px 32px 30px" }}>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 14, marginBottom: 22 }}>
              {[["XP earned", xp.toLocaleString(), "bolt"], ["Accuracy", acc + "%", "target"], ["Best combo", "×" + maxCombo, "flame"]].map(([k, v, ic]) => (
                <div key={k} style={{ padding: "18px 12px", borderRadius: 14, background: "var(--vh-blue-50)" }}>
                  <Icon name={ic} size={20} style={{ color: "var(--vh-blue-500)" }} />
                  <div className="kpi" style={{ fontSize: 26, marginTop: 6 }}>{v}</div>
                  <div className="dim" style={{ fontSize: 11.5, fontWeight: 600, textTransform: "uppercase", letterSpacing: ".05em" }}>{k}</div>
                </div>
              ))}
            </div>
            {passed && (
              <div style={{ display: "flex", alignItems: "center", gap: 13, padding: 15, borderRadius: 14, background: "var(--accent-soft)", marginBottom: 22, textAlign: "left" }}>
                <Badge icon="target" size={50} color="var(--vh-teal)" ink="#fff" style="hex" />
                <div><div style={{ fontWeight: 700, fontFamily: "var(--display)" }}>Badge unlocked — Quiz Ace</div><div className="muted" style={{ fontSize: 13 }}>Scored {acc}% on a gamified course</div></div>
              </div>
            )}
            <div style={{ display: "flex", gap: 12 }}>
              <button className="btn btn-ghost" style={{ flex: 1 }} onClick={() => { setStage("intro"); setQi(0); setPick(null); setLives(TOTAL_LIVES); setXp(0); setCombo(0); setMaxCombo(0); setCorrect(0); }}><Icon name="refresh" size={16} />Play again</button>
              <button className="btn btn-pri" style={{ flex: 1 }} onClick={back}>Back to course<Icon name="arrowR" size={16} /></button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  /* ---- quiz HUD ---- */
  const timePct = (time / QTIME) * 100;
  return (
    <div className="vh-in" style={{ maxWidth: 760, margin: "0 auto" }}>
      {/* HUD */}
      <div className="between" style={{ marginBottom: 14, flexWrap: "wrap", gap: 12 }}>
        <button className="btn btn-ghost" onClick={back}><Icon name="x" size={16} />Exit</button>
        <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
          <div style={{ display: "flex", gap: 5 }}>{Array.from({ length: TOTAL_LIVES }).map((_, i) => <HexPip key={i} filled={i < lives} />)}</div>
          {combo >= 2 && <span className="tag accent" style={{ fontWeight: 800 }}><Icon name="flame" size={14} />Combo ×{combo}</span>}
          <Points value={xp} pointsStyle="solid" icon="bolt" />
        </div>
      </div>

      {/* progress dots */}
      <div style={{ display: "flex", gap: 6, marginBottom: 18 }}>
        {bank.map((_, i) => (
          <div key={i} style={{ flex: 1, height: 6, borderRadius: 9, background: i < qi ? "var(--vh-teal)" : i === qi ? "var(--accent)" : "var(--surface-3)" }} />
        ))}
      </div>

      {/* timer */}
      <div className="between" style={{ marginBottom: 16 }}>
        <span className="dim" style={{ fontSize: 13, fontWeight: 700, fontFamily: "var(--display)" }}>Question {qi + 1} of {N}</span>
        <span style={{ display: "flex", alignItems: "center", gap: 7, fontFamily: "var(--display)", fontWeight: 700, fontSize: 14, color: time <= 6 ? "var(--vh-orange)" : "var(--ink-2)" }}>
          <Icon name="clock" size={16} />{time}s
        </span>
      </div>
      <div className="bar" style={{ marginBottom: 22, height: 7 }}><i style={{ width: timePct + "%", background: time <= 6 ? "var(--vh-orange)" : "linear-gradient(90deg,var(--vh-blue-400),var(--vh-blue-500))", transition: "width 1s linear" }} /></div>

      {/* question card */}
      <div className="card" style={{ padding: 28, position: "relative" }}>
        {pop && <FloatPop key={pop.key} pop={pop} onDone={() => setPop(null)} />}
        <span className="tag accent" style={{ fontSize: 11, marginBottom: 14 }}><Icon name="pptx" size={12} />Slide {q.slide}</span>
        <h2 style={{ fontSize: 22, fontWeight: 600, margin: "14px 0 22px", lineHeight: 1.3 }}>{q.q}</h2>
        <div style={{ display: "grid", gap: 11 }}>
          {q.options.map((o, i) => {
            let bd = "var(--line)", bg = "var(--surface)", ico = null, col = "var(--ink)";
            if (answered && i === q.answer) { bd = "var(--vh-teal)"; bg = "color-mix(in oklab,var(--vh-teal),transparent 88%)"; ico = "checkCircle"; }
            else if (answered && i === pick) { bd = "var(--vh-orange)"; bg = "color-mix(in oklab,var(--vh-orange),transparent 88%)"; ico = "x"; }
            else if (answered) { col = "var(--ink-3)"; }
            return (
              <button key={i} disabled={answered} onClick={() => handleAnswer(i)}
                style={{ textAlign: "left", padding: "15px 17px", borderRadius: 13, border: "1.5px solid " + bd, background: bg, color: col, display: "flex", alignItems: "center", gap: 13, fontSize: 15, fontWeight: 500, cursor: answered ? "default" : "pointer", transition: "all .14s" }}>
                <span style={{ width: 30, height: 30, borderRadius: 9, flex: "none", display: "grid", placeItems: "center", fontFamily: "var(--display)", fontWeight: 700, fontSize: 14, background: "var(--surface-3)", color: "var(--ink-2)" }}>{"ABCD"[i]}</span>
                <span style={{ flex: 1 }}>{o}</span>
                {ico && <Icon name={ico} size={22} style={{ color: i === q.answer ? "var(--vh-teal)" : "var(--vh-orange)" }} />}
              </button>
            );
          })}
        </div>
        {answered && (
          <div className="vh-in" style={{ marginTop: 18, padding: "13px 16px", borderRadius: 12, background: "var(--vh-blue-50)", fontSize: 14, display: "flex", gap: 10 }}>
            <Icon name="sparkle" size={18} style={{ color: "var(--vh-blue-500)", flex: "none", marginTop: 1 }} />
            <span className="muted">{q.why}</span>
          </div>
        )}
      </div>
    </div>
  );
}

function FloatPop({ pop, onDone }) {
  useEffect(() => { const t = setTimeout(onDone, 1000); return () => clearTimeout(t); }, []);
  return (
    <div style={{ position: "absolute", top: 18, right: 22, fontFamily: "var(--display)", fontWeight: 800, fontSize: 26,
      color: pop.ok ? "var(--vh-teal)" : "var(--vh-orange)", animation: "vhFloat 1s ease both", pointerEvents: "none" }}>
      {pop.v}
    </div>
  );
}

Object.assign(window, { PlayGame });
