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

export class Projectile extends Phaser.Physics.Arcade.Sprite {
  private lifetime: number;
  private direction: number;

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

    this.lifetime = PHYSICS.projectile.lifetime;
    this.direction = direction;

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

    // Spawn effect
    this.setScale(0.5);
    scene.tweens.add({
      targets: this,
      scaleX: 1,
      scaleY: 1,
      duration: 100,
      ease: 'Back.out',
    });
  }

  // Call this AFTER adding to group
  launch(): void {
    const body = this.body as Phaser.Physics.Arcade.Body;
    body.setAllowGravity(false);
    body.setVelocityX(PHYSICS.projectile.speed * this.direction);
  }

  update(_time: number, delta: number): void {
    this.lifetime -= delta;

    if (this.lifetime <= 0) {
      this.fadeOut();
    }
  }

  private fadeOut(): void {
    this.scene.tweens.add({
      targets: this,
      alpha: 0,
      scaleX: 0.5,
      scaleY: 0.5,
      duration: 100,
      onComplete: () => {
        this.destroy();
      },
    });
  }
}
