import Phaser from 'phaser';
import { SCENE_KEYS } from '../data/constants';
import { ENDING_NAMES, ENDING_SUBTITLES, type EndingId } from '../data/endings';
import { Director } from '../systems/CorruptionDirector';
import { audio } from '../audio/ProceduralAudio';

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

  constructor() {
    super(SCENE_KEYS.ENDING);
  }

  init(data: { endingId?: EndingId }): void {
    this.endingId = data?.endingId || Director.endingId || 'E1';
  }

  create(): void {
    const { width, height } = this.cameras.main;
    const id = this.endingId;

    if (id === 'E1') this.playE1(width, height);
    else if (id === 'E2') this.playE2(width, height);
    else if (id === 'E3') this.playE3(width, height);
    else this.playE4(width, height);

    this.time.delayedCall(id === 'E3' ? 6000 : 3500, () => this.showReturn(width, height));
  }

  private playE1(w: number, h: number): void {
    this.cameras.main.setBackgroundColor('#ffe080');
    // push saturation feel
    this.add
      .text(w / 2, 40, '糖衣', {
        fontFamily: 'monospace',
        fontSize: '18px',
        color: '#ff6080',
      })
      .setOrigin(0.5);
    this.add
      .text(w / 2, 70, '全村微笑合影定格', {
        fontFamily: 'monospace',
        fontSize: '10px',
        color: '#603020',
      })
      .setOrigin(0.5);
    // fake group photo blocks
    for (let i = 0; i < 7; i++) {
      this.add.rectangle(60 + i * 32, 110, 20, 28, 0xffd0a0).setStrokeStyle(1, 0xc08040);
    }
    this.tweens.add({
      targets: this.cameras.main,
      // visual: brighten overlay
      duration: 2000,
    });
    const overlay = this.add.rectangle(w / 2, h / 2, w, h, 0xfff0a0, 0).setDepth(5);
    this.tweens.add({ targets: overlay, alpha: 0.45, duration: 2500 });
    ENDING_SUBTITLES.E1.forEach((line, i) => {
      this.add
        .text(w / 2, 145 + i * 14, line, {
          fontFamily: 'monospace',
          fontSize: '10px',
          color: '#402010',
        })
        .setOrigin(0.5)
        .setDepth(6);
    });
  }

  private playE2(w: number, h: number): void {
    this.cameras.main.setBackgroundColor('#201018');
    this.add
      .text(w / 2, 40, '回收', {
        fontFamily: 'monospace',
        fontSize: '18px',
        color: '#ff8080',
      })
      .setOrigin(0.5);
    // negative 2s
    const flash = this.add.rectangle(w / 2, h / 2, w, h, 0xffffff, 1).setDepth(5);
    this.tweens.add({ targets: flash, alpha: 0, duration: 2000 });
    audio.ecg();
    this.time.delayedCall(400, () => audio.ecg());
    this.add
      .text(w / 2, 100, '画面骤停。心电监护滴声。', {
        fontFamily: 'monospace',
        fontSize: '10px',
        color: '#e0c0c0',
      })
      .setOrigin(0.5);
    this.add
      .text(w / 2, 120, '回到 Day 1 清晨的床上。日历翻回同一天。', {
        fontFamily: 'monospace',
        fontSize: '9px',
        color: '#c0a0a0',
      })
      .setOrigin(0.5);
    ENDING_SUBTITLES.E2.forEach((line, i) => {
      this.add
        .text(w / 2, 145 + i * 14, line, {
          fontFamily: 'monospace',
          fontSize: '11px',
          color: '#ffffff',
        })
        .setOrigin(0.5);
    });
  }

  private playE3(w: number, h: number): void {
    this.cameras.main.setBackgroundColor('#e8e8f0');
    this.add
      .text(w / 2, 16, '苏醒', {
        fontFamily: 'monospace',
        fontSize: '16px',
        color: '#606070',
      })
      .setOrigin(0.5);

    // corridor → ward → record
    const story = this.add
      .text(w / 2, 40, '雾墙裂开成白色走廊……', {
        fontFamily: 'monospace',
        fontSize: '9px',
        color: '#707080',
      })
      .setOrigin(0.5);

    this.time.delayedCall(1200, () => story.setText('病房。消毒水的气味。'));
    this.time.delayedCall(2400, () => {
      story.setText('');
      // Medical record
      const box = this.add.rectangle(w / 2, 95, 260, 90, 0xffffff).setStrokeStyle(1, 0x808090);
      this.add
        .text(w / 2, 58, '蜜糖谷情绪疗养中心', {
          fontFamily: 'monospace',
          fontSize: '11px',
          color: '#303040',
        })
        .setOrigin(0.5);
      this.add
        .text(w / 2, 78, `姓名：${Director.playerName}`, {
          fontFamily: 'monospace',
          fontSize: '10px',
          color: '#303040',
        })
        .setOrigin(0.5);
      this.add
        .text(w / 2, 94, '编号：PT-07', {
          fontFamily: 'monospace',
          fontSize: '10px',
          color: '#303040',
        })
        .setOrigin(0.5);
      this.add
        .text(w / 2, 110, `疗程时长：${Director.sessionDurationLabel()}`, {
          fontFamily: 'monospace',
          fontSize: '10px',
          color: '#303040',
        })
        .setOrigin(0.5);
      void box;
    });

    this.time.delayedCall(4200, () => {
      // Real face — only time smile changes
      this.add
        .text(w / 2, 150, '微笑消失。真实的脸。', {
          fontFamily: 'monospace',
          fontSize: '9px',
          color: '#505060',
        })
        .setOrigin(0.5);
      this.add.image(w / 2, 170, 'portraits', 1).setScale(1.2); // real face frame
      this.add
        .text(w / 2, 190, '窗外，一只灰色的、真的麻雀。', {
          fontFamily: 'monospace',
          fontSize: '8px',
          color: '#808090',
        })
        .setOrigin(0.5);
      // grey sparrow pixel
      this.add.rectangle(w / 2 + 80, 168, 6, 4, 0x808080);
    });
  }

  private playE4(w: number, h: number): void {
    this.cameras.main.setBackgroundColor('#101018');
    this.add
      .text(w / 2, 40, '静默', {
        fontFamily: 'monospace',
        fontSize: '18px',
        color: '#808090',
      })
      .setOrigin(0.5);
    this.add
      .text(w / 2, 70, '庆典无人出席。', {
        fontFamily: 'monospace',
        fontSize: '10px',
        color: '#a0a0b0',
      })
      .setOrigin(0.5);
    this.add
      .text(w / 2, 90, '空广场，彩带在没有风的空气里飘。', {
        fontFamily: 'monospace',
        fontSize: '9px',
        color: '#9090a0',
      })
      .setOrigin(0.5);
    // ribbons
    for (let i = 0; i < 5; i++) {
      const r = this.add.rectangle(80 + i * 40, 120, 20, 3, 0xff6080, 0.5);
      this.tweens.add({
        targets: r,
        y: 125,
        duration: 1500 + i * 200,
        yoyo: true,
        repeat: -1,
      });
    }
    ENDING_SUBTITLES.E4.forEach((line) => {
      this.add
        .text(w / 2, 150, line, {
          fontFamily: 'monospace',
          fontSize: '11px',
          color: '#c0c0d0',
        })
        .setOrigin(0.5);
    });
    this.time.delayedCall(2500, () => {
      this.cameras.main.fade(800, 0, 0, 0);
    });
  }

  private showReturn(w: number, h: number): void {
    const btn = this.add
      .text(w / 2, h - 20, '回到标题', {
        fontFamily: 'monospace',
        fontSize: '12px',
        color: '#ffffff',
        backgroundColor: '#405060',
        padding: { x: 10, y: 5 },
      })
      .setOrigin(0.5)
      .setDepth(20)
      .setInteractive({ useHandCursor: true });

    btn.on('pointerdown', () => this.returnTitle());
    this.input.keyboard?.once('keydown-E', () => this.returnTitle());
    this.input.keyboard?.once('keydown-ENTER', () => this.returnTitle());

    this.add
      .text(w / 2, 8, `结局 · ${ENDING_NAMES[this.endingId]}`, {
        fontFamily: 'monospace',
        fontSize: '8px',
        color: '#a0a0b0',
      })
      .setOrigin(0.5)
      .setDepth(20);
  }

  private returnTitle(): void {
    audio.stopAll();
    Director.resetSession();
    for (const k of Object.values(SCENE_KEYS)) {
      if (this.scene.isActive(k)) this.scene.stop(k);
    }
    this.scene.start(SCENE_KEYS.TITLE);
  }
}
