(() => {
  const $ = (sel) => document.querySelector(sel);
  const screens = {
    start: $("#screen-start"),
    quiz: $("#screen-quiz"),
    result: $("#screen-result"),
  };

  const btnStart = $("#btnStart");
  const btnExit = $("#btnExit");
  const btnQuit = $("#btnQuit");
  const btnReplay = $("#btnReplay");
  const btnToTitle = $("#btnToTitle");
  const progress = $("#progress");
  const scoreEl = $("#score");
  const questionEl = $("#question");
  const questionModeLabel = $("#questionModeLabel");
  const choicesEl = $("#choices");
  const resultTitle = $("#resultTitle");
  const resultText = $("#resultText");
  const storyHint = $("#storyHint");
  const popup = $("#popup");
  const popupVideo = $("#popupVideo");
  const popupClose = $("#popupClose");
  const toast = $("#toast");
  const bgmEl = document.getElementById("bgm");

  const popupCard = popup.querySelector(".popup-card");
  const popupImg = document.createElement("img");
  popupImg.id = "popupImg";
  popupImg.alt = "popup image";
  popupImg.style.width = "100%";
  popupImg.style.height = "auto";
  popupImg.style.maxHeight = "calc(80vh - 52px)";
  popupImg.style.borderRadius = "12px";
  popupImg.style.display = "none";
  popupCard.appendChild(popupImg);

  const introNext = document.createElement("button");
  introNext.textContent = "次へ";
  introNext.style.position = "absolute";
  introNext.style.right = "18px";
  introNext.style.bottom = "18px";
  introNext.style.padding = "10px 14px";
  introNext.style.border = "none";
  introNext.style.borderRadius = "12px";
  introNext.style.background = "rgba(0,0,0,0.65)";
  introNext.style.color = "#fff";
  introNext.style.fontWeight = "700";
  introNext.style.cursor = "pointer";
  introNext.style.display = "none";
  popupCard.appendChild(introNext);

  const playOverlay = document.createElement("button");
  playOverlay.type = "button";
  playOverlay.textContent = "▶ 再生";
  playOverlay.style.position = "absolute";
  playOverlay.style.left = "50%";
  playOverlay.style.top = "50%";
  playOverlay.style.transform = "translate(-50%, -50%)";
  playOverlay.style.padding = "14px 18px";
  playOverlay.style.fontSize = "18px";
  playOverlay.style.borderRadius = "14px";
  playOverlay.style.border = "0";
  playOverlay.style.cursor = "pointer";
  playOverlay.style.boxShadow = "0 10px 24px rgba(0,0,0,.35)";
  playOverlay.style.display = "none";
  playOverlay.style.zIndex = "5";
  popupCard.style.position = "relative";
  popupCard.appendChild(playOverlay);

  const state = {
    questions: Array.isArray(window.CELINE_QUESTIONS) ? window.CELINE_QUESTIONS : [],
    order: [],
    idx: 0,
    correct: 0,
    currentCorrectIndex: 0,
    locked: false,
  };
  let introCallback = null;

  const showToast = (msg) => {
    if (!toast) return;
    toast.textContent = msg;
    toast.classList.remove("hidden");
    clearTimeout(showToast._t);
    showToast._t = setTimeout(() => toast.classList.add("hidden"), 1200);
  };

  const shuffle = (arr) => {
    for (let i = arr.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [arr[i], arr[j]] = [arr[j], arr[i]];
    }
    return arr;
  };

  const setScreen = (name) => {
    Object.values(screens).forEach(s => s && s.classList.remove("active"));
    screens[name] && screens[name].classList.add("active");
  };

  const applyBgm = async () => {
    if (!bgmEl) return;
    bgmEl.volume = 0.25;
    bgmEl.loop = true;
    bgmEl.preload = "auto";
    try { await bgmEl.play(); } catch (e) {}
  };

  const tryLoadImage = (src) => new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve(src);
    img.onerror = () => reject(new Error("fail"));
    img.src = src + "?v=" + Date.now();
  });

  const setupQuizSideImage = async () => {
    const panel = document.querySelector(".quiz-image");
    if (!panel) return;
    const candidates = ["assets/quiz_side_1.png", "assets/quiz_side.png"];
    for (const src of candidates) {
      try {
        await tryLoadImage(src);
        panel.style.backgroundImage = `url("${src}?v=${Date.now()}")`;
        panel.style.backgroundSize = "cover";
        panel.style.backgroundPosition = "center";
        panel.style.backgroundRepeat = "no-repeat";
        return;
      } catch (e) {}
    }
  };

  const closeVideoPopup = () => {
    popup.classList.add("hidden");
    try { popupVideo.pause(); } catch (e) {}
    playOverlay.style.display = "none";
    introNext.style.display = "none";
    if (bgmEl && bgmEl.paused) applyBgm();
  };

  const showPopupImage = (imgSrc) => {
    try { popupVideo.pause(); } catch (e) {}
    popupVideo.style.display = "none";
    popupImg.src = imgSrc;
    popupImg.style.display = "block";
    playOverlay.style.display = "none";
    popup.classList.remove("hidden");
  };

  const showIntro = (imgSrc, onDone) => {
    popupVideo.style.display = "none";
    popupImg.src = imgSrc;
    popupImg.style.display = "block";
    playOverlay.style.display = "none";
    introNext.style.display = "inline-block";
    introCallback = onDone || null;
    popup.classList.remove("hidden");
  };

  introNext.addEventListener("click", () => {
    const cb = introCallback;
    introCallback = null;
    closeVideoPopup();
    if (cb) cb();
  });

  const showPopupVideo = (videoSrc, fallbackImgSrc) => {
    popupImg.style.display = "none";
    popupVideo.style.display = "block";
    popupVideo.pause();
    popupVideo.removeAttribute("src");
    popupVideo.load();
    popupVideo.src = videoSrc;
    popup.classList.remove("hidden");
    try { if (bgmEl) bgmEl.pause(); } catch (e) {}
    const onError = () => {
      popupVideo.removeEventListener("error", onError);
      showPopupImage(fallbackImgSrc);
    };
    popupVideo.addEventListener("error", onError);
    popupVideo.play().catch(() => {
      showToast("動画は再生ボタンで開始できます");
      playOverlay.style.display = "block";
      playOverlay.onclick = () => {
        playOverlay.style.display = "none";
        popupVideo.play().catch(() => {});
      };
    });
  };

  const renderHeader = () => {
    questionModeLabel.textContent = "ビジネス英語 Part5 体験版";
    progress.textContent = `問題 ${state.idx + 1} / 10`;
    scoreEl.textContent = `正解 ${state.correct} / 10`;
  };

  const renderQuestion = () => {
    renderHeader();
    const qIndex = state.order[state.idx];
    const q = state.questions[qIndex];
    questionEl.textContent = q.q;
    const packed = q.choices.map((t, i) => ({ t, isCorrect: i === q.a }));
    shuffle(packed);
    state.currentCorrectIndex = packed.findIndex(x => x.isCorrect);
    choicesEl.innerHTML = "";
    packed.forEach((item, i) => {
      const b = document.createElement("button");
      b.className = "choice";
      b.type = "button";
      b.textContent = item.t;
      b.addEventListener("click", () => onAnswer(i));
      choicesEl.appendChild(b);
    });
    setTimeout(setupQuizSideImage, 10);
  };

  const startGame = () => {
    if (!Array.isArray(state.questions) || state.questions.length < 10) {
      alert("問題データの読み込みに失敗しました。");
      return;
    }
    state.order = shuffle([...Array(state.questions.length).keys()]).slice(0, 10);
    state.idx = 0;
    state.correct = 0;
    state.locked = false;
    setScreen("quiz");
    renderQuestion();
  };

  const finishGame = () => {
    const passed = state.correct >= 7;
    resultTitle.textContent = passed ? "体験版クリア" : "体験版終了";
    resultText.textContent = passed
      ? `10問中 ${state.correct} 問正解。セリーヌとの個別補習は好調です。`
      : `10問中 ${state.correct} 問正解。基礎を見直してもう一度挑戦しましょう。`;
    storyHint.textContent = passed
      ? "製品版では10回の補習を通して、距離の変化とエンディング分岐を楽しめます。"
      : "製品版では問題数と補習イベントが大きく増え、合格の積み重ねで展開が変わります。";
    setScreen("result");
    showPopupVideo(passed ? "assets/reward_1.mp4" : "assets/punish.mp4", "assets/start.png");
  };

  const onAnswer = (choiceIndex) => {
    if (state.locked) return;
    state.locked = true;
    const buttons = [...choicesEl.querySelectorAll(".choice")];
    buttons.forEach((b, i) => {
      if (i === state.currentCorrectIndex) b.classList.add("correct");
      if (i === choiceIndex && i !== state.currentCorrectIndex) b.classList.add("wrong");
      b.disabled = true;
    });
    const correct = (choiceIndex === state.currentCorrectIndex);
    if (correct) state.correct += 1;
    renderHeader();
    showToast(correct ? "正解" : "不正解");
    setTimeout(() => {
      state.locked = false;
      state.idx += 1;
      if (state.idx >= 10) finishGame();
      else renderQuestion();
    }, 650);
  };

  btnStart && btnStart.addEventListener("click", async () => {
    await applyBgm();
    showIntro("assets/intro.png", startGame);
  });
  btnExit && btnExit.addEventListener("click", () => showToast("終了する場合はタブを閉じてください"));
  btnQuit && btnQuit.addEventListener("click", () => setScreen("start"));
  btnReplay && btnReplay.addEventListener("click", startGame);
  btnToTitle && btnToTitle.addEventListener("click", () => setScreen("start"));
  popupClose && popupClose.addEventListener("click", closeVideoPopup);
  const popupBackdrop = popup ? popup.querySelector(".popup-backdrop") : null;
  popupBackdrop && popupBackdrop.addEventListener("click", closeVideoPopup);
  popupVideo && popupVideo.addEventListener("ended", closeVideoPopup);
  document.addEventListener("pointerdown", () => {
    if (bgmEl && bgmEl.paused && popup.classList.contains("hidden")) applyBgm();
  }, { passive: true });
  setTimeout(setupQuizSideImage, 100);
})();
