import Phaser from 'phaser';

export class Saw extends Phaser.Physics.Arcade.Sprite {
  private startX: number;
  private startY: number;
  private moveDirection: 1 | -1 = 1;
  private patrolDistance: number;
  private speed = 150;
  private rotationSpeed = 10;
  private isVertical: boolean;

  constructor(scene: Phaser.Scene, x: number, y: number, patrolDistance = 100, vertical = false) {
    super(scene, x, y, 'spikes'); // Use spikes texture, we'll make it circular

    this.startX = x;
    this.startY = y;
    this.patrolDistance = patrolDistance;
    this.isVertical = vertical;

    scene.add.existing(this);
    scene.physics.add.existing(this);

    const body = this.body as Phaser.Physics.Arcade.Body;
    body.setAllowGravity(false);
    body.setImmovable(true);
    body.setCircle(14); // Circular hitbox
    body.setOffset(1, 1);

    this.setTint(0xff6666); // Red tint
  }

  update(_time: number, delta: number): void {
    const body = this.body as Phaser.Physics.Arcade.Body;

    // Rotate
    this.rotation += this.rotationSpeed * delta * 0.001;

    // Move
    if (this.isVertical) {
      body.setVelocity(0, this.speed * this.moveDirection);

      // Check patrol bounds
      if (this.y > this.startY + this.patrolDistance) {
        this.moveDirection = -1;
      } else if (this.y < this.startY - this.patrolDistance) {
        this.moveDirection = 1;
      }
    } else {
      body.setVelocity(this.speed * this.moveDirection, 0);

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