import { PHYSICS } from '@/config/physics.config';
import { BaseEnemy } from './BaseEnemy';

export class Flyer extends BaseEnemy {
  private moveDirection: 1 | -1 = 1;
  private startX: number;
  private startY: number;
  private patrolDistance = 200;
  private flyTime = 0;

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

    this.startX = x;
    this.startY = y;
    this.setTint(0x8888ff); // Blue tint to distinguish

    // Disable gravity for flyer
    const body = this.body as Phaser.Physics.Arcade.Body;
    body.setAllowGravity(false);
  }

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

    this.flyTime = time * 0.003; // Convert to seconds and slow down

    // Horizontal movement
    body.setVelocityX(PHYSICS.enemies.flyer.speed * this.moveDirection);

    // Sine wave vertical movement
    const targetY = this.startY + Math.sin(this.flyTime) * PHYSICS.enemies.flyer.amplitude;
    const dy = targetY - this.y;
    body.setVelocityY(dy * 5); // Smooth movement towards target

    // 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(0x8888ff); // Restore blue tint
  }

  public stun(duration?: number): void {
    super.stun(duration);
    // Re-enable gravity when stunned to fall
    const body = this.body as Phaser.Physics.Arcade.Body;
    body.setAllowGravity(true);
  }

  protected recoverFromStun(): void {
    // Disable gravity again when recovered
    const body = this.body as Phaser.Physics.Arcade.Body;
    body.setAllowGravity(false);
    this.startY = this.y; // Update start Y to current position
  }
}
