// EndingScene.ts: plays out the determined ending per §9, then offer "回到标题".
import Phaser from 'phaser';
import { director } from '../systems/CorruptionDirector';
import { ENDINGS, ENDING_CAPTIONS } from '../data/gamedata';
import { audio } from '../systems/AudioEngine';

export class EndingScene extends Phaser.Scene {
  ending: 'E4'|'E3'|'E2'|'E1' = 'E1';
  constructor() { super('EndingScene'); }

  init(data: any) { this.ending = data.ending || 'E1'; }

  create() {
    audio.stopMusic();
    this.cameras.main.setBackgroundColor('#000000');
    const def = ENDINGS.find(e => e.key === this.ending)!;
    const cx = 160;
    this.add.text(cx, 30, `结局 ${this.ending}：${def.name}`, { fontFamily:'monospace', fontSize:'12px', color:'#ffd86b' }).setOrigin(0.5);

    // run show per ending
    if (this.ending === 'E4') this.runE4();
    else if (this.ending === 'E3') this.runE3();
    else if (this.ending === 'E2') this.runE2();
    else this.runE1();
  }

  private showCaption(y: number, text: string, color = '#ffffff', delay = 0) {
    const t = this.add.text(160, y, '', { fontFamily:'monospace', fontSize:'9px', color }).setOrigin(0.5);
    this.time.delayedCall(delay, () => t.setText(text));
    return t;
  }

  runE4() {
    // empty plaza, ribbons floating in windless air
    this.add.text(160, 70, '（空荡荡的广场，彩带在没有风的空气里飘。）', { fontFamily:'monospace', fontSize:'8px', color:'#9a9a9a' }).setOrigin(0.5);
    this.showCaption(110, `「${ENDING_CAPTIONS.E4}」`, '#ff8888', 1500);
    this.time.delayedCall(3000, () => { this.cameras.main.fadeOut(1500, 0,0,0); });
    this.finish(5000);
  }

  runE3() {
    // medical chart reveal + final frame: smile gone -> tired real face + grey sparrow
    this.showCaption(60, ENDING_CAPTIONS.E3_medical, '#ffffff', 300);
    this.showCaption(80, `姓名：${director.playerName}`, '#e0e0e0', 1000);
    this.showCaption(95, '编号：PT-07', '#e0e0e0', 1700);
    this.showCaption(110, `疗程时长：${director.formatPlayTime()}`, '#e0e0e0', 2400);
    // final frame: portrait real face (index 1)
    this.time.delayedCall(3300, () => {
      const portrait = this.add.image(160, 140, 'portraits', 1).setOrigin(0.5).setScale(2);
      this.add.text(160, 168, '（微笑消失了。窗外，一只灰色的、真的麻雀。）', { fontFamily:'monospace', fontSize:'7px', color:'#bbbbbb' }).setOrigin(0.5);
    });
    this.finish(6500);
  }

  runE2() {
    // freeze, negative 2s, heartbeat, back to day1
    this.showCaption(70, '（画面骤停）', '#ffffff', 300);
    this.time.delayedCall(1200, () => {
      const r = this.add.rectangle(160, 90, 320, 180, 0xffffff, 1);
      this.time.delayedCall(400, () => { r.destroy(); });
      audio.sfxHeartbeat();
    });
    this.showCaption(110, `「${ENDING_CAPTIONS.E2}」`, '#ff8888', 2600);
    this.finish(5000);
  }

  runE1() {
    // festival圆满, saturation to 1.5, captions
    this.add.text(160, 70, '（全村微笑合影定格。）', { fontFamily:'monospace', fontSize:'8px', color:'#ffe9b0' }).setOrigin(0.5);
    // ramp saturation via ColorMatrix matrix
    let sat = 1.0;
    const cam = this.cameras.main as any;
    const fx = cam.postFX;
    this.time.addEvent({ delay: 100, repeat: 24, callback: () => {
      sat = Math.min(1.5, sat + 0.02);
      try {
        fx.clear();
        const cm = fx.addColorMatrix();
        const s = sat, sr=0.213, sg=0.715, sb=0.072;
        const m = [sr*(1-s)+s,sg*(1-s),sb*(1-s),0,0, sr*(1-s),sg*(1-s)+s,sb*(1-s),0,0, sr*(1-s),sg*(1-s),sb*(1-s)+s,0,0, 0,0,0,1,0];
        if (cm._data && cm._data.length===m.length) for(let i=0;i<m.length;i++) cm._data[i]=m[i]; else if(cm._data) cm._data=m.slice();
        cm._dirty = true;
      } catch(e){}
    }});
    this.showCaption(105, `「${ENDING_CAPTIONS.E1a}」`, '#ffd86b', 2000);
    this.showCaption(125, `「${ENDING_CAPTIONS.E1b}」`, '#ffaaaa', 3500);
    this.finish(6000);
  }

  finish(delay: number) {
    this.time.delayedCall(delay, () => {
      const btn = this.add.text(160, 165, '回到标题', { fontFamily:'monospace', fontSize:'10px', color:'#bfe3ff', backgroundColor:'#222222', padding:{x:8,y:4} }).setOrigin(0.5).setInteractive({ useHandCursor: true });
      btn.on('pointerover', () => btn.setStyle({ color:'#ffffff' }));
      btn.on('pointerout', () => btn.setStyle({ color:'#bfe3ff' }));
      btn.on('pointerdown', () => {
        audio.startMusic();
        this.scene.start('TitleScene');
      });
      this.input.keyboard!.on('keydown-ENTER', () => {
        audio.startMusic();
        this.scene.start('TitleScene');
      });
    });
  }
}
