class Player extends Sprite {
    constructor(x, y, width = 40, height = 50, imagePath = null) {
        super(x, y, width, height);
        this.vx = 0;
        this.vy = 0;
        this.speed = 4;
        this.jumpStrength = 12;
        this.gravity = 0.6;
        this.maxFallSpeed = 10;
        this.onGround = false;
        this.invincible = false;
        this.invincibleTime = 0;

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

    update(sprites, input, mouse) {
        // Handle invincibility
        if (this.invincible) {
            this.invincibleTime--;
            if (this.invincibleTime <= 0) {
                this.invincible = false;
            }
        }

        this.vx = 0;
        if (input.isKeyDown('ArrowLeft')) this.vx = -this.speed;
        if (input.isKeyDown('ArrowRight')) this.vx = this.speed;
        if ((input.isKeyPressed('Space') || input.isKeyPressed('ArrowUp')) && this.onGround) {
            this.vy = -this.jumpStrength;
        }

        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.y += this.vy;
        this.onGround = false;
        for (let s of sprites) {
            if (s !== this && s.isSolid && CollisionManager.isColliding(this, s)) {
                if (this.vy > 0) {
                    this.y = s.y - this.height;
                    this.onGround = true;
                    this.vy = 0;
                } else if (this.vy < 0) {
                    this.y = s.y + s.height;
                    this.vy = 0;
                }
            }
        }

        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 = 'blue';
            ctx.fillRect(this.x, this.y, this.width, this.height);
        }
    }
}
