// Debug 面板（PRD §13）：反引号 ` 开关。默认关闭，无 UI 痕迹，不影响正常游玩。
import Phaser from "phaser";
import { director } from "./director";

const SCENES = ["house", "plaza", "bakery", "store", "clinic", "lake", "field", "well", "fogwall", "white_corridor", "white_ward"];

export function setupDebug(game: Phaser.Game) {
  const panel = document.getElementById("debug-panel")!;
  let open = false;

  const activeWorld = () =>
    game.scene.getScenes(true).map(s => s.scene.key).filter(k => !["ui", "boot", "title", "dream", "ending"].includes(k));

  const stopAll = () => {
    for (const k of activeWorld()) game.scene.stop(k);
  };

  const teleport = (key: string) => {
    if (!director.playStart) return;
    director.pendingSpawn = "entry";
    stopAll();
    game.scene.stop("dream"); game.scene.stop("ending"); game.scene.stop("title");
    if (!game.scene.isActive("ui")) game.scene.start("ui");
    game.scene.start(key);
  };

  const forceEnding = (code: string) => {
    if (!director.playStart) return;
    director.endingPlayed = true;
    game.registry.set("ending", code);
    stopAll();
    game.scene.stop("ui"); game.scene.stop("dream"); game.scene.stop("title");
    game.scene.start("ending");
  };

  panel.innerHTML = `
    <h3>DEBUG</h3>
    <div class="row">状态：<span id="dbg-state"></span></div>
    <div class="row">幸福 <input id="dbg-h" type="number" min="0" max="100"/><button id="dbg-h-set">设置</button></div>
    <div class="row">觉知 <input id="dbg-a" type="number" min="0" max="100"/><button id="dbg-a-set">设置</button></div>
    <div class="row">日：${[1, 2, 3, 4, 5, 6, 7].map(d => `<button data-day="${d}">${d}</button>`).join("")}</div>
    <div class="row">传送：${SCENES.map(s => `<button data-tp="${s}">${s}</button>`).join("")}</div>
    <div class="row"><button id="dbg-clues">置齐全部线索</button></div>
    <div class="row">结局：${["E1", "E2", "E3", "E4"].map(e => `<button data-end="${e}">${e}</button>`).join("")}</div>
  `;

  panel.querySelector("#dbg-h-set")!.addEventListener("click", () => {
    director.setHappiness(Number((panel.querySelector("#dbg-h") as HTMLInputElement).value));
  });
  panel.querySelector("#dbg-a-set")!.addEventListener("click", () => {
    director.setAwareness(Number((panel.querySelector("#dbg-a") as HTMLInputElement).value));
  });
  panel.querySelectorAll("[data-day]").forEach(b => b.addEventListener("click", () => {
    director.startDay(Number((b as HTMLElement).dataset.day));
    director.pendingSpawn = "bed";
    teleport("house");
  }));
  panel.querySelectorAll("[data-tp]").forEach(b => b.addEventListener("click", () => {
    teleport((b as HTMLElement).dataset.tp!);
  }));
  panel.querySelector("#dbg-clues")!.addEventListener("click", () => {
    for (let i = 1; i <= 9; i++) director.foundClue("C" + i);
  });
  panel.querySelectorAll("[data-end]").forEach(b => b.addEventListener("click", () => {
    forceEnding((b as HTMLElement).dataset.end!);
  }));

  setInterval(() => {
    if (!open) return;
    const el = panel.querySelector("#dbg-state")!;
    el.textContent = `D${director.day} 幸福${director.happiness} 觉知${director.awareness} S${director.stage} 线索${director.clues.size}/9 逃离${director.escapes}`;
  }, 300);

  document.addEventListener("keydown", (ev) => {
    if (ev.key === "`") {
      open = !open;
      panel.style.display = open ? "block" : "none";
    }
  });
}
