// HouseScene.ts: 小满小屋. Bed (sleep to advance day), calendar (C1), door to plaza.
import Phaser from 'phaser';
import { MapScene } from '../MapScene';
import { director } from '../../systems/CorruptionDirector';
import { story } from '../../systems/StoryDirector';
import { audio } from '../../systems/AudioEngine';
import { CLUES } from '../../data/gamedata';

export class HouseScene extends MapScene {
  constructor() { super('HouseScene', 'map:house', 'house'); }

  onBuild(map: Phaser.Tilemaps.Tilemap, ts: Phaser.Tilemaps.Tileset) {
    // sleep point
    this.addInteract(6, 5, () => this.sleep(), { promptText: '按 E 睡觉' });
    // calendar C1 (from D2)
    this.addInteract(2, 0, () => {
      const avail = director.day >= 2;
      if (avail) {
        const got = director.discoverClue('C1');
        this.say([{ speaker:'', text: got ? '日历上每一页都是同一个日期……' : '日历上还是同一个日期。' }]);
      } else {
        this.say([{ speaker:'', text: '今天的日历，崭新的一页。' }]);
      }
    }, { promptText: '按 E 看日历' });
    // bed interaction (also can sleep)
    this.addInteract(1, 5, () => this.sleep(), { promptText: '按 E 睡觉' });

    // if just spawned 'default' -> it's a new-game start: morning of Day 1
    if (this.pendingSpawn === 'default' && director.day === 1) {
      story.resetDay();
      this.time.delayedCall(400, () => {
        this.say([{ speaker:'', text:`第 ${director.day} 天的清晨。阳光真好。` }]);
      });
    }
  }

  sleep() {
    if (director.day >= 7) {
      // go to festival / ending
      this.runEnding();
      return;
    }
    // dream sequence then advance day
    this.dreamSequence(() => {
      director.advanceDay();
      story.resetDay();
      // re-spawn into house morning
      this.scene.restart({ spawn: 'default' });
    });
  }

  dreamSequence(onDone: ()=>void) {
    const stage = director.stage;
    // S3+ : brief white ward flash 1s
    let flash = false;
    if (stage === 'S3' || stage === 'S4') flash = true;
    const overlay = this.add.rectangle(160, 90, 320, 180, 0xffffff, 0).setScrollFactor(0).setDepth(6000);
    this.tweens.add({ targets: overlay, alpha: flash ? 0.9 : 0.0, duration: flash ? 700 : 200, yoyo: flash, hold: 200,
      onComplete: () => { overlay.destroy(); onDone(); } });
  }

  runEnding() {
    this.scene.stop('UIScene');
    this.scene.stop('DebugScene');
    this.scene.start('EndingScene', { ending: director.determineEnding() });
  }
}
