// 梦境过场：侵蚀越高，梦境越"漏"；Day3 夜起闪切白色病房 1 秒
import Phaser from "phaser";
import { director } from "../core/director";
import { audio } from "../core/audio";
import { DREAMS } from "../data/story";

const FONT = { fontFamily: '"PingFang SC","Hiragino Sans GB",sans-serif', fontSize: "11px", color: "#c8c8d0" };

export class DreamScene extends Phaser.Scene {
  constructor() { super("dream"); }

  create() {
    this.cameras.main.setBackgroundColor("#000000");
    const day = director.day;
    const lines = [...(DREAMS[day] ?? ["……"])];
    // 觉知越高，梦越漏
    if (director.awareness >= 30) lines.push("（有人在很近的地方换点滴。）");
    if (director.awareness >= 60) lines.push("「PT-07，睡眠状态良好。」");

    const t = this.add.text(160, 84, "", { ...FONT, align: "center", wordWrap: { width: 260 } }).setOrigin(0.5);
    let i = 0;
    const showNext = () => {
      if (i === Math.min(1, lines.length - 1) && day >= 3) this.wardFlash();
      if (i >= lines.length) { this.finish(); return; }
      t.setText(lines[i]).setAlpha(0);
      this.tweens.add({
        targets: t, alpha: 1, duration: 700, hold: 1200, yoyo: true,
        onComplete: () => { i++; showNext(); },
      });
    };
    i = 0;
    this.time.delayedCall(500, showNext);
  }

  // 闪切白色病房 1 秒（用真实病房地图渲染）
  private wardFlash() {
    this.time.delayedCall(950, () => {
      const map = this.make.tilemap({ key: "map_white_ward" });
      const ts = map.addTilesetImage("tiles", "tiles")!;
      const g = map.createLayer("ground", ts)!.setPosition(80, 56);
      const o = map.createLayer("obstacles", ts)!.setPosition(80, 56);
      audio.sfxEcg();
      this.time.delayedCall(1000, () => { g.destroy(); o.destroy(); });
    });
  }

  private finish() {
    director.startDay(director.day + 1);
    director.pendingSpawn = "bed";
    this.scene.start("house");
  }
}
