// 古井空地（14×10）：古井（C7，D5 起，交互聆听 5 秒；D5 前被 NPC 温柔劝离）。
// 注视古井 5 秒（每日 1 次 +3 觉知）。

import Phaser from 'phaser';
import { MapScene } from './MapScene';
import { director } from '../core/CorruptionDirector';
import { audio } from '../audio/AudioEngine';
import { CLUES } from '../data/clues';
import { WELL_DISSUADE, WELL_LISTEN_START } from '../data/dialogues';

export class WellScene extends MapScene {
  readonly mapKey = 'well';

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

  private stareMs = 0;
  private listening = false;

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

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

    if (director.day < 5) {
      // D5 前：被 NPC 温柔劝离
      await this.say({ lines: WELL_DISSUADE });
      return true;
    }

    if (this.listening) return true;
    this.listening = true;
    await this.say({ lines: WELL_LISTEN_START });
    // 交互 5 秒：井底回声——极轻的监护仪滴声
    for (let i = 0; i < 5; i++) {
      audio.ecgSoft();
      await this.wait(1000);
    }
    director.addClue('C7');
    await this.say({ lines: CLUES.C7.lines });
    this.listening = false;
    return true;
  }

  protected extraUpdate(_time: number, delta: number): void {
    if (director.day < 5 || this.listening) return;
    const z = this.interactZones.find((zz) => zz.id === 'ancient_well');
    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; // 每日一次由 director 判定；本地只触发一次
        if (director.registerStare('well')) {
          void this.say({ lines: ['你盯着井口看了很久。', '井水黑得不像水。'] });
        }
      }
    } else if (this.stareMs > 0) {
      this.stareMs = 0;
    }
  }
}
