import Phaser from 'phaser';
import { Director } from '../core/Director';
import { Audio } from '../core/Audio';
import { ENDING_TEXT } from '../data/content';

const FONT = '"PingFang SC","Microsoft YaHei","Hiragino Sans GB",sans-serif';

export class EndingScene extends Phaser.Scene {
  constructor() { super('Ending'); }

  create(data: { id: string }) {
    this.cameras.main.setBackgroundColor('#000000');
    this.cameras.main.fadeIn(500, 0, 0, 0);
    switch (data.id) {
      case 'E1': this.e1(); break;
      case 'E2': this.e2(); break;
      case 'E3': this.e3(); break;
      default: this.e4(); break;
    }
  }

  // 字幕逐行（前一行淡出，避免重叠）
  private prevCap?: Phaser.GameObjects.Text;
  private captions(lines: string[], startDelay: number, gap: number, y = 150, cb?: () => void) {
    let d = startDelay;
    lines.forEach((ln, i) => {
      this.time.delayedCall(d, () => {
        if (this.prevCap) { const p = this.prevCap; this.tweens.add({ targets: p, alpha: 0, duration: 400, onComplete: () => p.destroy() }); }
        const t = this.add.text(160, y, ln, { fontFamily: FONT, fontSize: '11px', color: '#f2ead6', align: 'center', wordWrap: { width: 300 } }).setOrigin(0.5).setAlpha(0).setDepth(100);
        this.tweens.add({ targets: t, alpha: 1, duration: 600 });
        this.prevCap = t;
        if (i === lines.length - 1 && cb) this.time.delayedCall(gap, cb);
      });
      d += gap;
    });
  }
  private homeButton(delay: number) {
    this.time.delayedCall(delay, () => {
      const b = this.add.text(160, 168, '回到标题', { fontFamily: FONT, fontSize: '11px', color: '#fff', backgroundColor: '#8a5a3a', padding: { x: 8, y: 3 } })
        .setOrigin(0.5).setDepth(200).setInteractive({ useHandCursor: true }).setAlpha(0);
      this.tweens.add({ targets: b, alpha: 1, duration: 500 });
      b.on('pointerdown', () => this.scene.start('Title'));
    });
  }

  // E1 糖衣：全村微笑合影定格，饱和度缓慢推到 1.5
  private e1() {
    this.cameras.main.setBackgroundColor('#f6e7b8');
    const g = this.add.graphics(); g.fillStyle(0x8fd3f0, 1).fillRect(0, 0, 320, 110); g.fillStyle(0x7bc86c, 1).fillRect(0, 110, 320, 70);
    const cast = ['npc_afu', 'npc_yuan', 'npc_dabao', 'npc_mimi', 'npc_fu', 'npc_gui'];
    cast.forEach((c, i) => this.add.sprite(56 + i * 36, 108, c, 0).setOrigin(0.5, 1).setScale(1.4));
    this.add.image(232, 108, 'portraits', 0).setOrigin(0.5, 1).setScale(0.9);
    // 合影相框
    const fr = this.add.graphics(); fr.lineStyle(4, 0xffffff, 1).strokeRect(20, 40, 280, 80);
    this.add.text(160, 34, '📷', { fontSize: '12px' }).setOrigin(0.5);
    const sat = this.cameras.main.postFX.addColorMatrix();
    let s = 1.0; const ev = this.time.addEvent({ delay: 60, loop: true, callback: () => { s = Math.min(1.5, s + 0.006); sat.saturate((s - 1) * 1.5, false); } });
    this.time.delayedCall(9000, () => ev.remove());
    this.captions(ENDING_TEXT.E1, 1200, 2000, 150);
    this.homeButton(1200 + 2000 * ENDING_TEXT.E1.length + 800);
  }

  // E2 回收：负片 2 秒 + 心电滴声 → 回到 Day1 床上，日历翻回同一天
  private e2() {
    const neg = this.cameras.main.postFX.addColorMatrix(); neg.negative();
    Audio.sfxEcg();
    const t = this.add.text(160, 90, '——', { fontFamily: FONT, fontSize: '14px', color: '#ffffff' }).setOrigin(0.5);
    this.time.delayedCall(2000, () => {
      neg.reset(); t.destroy();
      // Day1 清晨的床（用室内地板 + 床 tile 感觉）
      this.cameras.main.setBackgroundColor('#b09a78');
      const g = this.add.graphics(); g.fillStyle(0xcaa06e, 1).fillRect(60, 70, 200, 60); g.fillStyle(0xf49ac1, 1).fillRect(70, 78, 180, 40); g.fillStyle(0xf5e6c0, 1).fillRect(70, 78, 60, 40);
      this.add.image(150, 100, 'portraits', 0).setScale(1.4);
      this.add.text(238, 60, '日\n历', { fontFamily: FONT, fontSize: '9px', color: '#8a5a3a', align: 'center' });
      this.captions(ENDING_TEXT.E2, 600, 1900, 150);
      this.homeButton(600 + 1900 * ENDING_TEXT.E2.length + 800);
    });
  }

