import Phaser from 'phaser';
import { PHYSICS } from '@/config/physics.config';
import { BaseEnemy } from './BaseEnemy';
import type { Player } from '../Player';

export class Chaser extends BaseEnemy {
  private moveDirection: 1 | -1 = 1;
  private startX: number;
  private patrolDistance = 100;
  private isChasing = false;
  private player: Player | null = null;

  constructor(scene: Phaser.Scene, x: number, y: number) {
    super(scene, x, y, 'enemy');

    this.startX = x;
    this.setTint(0xff8888); // Red tint to distinguish
  }

  public setPlayer(player: Player): void {
    this.player = player;
  }

  protected updateBehavior(): void {
    const body = this.body as Phaser.Physics.Arcade.Body;

    // Check if player is in detection range
    if (this.player && !this.player.isDead) {
      const dx = this.player.x - this.x;
      const dy = this.player.y - this.y;
      const distance = Math.sqrt(dx * dx + dy * dy);

      if (distance < PHYSICS.enemies.chaser.detectionRange) {
        this.isChasing = true;

        // Chase player
        const chaseSpeed = PHYSICS.enemies.chaser.speed * 2; // Faster when chasing
        if (dx > 0) {
          body.setVelocityX(chaseSpeed);
          this.setFlipX(false);
        } else {
          body.setVelocityX(-chaseSpeed);
          this.setFlipX(true);
        }

        // Pulse effect when chasing
        if (!this.scene.tweens.isTweening(this)) {
          this.scene.tweens.add({
            targets: this,
            scaleX: 1.1,
            scaleY: 0.9,
            duration: 200,
            yoyo: true,
            repeat: 0,
          });
        }

        return;
      }
    }

    // Return to patrol if was chasing
    if (this.isChasing) {
      this.isChasing = false;
    }

    // Normal patrol
    body.setVelocityX(PHYSICS.enemies.chaser.speed * this.moveDirection);

    // Check patrol bounds
    if (this.x > this.startX + this.patrolDistance) {
      this.moveDirection = -1;
      this.setFlipX(true);
    } else if (this.x < this.startX - this.patrolDistance) {
      this.moveDirection = 1;
      this.setFlipX(false);
    }

    // Check for walls
    if (body.blocked.right) {
      this.moveDirection = -1;
      this.setFlipX(true);
    } else if (body.blocked.left) {
      this.moveDirection = 1;
      this.setFlipX(false);
    }
  }

  protected recover(): void {
    super.recover();
    this.setTint(0xff8888); // Restore red tint
  }
}
