import { Physics } from 'phaser';
import { GAME_WIDTH } from '../config/game.config.js';
import { rng } from '../utils/random.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 = rng.between(60, 140) * rng.sign();
      this.startX = x;
      this.patrolRange = rng.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 = rng.between(80, 140);
      this.driftAmplitude = rng.between(20, 60);
      this.driftFreq = rng.realBetween(0.001, 0.003);
      this.spawnTime = scene.time.now;
      this.spawnX = x;
    } else if (type === 'mev_bot') {
      // Homing chaser: eases toward the player's X. Stompable like the rest.
      this.setScale(0.6);
      this.setTint(0x22d3ee);
      this.body.setSize(this.width * 0.65, this.height * 0.65);
      this.body.setOffset(this.width * 0.18, this.height * 0.18);
      this.homeSpeed = rng.between(70, 120);
      this.bobAmp = rng.between(4, 10);
      this.baseY = y;
      this.spawnTime = scene.time.now;
    }
  }

  preUpdate(time, delta) {
    super.preUpdate(time, delta);
    const dt = delta / 1000;

    if (this.enemyType === 'bug') {
      this.x += this.speed * dt;
      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') {
      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);
    } else if (this.enemyType === 'mev_bot') {
      const player = this.scene.player;
      if (player && player.active) {
        const dir = Math.sign(player.x - this.x);
        this.x += dir * this.homeSpeed * dt;
        this.setFlipX(dir < 0);
      }
      this.x = Phaser.Math.Clamp(this.x, 24, GAME_WIDTH - 24);
      const t = time - this.spawnTime;
      this.y = this.baseY + Math.sin(t * 0.004) * this.bobAmp;
    }
  }
}
