import Phaser from 'phaser';
import { audio } from '../AudioDirector';
import { director } from '../CorruptionDirector';
import { MAP_KEYS, type EndingId } from '../data';

export class EndingScene extends Phaser.Scene {
  private ending: EndingId = 'E1';

  constructor() { super('EndingScene'); }

  init(data: { ending?: EndingId }): void { this.ending = data.ending ?? director.ending() ?? 'E1'; }

  create(): void {
    MAP_KEYS.forEach((key) => { if (this.scene.isActive(key)) this.scene.stop(key); });
    if (this.scene.isActive('UIScene')) this.scene.stop('UIScene');
    this.cameras.main.setBackgroundColor('#241f22');
    ({ E1: () => this.playE1(), E2: () => this.playE2(), E3: () => this.playE3(), E4: () => this.playE4() })[this.ending]();
  }

  private title(text: string): Phaser.GameObjects.Text {
    return this.add.text(160, 18, text, this.style(13, '#fff0bd')).setOrigin(0.5).setDepth(20);
  }

  private caption(text: string, y = 132): Phaser.GameObjects.Text {
    return this.add.text(160, y, text, { ...this.style(9, '#fff0bd'), align: 'center', wordWrap: { width: 280 } }).setOrigin(0.5).setDepth(20).setLineSpacing(4);
  }

  private style(size: number, color: string): Phaser.Types.GameObjects.Text.TextStyle {
    return { fontFamily: '"Courier New", "PingFang SC", monospace', fontSize: `${size}px`, fontStyle: 'bold', color };
  }

  private playE1(): void {
    this.cameras.main.setBackgroundColor('#86d55b');
    this.title('E1  糖衣');
    for (let i = 0; i < 12; i += 1) this.add.sprite(50 + (i % 6) * 44, 67 + Math.floor(i / 6) * 34, 'characters', i < 7 ? 16 + i * 3 : 37 + (i - 7)).setScale(1.35);
    this.caption('从此，每一天都很幸福。\n\n每一天。', 137);
    const saturation = this.cameras.main.postFX.addColorMatrix();
    this.tweens.addCounter({ from: 0, to: 0.5, duration: 5000, onUpdate: (tween) => saturation.reset().saturate(tween.getValue() ?? 0), onComplete: () => this.showReturn() });
  }

  private playE2(): void {
    this.cameras.main.setBackgroundColor('#f5e8b1');
    this.title('E2  回收');
    const frozen = this.add.sprite(160, 90, 'characters', 0).setScale(3);
    const negative = this.cameras.main.postFX.addColorMatrix().negative();
    this.time.delayedCall(2000, () => {
      negative.reset();
      audio.beep('monitor');
      frozen.destroy();
      this.add.rectangle(160, 90, 190, 112, 0xffe8a4).setStrokeStyle(3, 0x5b362b);
      this.add.sprite(160, 85, 'characters', 0).setScale(2);
      this.add.text(92, 53, '日历：同一天', this.style(7, '#58372e'));
      this.caption('疗程重新开始。', 145);
      this.showReturn(2100);
    });
  }

  private playE3(): void {
    this.cameras.main.setBackgroundColor('#e7e8e5');
    const map = this.make.tilemap({ key: 'WhiteScene' });
    const tileset = map.addTilesetImage('honey-village', 'tiles');
    if (tileset) map.createLayer('ground', tileset, 0, 26)?.setAlpha(0.45);
    this.title('E3  苏醒');
    const corridor = this.add.graphics();
    corridor.fillStyle(0xf8f8f4).fillRect(18, 38, 284, 96);
    corridor.lineStyle(2, 0xb8bec0).strokeRect(18, 38, 284, 96);
    corridor.fillStyle(0xc9cecf).fillRect(156, 38, 8, 96);
    const player = this.add.sprite(42, 112, 'characters', 0);
    this.tweens.add({ targets: player, x: 260, duration: 2800, onComplete: () => {
      corridor.clear().fillStyle(0xfafafa).fillRect(18, 38, 284, 96);
      player.destroy();
      const record = this.add.rectangle(160, 87, 240, 108, 0xffffff).setStrokeStyle(2, 0x899092);
      const recordText = this.add.text(54, 43,
        `蜜糖谷情绪疗养中心\n\n姓名：${director.snapshot.playerName}\n编号：PT-07\n疗程时长：${director.elapsedLabel()}`,
        { ...this.style(9, '#394044'), lineSpacing: 5 });
      this.time.delayedCall(2800, () => {
        record.destroy(); recordText.destroy();
        const face = this.add.image(119, 86, 'portraits', 0).setScale(1.5);
        this.time.delayedCall(400, () => {
          face.setFrame(1);
          this.add.text(171, 65, '微笑消失了。', this.style(8, '#555b5d'));
          this.add.text(171, 83, '窗外，一只灰色的、\n真的麻雀。', { ...this.style(8, '#555b5d'), lineSpacing: 4 });
          const bird = this.add.sprite(240, 113, 'characters', 42).setTint(0x92999a);
          this.tweens.add({ targets: bird, y: 106, yoyo: true, repeat: -1, duration: 450 });
          this.showReturn(1800);
        });
      });
    } });
  }

  private playE4(): void {
    this.cameras.main.setBackgroundColor('#8fd35f');
    this.title('E4  静默');
    this.add.rectangle(160, 101, 270, 70, 0xcdbb8e).setStrokeStyle(2, 0x78644c);
    for (let i = 0; i < 7; i += 1) {
      const ribbon = this.add.rectangle(65 + i * 31, 58, 20, 3, i % 2 ? 0xf2a64c : 0xef7195);
      this.tweens.add({ targets: ribbon, angle: 4, yoyo: true, repeat: -1, duration: 900 + i * 80 });
    }
    this.caption('系统检测到疗程无效。', 145);
    this.cameras.main.fadeOut(3500, 0, 0, 0, (_camera: Phaser.Cameras.Scene2D.Camera, progress: number) => {
      if (progress === 1) {
        this.children.removeAll(true);
        this.cameras.main.resetFX().setBackgroundColor('#000000');
        this.showReturn();
      }
    });
  }

  private showReturn(delay = 0): void {
    this.time.delayedCall(delay, () => {
      const button = this.add.text(160, 166, '回到标题', this.style(8, '#fff4ca')).setOrigin(0.5).setPadding(8, 4, 8, 4).setBackgroundColor('#5b362b').setInteractive({ useHandCursor: true }).setDepth(50);
      button.on('pointerdown', () => this.scene.start('TitleScene'));
    });
  }
}
