import { Physics } from 'phaser';
import { GAME_WIDTH } from '../config/game.config.js';

export class Enemy extends Physics.Arcade.Sprite {
  constructor(scene, x, y, type = 'bug') {
    super(scene, x, y, 'enemy_bug');
    scene.add.existing(this);
    scene.physics.add.existing(this);

    this.enemyType = type;
    this.body.allowGravity = false;

    if (type === 'bug') {
      this.setScale(0.7);
      this.body.setSize(this.width * 0.7, this.height * 0.7);
      this.body.setOffset(this.width * 0.15, this.height * 0.15);
      this.speed = Phaser.Math.Between(60, 140) * (Math.random() < 0.5 ? 1 : -1);
      this.startX = x;
      this.patrolRange = Phaser.Math.Between(80, 200);
    } else if (type === 'failed_tx') {
      this.setScale(0.55);
      this.setTint(0xef4444);
      this.body.setSize(this.width * 0.6, this.height * 0.6);
      this.body.setOffset(this.width * 0.2, this.height * 0.2);
      this.fallSpeed = Phaser.Math.Between(80, 140);
      this.driftAmplitude = Phaser.Math.Between(20, 60);
      this.driftFreq = Phaser.Math.FloatBetween(0.001, 0.003);
      this.spawnTime = scene.time.now;
      this.spawnX = x;
    }
  }

  preUpdate(time, delta) {
    super.preUpdate(time, delta);

    if (this.enemyType === 'bug') {
      this.x += this.speed * (delta / 1000);
      if (Math.abs(this.x - this.startX) > this.patrolRange) {
        this.speed *= -1;
        this.setFlipX(this.speed < 0);
      }
      if (this.x < -60) this.x = GAME_WIDTH + 60;
      if (this.x > GAME_WIDTH + 60) this.x = -60;
    } else if (this.enemyType === 'failed_tx') {
      const dt = delta / 1000;
      this.y += this.fallSpeed * dt;
      const t = time - this.spawnTime;
      this.x = this.spawnX + Math.sin(t * this.driftFreq) * this.driftAmplitude;
      this.x = Phaser.Math.Clamp(this.x, 30, GAME_WIDTH - 30);
      this.setAngle(Math.sin(t * 0.005) * 15);
    }
  }
}
