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.setScale(0.7);
    this.body.allowGravity = false;
    this.body.setSize(90, 80);
    this.body.setOffset(35, 30);

    if (type === 'bug') {
      this.speed = Phaser.Math.Between(60, 140) * (Math.random() < 0.5 ? 1 : -1);
      this.startX = x;
      this.patrolRange = Phaser.Math.Between(80, 200);
    }
  }

  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);
      }
      // Wrap
      if (this.x < -60) this.x = GAME_WIDTH + 60;
      if (this.x > GAME_WIDTH + 60) this.x = -60;
    }
  }
}
