class Enemy extends Sprite {
    constructor(x, y, width = 40, height = 40, imagePath = null) {
        super(x, y, width, height);
        this.vx = -1.5;
        this.vy = 0;
        this.gravity = 0.6;
        this.maxFallSpeed = 10;

        this.image = null;
        if (imagePath) {
            this.image = new Image();
            this.image.src = imagePath;
        }
    }

    update(sprites) {
        this.vy += this.gravity;
        if (this.vy > this.maxFallSpeed) this.vy = this.maxFallSpeed;

        this.x += this.vx;
        for (let s of sprites) {
            if (s !== this && s.isSolid && CollisionManager.isColliding(this, s)) {
                if (this.vx > 0) this.x = s.x - this.width;
                else if (this.vx < 0) this.x = s.x + s.width;
                this.vx = -this.vx;
            }
        }

        this.y += this.vy;
        for (let s of sprites) {
            if (s !== this && s.isSolid && CollisionManager.isColliding(this, s)) {
                if (this.vy > 0) this.y = s.y - this.height;
                else if (this.vy < 0) this.y = s.y + s.height;
                this.vy = 0;
            }
        }

        const score = sprites.find(s => s instanceof Score);
        const life = sprites.find(s => s instanceof Life);

        for (let s of sprites) {
            if (s instanceof Player && CollisionManager.isColliding(this, s)) {
                const playerBottom = s.y + s.height;
                const enemyTop = this.y;

                if (s.vy > 0 && playerBottom <= enemyTop + 10) {
                    // Player landed on top
                    return true; // remove enemy
                    s.vy = -s.jumpStrength / 2;
                    if (score) score.add(50);
                } else {
                    // Side or bottom hit
                    if (!s.invincible && life) {
                        life.lose();
                        s.invincible = true;
                        s.invincibleTime = 60;
                        return true;
                    }
                }
            }
        }

        return false;
    }

    draw(ctx) {
        if (this.image && this.image.complete) {
            ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
        } else {
            ctx.fillStyle = 'red';
            ctx.fillRect(this.x, this.y, this.width, this.height);
        }
    }
}
