// 结局演出（PRD §9，封闭 4 个）。落幕后停在结束画面，提供「回到标题」（重开无继承）
import Phaser from "phaser";
import { director } from "../core/director";
import { audio } from "../core/audio";
import { ENDING_TEXT } from "../data/story";

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

export class EndingScene extends Phaser.Scene {
  private colorFx?: Phaser.FX.ColorMatrix;

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

  create() {
    const code = (this.registry.get("ending") as string) ?? "E1";
    this.cameras.main.setBackgroundColor("#000000");
    this.colorFx = this.cameras.main.postFX.addColorMatrix();
    if (code === "E1") this.e1();
    else if (code === "E2") this.e2();
    else if (code === "E3") this.e3();
    else this.e4();
  }

  private drawMap(key: string): Phaser.Tilemaps.Tilemap {
    const map = this.make.tilemap({ key: "map_" + key });
    const ts = map.addTilesetImage("tiles", "tiles")!;
    map.createLayer("ground", ts);
    map.createLayer("obstacles", ts);
    return map;
  }

  private subtitle(lines: string[], startDelay: number, gap = 2600, cb?: () => void) {
    const t = this.add.text(160, 158, "", { ...FONT, align: "center" }).setOrigin(0.5).setDepth(50).setStroke("#000000", 4).setScrollFactor(0);
    lines.forEach((l, i) => {
      this.time.delayedCall(startDelay + i * gap, () => {
        t.setText(l).setAlpha(0);
        this.tweens.add({ targets: t, alpha: 1, duration: 700 });
      });
    });
    if (cb) this.time.delayedCall(startDelay + lines.length * gap, cb);
  }

  private backButton(delay: number) {
    this.time.delayedCall(delay, () => {
      const b = this.add.text(160, 172, "［ 回到标题 ］", { ...FONT, fontSize: "10px", color: "#ffd94a" })
        .setOrigin(0.5).setDepth(60).setStroke("#000000", 4).setScrollFactor(0).setInteractive({ useHandCursor: true });
      b.on("pointerdown", () => window.location.reload());
      this.input.keyboard!.once("keydown-E", () => window.location.reload());
      this.input.keyboard!.once("keydown-ENTER", () => window.location.reload());
      this.tweens.add({ targets: b, alpha: 0.5, duration: 700, yoyo: true, repeat: -1 });
    });
  }

  // E1 糖衣：庆典圆满，合影定格，饱和度推到 1.5
  private e1() {
    this.drawMap("plaza");
    this.cameras.main.centerOn(240, 190);
    const lineup: [string, number, number][] = [
      ["npc_afu", 208, 196], ["npc_yuanyuan", 228, 200], ["npc_dabao", 248, 196],
      ["npc_mimi", 268, 200], ["npc_fu", 218, 216], ["npc_gui", 258, 216],
    ];
    for (const [tex, x, y] of lineup) this.add.sprite(x, y, tex, 0).setOrigin(0.5, 1);
    this.add.sprite(238, 214, "player", 0).setOrigin(0.5, 1);
    for (let i = 0; i < 6; i++) this.add.image(200 + i * 16, 168, "tiles", 58);
    // 快门定格 + 饱和度缓慢推到 1.5
    this.time.delayedCall(1200, () => this.cameras.main.flash(300, 255, 255, 255));
    this.tweens.addCounter({
      from: 0, to: 0.5, duration: 7000, delay: 1500,
      onUpdate: (tw) => { this.colorFx!.reset(); this.colorFx!.saturate(tw.getValue()!); },
    });
    this.subtitle(ENDING_TEXT.E1, 2600, 3000);
    this.backButton(9000);
  }

  // E2 回收：负片 2 秒 + 心电一响 → 回到 Day1 清晨的床
  private e2() {
    audio.stopBgm();
    const g = this.drawMap("plaza");
    this.cameras.main.centerOn(240, 190);
    this.colorFx!.negative();
    audio.sfxEcg();
    this.time.delayedCall(2000, () => {
      this.children.removeAll();
      this.colorFx!.reset();
      this.drawMap("house");
      this.cameras.main.centerOn(96, 64);
      this.add.sprite(24, 64, "player", 0).setOrigin(0.5, 1).setAngle(90); // 躺在床上
      this.subtitle(ENDING_TEXT.E2, 1500);
      this.backButton(4500);
    });
    void g;
  }

  // E3 苏醒：病历特写 → 微笑消失，换上真实的脸；窗外一只灰色的、真的麻雀
  private e3() {
    audio.stopBgm();
    this.drawMap("white_ward");
    this.cameras.main.centerOn(80, 64);
    this.colorFx!.saturate(-0.4);
    // 病历特写
    const panel = this.add.graphics().setDepth(20).setScrollFactor(0);
    panel.fillStyle(0xf2f2f4, 1).fillRect(60, 24, 200, 108);
    panel.lineStyle(1, 0x9a9aa4, 1).strokeRect(60, 24, 200, 108);
    const chartLines = ENDING_TEXT.E3chart(director.playerName, director.playTimeText);
    const texts: Phaser.GameObjects.Text[] = [];
    chartLines.forEach((l, i) => {
      const t = this.add.text(70, 36 + i * 22, "", {
        fontFamily: '"PingFang SC",sans-serif', fontSize: i === 0 ? "13px" : "10px",
        color: i === 0 ? "#2a2a34" : "#4a4a56",
      }).setDepth(21).setScrollFactor(0);
      texts.push(t);
      this.time.delayedCall(900 + i * 1500, () => t.setText(l));
    });
    // 最后一帧：微笑消失
    this.time.delayedCall(900 + chartLines.length * 1500 + 1500, () => {
      panel.destroy(); texts.forEach(t => t.destroy());
      this.cameras.main.setBackgroundColor("#dcdce0");
      const smile = this.add.image(160, 80, "portrait_smile").setScale(3).setDepth(30).setScrollFactor(0);
      this.time.delayedCall(2200, () => {
        smile.setTexture("portrait_real"); // 全流程唯一一次头像变化
        // 窗外，一只灰色的、真的麻雀
        const sp = this.add.image(240, 46, "sparrow").setDepth(31).setAlpha(0).setScrollFactor(0);
        this.tweens.add({ targets: sp, alpha: 1, duration: 1200, delay: 800 });
        this.tweens.add({ targets: sp, y: 44, duration: 900, delay: 2000, yoyo: true, repeat: 2 });
        this.subtitle(["…………", "早上好。"], 1600, 2600);
        this.backButton(7000);
      });
    });
  }

  // E4 静默：庆典无人出席，彩带在没有风的空气里飘
  private e4() {
    audio.stopBgm();
    this.drawMap("plaza");
    this.cameras.main.centerOn(240, 190);
    this.colorFx!.saturate(-0.15);
    for (let i = 0; i < 6; i++) {
      const img = this.add.image(200 + i * 16, 168, "tiles", 58);
      this.tweens.add({ targets: img, y: 166, duration: 1700 + i * 140, yoyo: true, repeat: -1 });
    }
    this.subtitle(ENDING_TEXT.E4, 2600, 2600, () => {
      const black = this.add.rectangle(160, 90, 320, 180, 0x000000, 0).setDepth(40).setScrollFactor(0);
      this.tweens.add({ targets: black, fillAlpha: 1, duration: 2200 });
    });
    this.backButton(8200);
  }
}
