// NPC 与群演行为组件（PRD §4 / §6.4）。
// 表情档：0=smile 1=flat 2=off，按阶段 + 个体阈值偏移切换；
// S3 起静止 NPC 面朝玩家（flipX）；S4：off 档 0.6 次/分钟闪 0.1 秒、群演随机 1 只停摆；
// 双子鸟张嘴动画循环（S4 照张）；阶段切换时鸟动画卡帧一下。

import Phaser from 'phaser';
import { NPC_DEFS, stageOf, type NpcDef, type NpcId, type Stage } from '../types';
import { director } from '../core/CorruptionDirector';

const FACE_FRAME: Record<number, number> = { 0: 0, 1: 0, 2: 0, 3: 1, 4: 1 }; // 阶段→表情帧（S4 基础 flat，off 靠闪）

export class NpcActor {
  readonly def: NpcDef;
  readonly sprite: Phaser.Physics.Arcade.Sprite;
  readonly isExtra: boolean;

  private scene: Phaser.Scene;
  /** 群演巡走范围 */
  private patrolLeft = 0;
  private patrolRight = 0;
  private patrolDir = 1;
  private patrolSpeed = 24;
  /** S4 停摆标记（每场景 1 只） */
  stalled = false;
  /** S4 off 档闪帧计时 */
  private offFlashMs = 0;
  /** 被「悲伤行为」惊动，转头看玩家计时 */
  private glanceMs = 0;
  /** T14 全村注视 */
  stareAtPlayer = false;

  constructor(scene: Phaser.Scene, id: NpcId, x: number, y: number) {
    this.scene = scene;
    this.def = NPC_DEFS[id];
    this.isExtra = this.def.isExtra;
    this.sprite = scene.physics.add.sprite(x, y, this.def.spriteKey, 0);
    this.sprite.setOrigin(0.5, 1);
    this.sprite.setImmovable(true);
    (this.sprite.body as Phaser.Physics.Arcade.Body).setAllowGravity(false);
    this.sprite.setSize(12, 8).setOffset(2, 16);

    if (this.isExtra) {
      this.patrolLeft = x - 32;
      this.patrolRight = x + 32;
      const anim = `${this.def.spriteKey}-walk`;
      if (scene.anims.exists(anim)) this.sprite.play(anim);
    } else if (id === 'bird') {
      if (scene.anims.exists('bird-sing')) this.sprite.play('bird-sing');
    }
  }

  /** 悲伤行为触发：转头看玩家一次 */
  glanceAt(playerX: number): void {
    this.glanceMs = 1200;
    this.sprite.setFlipX(playerX < this.sprite.x);
  }

  update(deltaMs: number, player: Phaser.Physics.Arcade.Sprite): void {
    const stage = director.stage;
    this.sprite.setDepth(this.sprite.y);

    if (this.isExtra) {
      this.updateExtra(deltaMs, player, stage);
    } else {
      this.updateNamed(deltaMs, player, stage);
    }
  }

  private updateNamed(deltaMs: number, player: Phaser.Physics.Arcade.Sprite, stage: Stage): void {
    // 表情档（芙医生/龟爷爷/双子鸟不参与侵蚀）
    if (this.def.expressive) {
      const effStage = stageOf(director.happiness - this.def.offset);
      let frame = FACE_FRAME[effStage];
      if (this.offFlashMs > 0) {
        frame = 2; // off 档闪现
        this.offFlashMs -= deltaMs;
      } else if (effStage === 4) {
        // S4：0.6 次/分钟闪 0.1 秒 → 每秒约 1% 概率触发
        if (Math.random() < (0.6 / 60) * (deltaMs / 1000)) this.offFlashMs = 100;
      }
      this.sprite.setFrame(frame);
    }

    // S3 起静止 NPC 面朝玩家；被惊动时也面朝玩家
    const facePlayer = stage >= 3 || this.glanceMs > 0 || this.stareAtPlayer;
    if (facePlayer && this.def.id !== 'bird') {
      this.sprite.setFlipX(player.x < this.sprite.x);
    }
    if (this.glanceMs > 0) this.glanceMs -= deltaMs;
  }

  private updateExtra(deltaMs: number, player: Phaser.Physics.Arcade.Sprite, stage: Stage): void {
    if (this.stalled) {
      // S4 停摆：原地面朝玩家
      this.sprite.setVelocity(0);
      this.sprite.setFrame(0);
      this.sprite.setFlipX(player.x < this.sprite.x);
      return;
    }
    const x = this.sprite.x;
    if (x <= this.patrolLeft) this.patrolDir = 1;
    if (x >= this.patrolRight) this.patrolDir = -1;
    this.sprite.setVelocityX(this.patrolDir * this.patrolSpeed);
    this.sprite.setFlipX(this.patrolDir < 0);
    if (stage >= 3) {
      // S3 起也会偶尔看向玩家？契约只要求 S4 停摆，巡走继续
    }
    void deltaMs;
  }

  destroy(): void {
    this.sprite.destroy();
  }
}

/** 群演停摆选择：S4 起随机 1 只停止循环 */
export function pickStallExtra(actors: NpcActor[]): NpcActor | null {
  const extras = actors.filter((a) => a.isExtra);
  if (extras.length === 0) return null;
  return extras[Math.floor(Math.random() * extras.length)];
}
