// Player.ts: the player sprite with 4-direction walk + idle animations.
import Phaser from 'phaser';
import { MOVE_SPEED } from '../data/gamedata';

export type Dir = 'down'|'up'|'left'|'right';

export class Player extends Phaser.Physics.Arcade.Sprite {
  dir: Dir = 'down';
  moving = false;
  lastMoveTime = 0;
  // track idleness for 发呆 detection
  idleSince = 0;
  atTaskPoint = false;
  // movement keys, created lazily/refreshed to avoid stale references across scene transitions
  private kLeft!: Phaser.Input.Keyboard.Key;
  private kRight!: Phaser.Input.Keyboard.Key;
  private kUp!: Phaser.Input.Keyboard.Key;
  private kDown!: Phaser.Input.Keyboard.Key;

  constructor(scene: Phaser.Scene, x: number, y: number) {
    super(scene, x, y, 'player', 0);
    scene.add.existing(this);
    scene.physics.add.existing(this);
    this.setSize(12, 8);
    this.setOffset(2, 16); // collision box near feet
    this.setOrigin(0.5, 0.9);
    this.setCollideWorldBounds(true);
    this.play('idle-down');
    this.refreshKeys();
  }

  // (Re)create movement keys on this scene's keyboard plugin so isDown stays accurate.
  refreshKeys() {
    const kb = this.scene.input.keyboard!;
    const KC = Phaser.Input.Keyboard.KeyCodes;
    this.kLeft = kb.addKey(KC.LEFT);
    this.kRight = kb.addKey(KC.RIGHT);
    this.kUp = kb.addKey(KC.UP);
    this.kDown = kb.addKey(KC.DOWN);
    // also register WASD via addKey (capture=false so browser default can still work)
    this.addWASD();
  }
  private wasdKeys: Phaser.Input.Keyboard.Key[] = [];
  private addWASD() {
    const kb = this.scene.input.keyboard!;
    const KC = Phaser.Input.Keyboard.KeyCodes;
    this.wasdKeys = [
      kb.addKey(KC.W), kb.addKey(KC.A), kb.addKey(KC.S), kb.addKey(KC.D),
    ];
  }

  update() {
    // frozen: T14 smile task locks movement
    if ((this as any).frozen) {
      this.setVelocity(0, 0);
      this.moving = false;
      this.play(`idle-${this.dir}`, true);
      this.setDepth(this.y);
      return;
    }
    // ensure keys are alive (recreate if detached)
    if (!this.kLeft || this.kLeft.plugin == null) this.refreshKeys();

    let vx = 0, vy = 0;
    const left = this.kLeft.isDown || this.wasdKeys[1].isDown;
    const right = this.kRight.isDown || this.wasdKeys[3].isDown;
    const up = this.kUp.isDown || this.wasdKeys[0].isDown;
    const down = this.kDown.isDown || this.wasdKeys[2].isDown;
    if (left) vx = -1;
    if (right) vx = 1;
    if (up) vy = -1;
    if (down) vy = 1;
    if (vx !== 0 && vy !== 0) { vx *= 0.7071; vy *= 0.7071; }
    this.setVelocity(vx * MOVE_SPEED, vy * MOVE_SPEED);

    const wasMoving = this.moving;
    if (vx !== 0 || vy !== 0) {
      this.moving = true;
      this.lastMoveTime = this.scene.time.now;
      let newDir = this.dir;
      if (Math.abs(vx) > Math.abs(vy)) newDir = vx > 0 ? 'right' : 'left';
      else newDir = vy > 0 ? 'down' : 'up';
      if (newDir !== this.dir || !wasMoving) {
        this.dir = newDir;
        this.play(`walk-${newDir}`, true);
      }
    } else {
      this.moving = false;
      this.play(`idle-${this.dir}`, true);
    }
    this.setDepth(this.y);
  }
}