  // E3 苏醒：白色走廊→病房→病历特写→微笑消失变疲惫脸 + 灰麻雀（§9）
  private e3() {
    const map = this.make.tilemap({ key: 'map_white' });
    map.layers.forEach((l: any) => (l.tilemapLayer = null));
    const ts = map.addTilesetImage('tiles', 'tiles')!;
    map.createLayer('ground', ts, 0, 0); map.createLayer('obstacles', ts, 0, 0);
    const cam = this.cameras.main; cam.setBounds(0, 0, map.widthInPixels, map.heightInPixels); cam.centerOn(160, 40);
    const hint = this.add.text(160, 20, '雾裂开了，成了一条白色的走廊……', { fontFamily: FONT, fontSize: '9px', color: '#5a5a60' }).setOrigin(0.5).setScrollFactor(0).setDepth(50);
    this.tweens.add({ targets: cam, scrollY: 44, duration: 3200, ease: 'Sine.inOut', delay: 700, onComplete: () => hint.setText('……病房。') });

    this.time.delayedCall(4600, () => {
      cam.fadeOut(600, 240, 242, 245);
      cam.once('camerafadeoutcomplete', () => { hint.destroy(); this.record(); });
    });
  }
  private record() {
    const cam = this.cameras.main; cam.setBounds(0, 0, 320, 180); cam.setScroll(0, 0); cam.setBackgroundColor('#e6e8ea'); cam.fadeIn(500, 240, 242, 245);
    // 病历特写（放进容器，稍后整体淡出）
    const c = this.add.container(0, 0).setDepth(60);
    const p = this.add.graphics(); p.fillStyle(0xffffff, 1).fillRoundedRect(36, 24, 248, 128, 4); p.lineStyle(1, 0x9aa0a8).strokeRoundedRect(36, 24, 248, 128, 4);
    const head = this.add.text(160, 42, '蜜糖谷情绪疗养中心', { fontFamily: FONT, fontSize: '13px', color: '#2a2a30', fontStyle: 'bold' }).setOrigin(0.5).setAlpha(0);
    const rule = this.add.graphics(); rule.lineStyle(1, 0xccced2).lineBetween(56, 58, 264, 58);
    c.add([p, head, rule]);
    this.tweens.add({ targets: head, alpha: 1, duration: 700 });
    const rows = [`姓名：${Director.playerName}`, `编号：PT-07`, `本次疗程时长：${Director.playtimeString()}`];
    rows.forEach((r, i) => this.time.delayedCall(900 + i * 750, () => {
      const t = this.add.text(64, 74 + i * 22, r, { fontFamily: FONT, fontSize: '12px', color: '#33333a' }).setAlpha(0); c.add(t);
      this.tweens.add({ targets: t, alpha: 1, duration: 500 });
    }));
    // 最后一帧：微笑头像消失 → 疲惫真实的脸 + 灰麻雀（§9 唯一一次头像变化）
    this.time.delayedCall(3800, () => {
      this.tweens.add({ targets: c, alpha: 0, duration: 700, onComplete: () => c.destroy() });
      this.time.delayedCall(800, () => this.finalFrame());
    });
  }
  private finalFrame() {
    const port = this.add.image(160, 82, 'portraits', 0).setScale(1.8).setDepth(60);
    const cap = this.add.text(160, 128, '……', { fontFamily: FONT, fontSize: '11px', color: '#55555c' }).setOrigin(0.5).setDepth(60);
    this.time.delayedCall(1400, () => {
      this.cameras.main.flash(220, 255, 255, 255);
      port.setTexture('portraits', 1);                       // 真实的、疲惫的脸
      this.add.image(252, 54, 'sparrow').setScale(1.5).setDepth(60); // 窗外，一只真的麻雀
      cap.setText('窗外，一只灰色的、真的麻雀。');
      this.homeButton(1800);
    });
  }

  // E4 静默：庆典无人出席，空广场，彩带在没有风里飘，字幕后黑屏
  private e4() {
    this.cameras.main.setBackgroundColor('#3a3d42');
    const g = this.add.graphics(); g.fillStyle(0x4a4e54, 1).fillRect(0, 120, 320, 60); // 灰广场
    // 无风飘的彩带
    for (let i = 0; i < 6; i++) {
      const x = 40 + i * 44, y = 60 + (i % 3) * 20;
      const r = this.add.graphics(); r.fillStyle([0xaa6688, 0x88888a, 0x9a8a6a][i % 3], 0.8);
      for (let k = 0; k < 12; k++) r.fillRect(x + k, y + Math.round(2 * Math.sin(k * 0.9)), 1, 2);
      this.tweens.add({ targets: r, y: y + 6, duration: 3000 + i * 300, yoyo: true, repeat: -1, ease: 'Sine.inOut' });
    }
    this.captions(ENDING_TEXT.E4, 1000, 2200, 40, () => {
      this.cameras.main.fadeOut(1500, 0, 0, 0);
      this.homeButton(2000);
    });
  }
}
