import Phaser from 'phaser';

export class Coin extends Phaser.Physics.Arcade.Sprite {
  private collected = false;
  private spawnX: number;
  private spawnY: number;
  private floatTween: Phaser.Tweens.Tween | null = null;
  private pulseTween: Phaser.Tweens.Tween | null = null;
  private isMagnetized = false;

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

    this.spawnX = x;
    this.spawnY = y;

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

    const body = this.body as Phaser.Physics.Arcade.Body;
    body.setAllowGravity(false);
    body.setImmovable(true);

    this.startIdleAnimation();
  }

  private startIdleAnimation(): void {
    // Random delay to desync animations between coins
    const floatDelay = Math.random() * 1000;
    const pulseDelay = Math.random() * 500;

    // Idle animation - gentle float
    this.floatTween = this.scene.tweens.add({
      targets: this,
      y: this.spawnY - 5,
      duration: 1000,
      yoyo: true,
      repeat: -1,
      ease: 'Sine.inOut',
      delay: floatDelay,
    });

    // Pulse effect
    this.pulseTween = this.scene.tweens.add({
      targets: this,
      scaleX: 1.1,
      scaleY: 1.1,
      duration: 500,
      yoyo: true,
      repeat: -1,
      ease: 'Sine.inOut',
      delay: pulseDelay,
    });
  }

  private stopIdleAnimation(): void {
    if (this.floatTween) {
      this.floatTween.stop();
      this.floatTween = null;
    }
    if (this.pulseTween) {
      this.pulseTween.stop();
      this.pulseTween = null;
    }
  }

  // Вызывается когда монета в радиусе магнита
  public magnetize(vx: number, vy: number): void {
    if (!this.isMagnetized) {
      this.isMagnetized = true;
      this.stopIdleAnimation();
    }
    this.setVelocity(vx, vy);
  }

  // Вызывается каждый кадр для возврата к оригинальной позиции
  public updateMagnetState(isInMagnetRange: boolean): void {
    if (this.collected) return;

    if (!isInMagnetRange && this.isMagnetized) {
      // Монета вышла из радиуса магнита - возвращаем к оригинальной позиции
      const dx = this.spawnX - this.x;
      const dy = this.spawnY - this.y;
      const distance = Math.sqrt(dx * dx + dy * dy);

      if (distance < 5) {
        // Достигли оригинальной позиции
        this.setPosition(this.spawnX, this.spawnY);
        this.setVelocity(0, 0);
        this.isMagnetized = false;
        this.startIdleAnimation();
      } else {
        // Двигаемся к оригинальной позиции
        const speed = 200;
        const vx = (dx / distance) * speed;
        const vy = (dy / distance) * speed;
        this.setVelocity(vx, vy);
      }
    }
  }

  public collect(): boolean {
    if (this.collected) return false;
    this.collected = true;

    // Collection animation
    this.scene.tweens.killTweensOf(this);

    this.scene.tweens.add({
      targets: this,
      y: this.y - 30,
      alpha: 0,
      scaleX: 1.5,
      scaleY: 1.5,
      duration: 200,
      ease: 'Power2',
      onComplete: () => {
        this.destroy();
      },
    });

    return true;
  }

  public isCollected(): boolean {
    return this.collected;
  }
}
