// 标题画面：输入名字（留空默认"小满"）后进入 Day 1 小屋
import Phaser from "phaser";
import { director } from "../core/director";
import { audio } from "../core/audio";

export class TitleScene extends Phaser.Scene {
  private starting = false;

  constructor() { super("title"); }

  create() {
    this.starting = false;
    this.cameras.main.setBackgroundColor("#8ecae6");
    // 糖果色村庄剪影
    const g = this.add.graphics();
    g.fillStyle(0x8fd05a).fillRect(0, 120, 320, 60);
    g.fillStyle(0xfff1d0).fillRect(50, 92, 40, 28).fillRect(230, 96, 36, 24);
    g.fillStyle(0xf4924a).fillTriangle(45, 92, 95, 92, 70, 74).fillTriangle(226, 96, 270, 96, 248, 80);
    g.fillStyle(0x5da53f).fillRect(140, 84, 36, 36);
    g.fillStyle(0x8a5a34).fillRect(154, 118, 8, 12);
    this.add.sprite(160, 40, "sunflower", 12).setScale(2);

    this.add.text(160, 66, "崩坏童话：蜜糖村", {
      fontFamily: '"PingFang SC","Hiragino Sans GB",sans-serif', fontSize: "20px", color: "#fff8e8",
    }).setOrigin(0.5).setStroke("#a05c28", 5);
    this.add.text(160, 132, "输入你的名字，回车开始", {
      fontFamily: '"PingFang SC",sans-serif', fontSize: "9px", color: "#4a3828",
    }).setOrigin(0.5);
    this.add.text(160, 168, "移动 WASD/方向键 · 交互 E", {
      fontFamily: '"PingFang SC",sans-serif', fontSize: "8px", color: "#4a3828",
    }).setOrigin(0.5).setAlpha(0.8);

    const entry = document.getElementById("name-entry")!;
    const input = document.getElementById("name-input") as HTMLInputElement;
    entry.style.display = "block";
    input.value = "";
    setTimeout(() => input.focus(), 50);

    const begin = () => {
      if (this.starting) return;
      this.starting = true;
      entry.style.display = "none";
      input.onkeydown = null;
      audio.start(); // 用户手势后启动 Web Audio
      director.reset(input.value.trim());
      director.pendingSpawn = "bed";
      if (!this.scene.isActive("ui")) this.scene.launch("ui");
      this.scene.start("house");
    };
    input.onkeydown = (ev) => {
      if (ev.key === "Enter") begin();
      ev.stopPropagation();
    };
    this.input.keyboard!.once("keydown-ENTER", begin);
  }
}
