import { Physics } from 'phaser';

export class Platform extends Physics.Arcade.Sprite {
  constructor(scene, x, y, type = 'stable') {
    super(scene, x, y, 'platform');
    scene.add.existing(this);
    scene.physics.add.existing(this, true);

    this.platformType = type;
    this.breakingState = 0;
    this.moveSpeed = 0;
    this.moveRange = 0;
    this.startX = x;
    this.glowTween = null;

    if (type === 'moving') {
      this.body.destroy();
      this.body = new Phaser.Physics.Arcade.Body(scene.physics.world, this);
      this.body.allowGravity = false;
      this.body.immovable = true;
      this.moveSpeed = Phaser.Math.Between(50, 120) * (Math.random() < 0.5 ? 1 : -1);
      this.moveRange = Phaser.Math.Between(60, 160);
    } else if (type === 'breaking') {
      this.setTint(0x999999);
    } else if (type === 'genesis') {
      this.setTint(0xffd700);
      this.genesisGlow = scene.add.ellipse(x, y + 10, 100, 30, 0xffd700, 0.25)
        .setDepth(this.depth - 1);
      this.glowTween = scene.tweens.add({
        targets: this.genesisGlow,
        scaleX: 1.4,
        scaleY: 1.4,
        alpha: 0.1,
        duration: 800,
        yoyo: true,
        repeat: -1,
      });
    }
  }

  preUpdate(time, delta) {
    super.preUpdate(time, delta);
    if (this.platformType === 'moving' && this.body) {
      this.setVelocityX(this.moveSpeed);
      if (Math.abs(this.x - this.startX) > this.moveRange) {
        this.moveSpeed *= -1;
      }
      if (this.genesisGlow) this.genesisGlow.setPosition(this.x, this.y + 10);
    }
  }

  onPlayerLand(player) {
    if (this.platformType === 'breaking') {
      if (this.breakingState > 0) return false;
      this.breakingState = 2;
      this.disableBody(true, false);
      this.scene.tweens.add({
        targets: this,
        alpha: 0,
        scaleX: 0.3,
        scaleY: 0.1,
        duration: 250,
        onComplete: () => this.destroy(),
      });
      return true;
    }
    return true;
  }

  isBroken() {
    return this.breakingState >= 2;
  }

  destroy(fromScene) {
    if (this.glowTween) {
      this.glowTween.stop();
      this.glowTween = null;
    }
    if (this.genesisGlow) {
      this.genesisGlow.destroy();
      this.genesisGlow = null;
    }
    super.destroy(fromScene);
  }
}
