class InputManager {
    constructor(canvas) {
        this.canvas = canvas;
        this.keys = {};
        this.keysPressed = {};
        this.mouse = { x: 0, y: 0, down: false, clicked: false };
        this._initKeyboard();
        this._initMouse();
    }

    _initKeyboard() {
        window.addEventListener('keydown', e => {
            if (!this.keys[e.code]) this.keysPressed[e.code] = true;
            this.keys[e.code] = true;
        });
        window.addEventListener('keyup', e => {
            this.keys[e.code] = false;
        });
    }

    _initMouse() {
        this.canvas.addEventListener("mousemove", e => {
            const rect = this.canvas.getBoundingClientRect();
            this.mouse.x = e.clientX - rect.left;
            this.mouse.y = e.clientY - rect.top;
        });
    
        this.canvas.addEventListener("mousedown", () => {
            this.mouse.down = true;
            this.mouse.clicked = true; // single click flag
        });
    
        this.canvas.addEventListener("mouseup", () => {
            this.mouse.down = false;
        });
    
        this.canvas.addEventListener("mouseleave", () => {
            this.mouse.down = false;
        });
    }
    

    isKeyDown(code) { return this.keys[code]; }
    isKeyPressed(code) { return this.keysPressed[code]; }
    reset() {
        this.keysPressed = {};
        this.mouse.clicked = false; // clear click after one frame
    }
}
