// 湖畔（24×16）：长椅（龟爷爷）、野餐布（T7）、湖面倒影演出。
// D2 起湖面倒影延迟 1 帧（§5 Day 2 极轻异常）。

import Phaser from 'phaser';
import { MapScene } from './MapScene';
import { director } from '../core/CorruptionDirector';
import { audio } from '../audio/AudioEngine';
import { PICNIC_LINES, PICNIC_DONE } from '../data/dialogues';

export class LakeScene extends MapScene {
  readonly mapKey = 'lake';

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

  private mirror: Phaser.GameObjects.Sprite | null = null;
  private prevX = 0;
  private prevY = 0;
  private prevFrame = 0;
  private waterY = 0;

  protected onReady(): void {
    this.mirror = null;
    this.prevX = 0;
    this.prevY = 0;
    this.prevFrame = 0;
    // 动态找水面下缘（湖水瓦片 id 8/9/11/12/13 → gid 9/10/12/13/14）
    let maxRow = 6;
    const layer = this.obstacleLayer.layer;
    for (let y = 0; y < layer.height; y++) {
      for (let x = 0; x < layer.width; x++) {
        const t = this.obstacleLayer.getTileAt(x, y);
        if (t && [9, 10, 12, 13, 14].includes(t.index)) maxRow = Math.max(maxRow, y);
      }
    }
    this.waterY = (maxRow + 1) * 16;
    // 湖面倒影（D1 实时；D2 起延迟 1 帧）
    this.mirror = this.add.sprite(this.player.x, this.player.y, 'player', 0)
      .setOrigin(0.5, 0)
      .setFlipY(true)
      .setAlpha(0.28)
      .setTint(0x4fa8d8)
      .setDepth(1);
  }

  protected async onInteract(id: string): Promise<boolean> {
    if (id === 'picnic_mat') {
      if (director.isTaskActive('T7')) {
        await this.say({ lines: PICNIC_LINES });
        director.completeTask('T7');
        audio.ding();
      } else {
        await this.say({ lines: PICNIC_DONE });
      }
      return true;
    }
    return false;
  }

  protected extraUpdate(): void {
    if (!this.mirror) return;
    const day = director.day;
    const px = day >= 2 ? this.prevX : this.player.x;
    const py = day >= 2 ? this.prevY : this.player.y;
    const pf = day >= 2 ? this.prevFrame : this.player.frame.name;

    if (this.player.y > this.waterY + 40) {
      this.mirror.setVisible(false);
    } else {
      this.mirror.setVisible(true);
      this.mirror.setPosition(px, 2 * this.waterY - py);
      this.mirror.setFrame(Number(pf) || 0);
    }

    this.prevX = this.player.x;
    this.prevY = this.player.y;
    this.prevFrame = Number(this.player.frame.name) || 0;
  }
}
