// 雾墙边界（20×8）：村庄尽头的雾。D5 前不可接近（广场门劝离）；
// D5 起可交互；注视 5 秒每日 +3 觉知；D7 且满足 E3 条件时走向雾墙 → 白色走廊。

import Phaser from 'phaser';
import { MapScene } from './MapScene';
import { director } from '../core/CorruptionDirector';
import { FOG_DISSUADE, FOG_WALL_LINES, FOG_WALL_BLOCKED } from '../data/dialogues';
import { E3_WALK_SUBTITLES } from '../data/endings';

export class FogScene extends MapScene {
  readonly mapKey = 'fog';

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

  private stareMs = 0;

  protected onReady(): void {
    this.stareMs = 0;
  }

  protected async onInteract(id: string): Promise<boolean> {
    if (id !== 'fog_wall') return false;

    if (director.day < 5) {
      await this.say({ lines: FOG_DISSUADE });
      return true;
    }

    // D7：E3 苏醒——庆典中走向雾墙（觉知 ≥70 且线索 ≥6/9）
    if (director.day === 7) {
      if (director.awareness >= 70 && director.clues.size >= 6) {
        director.startEnding('E3');
        await this.say({ lines: E3_WALK_SUBTITLES });
        this.cameras.main.fadeOut(1200, 255, 255, 255);
        this.cameras.main.once('camerafadeoutcomplete', () => {
          this.scene.start('WhiteScene', { e3: true });
        });
      } else {
        await this.say({ lines: FOG_WALL_BLOCKED });
      }
      return true;
    }

    await this.say({ lines: FOG_WALL_LINES });
    return true;
  }

  protected extraUpdate(_time: number, delta: number): void {
    if (director.day < 5) return;
    const z = this.interactZones.find((zz) => zz.id === 'fog_wall');
    if (!z) return;
    const d = Phaser.Math.Distance.Between(this.player.x, this.player.y - 8, z.x, z.y);
    const still = (this.player.body?.velocity.lengthSq() ?? 0) <= 1;
    if (d <= 40 && still && !director.dialogueActive) {
      this.stareMs += delta;
      if (this.stareMs >= 5000) {
        this.stareMs = -1e9;
        if (director.registerStare('fog')) {
          void this.say({ lines: ['你盯着雾墙看了很久。', '雾的后面，好像有什么在看你。'] });
        }
      }
    } else if (this.stareMs > 0) {
      this.stareMs = 0;
    }
  }
}
