import { playSfx, primeSfx } from "../game/sfx.js";

/**
 * Setup input handlers for keyboard and pointer events
 * @param {HTMLCanvasElement} canvas
 * @param {Object} state - Shared game state
 * @param {Object} callbacks - Event callbacks
 */
export function setupInputHandlers(canvas, state, callbacks) {
    // Pointer lock helper
    function requestPointerLockSafely() {
        const cameraMode = callbacks.getCameraMode?.() || "fp";
        if (cameraMode !== "fp" || document.pointerLockElement === canvas) {
            return;
        }

        try {
            const lockResult = canvas.requestPointerLock();
            if (lockResult && typeof lockResult.catch === "function") {
                lockResult.catch((error) => {
                    if (error && error.name === "SecurityError") {
                        state.runtime.message = "Click once more to re-enable mouse look.";
                        return;
                    }
                    console.warn(error);
                });
            }
        } catch (error) {
            if (error && error.name === "SecurityError") {
                state.runtime.message = "Click once more to re-enable mouse look.";
                return;
            }
            console.warn(error);
        }
    }

    // Canvas click for pointer lock
    canvas.addEventListener("click", () => {
        primeSfx();
        requestPointerLockSafely();
    });

    // Keyboard input
    window.addEventListener("keydown", (event) => {
        // Prime audio context on common movement keys
        if (event.code === "KeyW" || event.code === "KeyA" || event.code === "KeyS" || event.code === "KeyV" || event.code === "KeyR") {
            primeSfx();
        }

        // Debug panel toggle
        if (event.code === "KeyB") {
            callbacks.onDebugToggle?.();
            return;
        }

        // Restart or start game
        if (event.code === "KeyR") {
            const gameOverActive = callbacks.isGameOverActive?.() || false;
            const startPanelVisible = callbacks.isStartPanelVisible?.() || false;
            
            if (gameOverActive) {
                callbacks.onRestart?.();
            } else if (!state.runtime.runActive && startPanelVisible) {
                callbacks.onStartGame?.();
            }
            return;
        }

        // Camera mode toggle
        if (event.code === "KeyV") {
            callbacks.onCameraToggle?.();
        }
    });

    // Pointer interaction for chests
    if (callbacks.setupScenePointerObserver) {
        callbacks.setupScenePointerObserver();
    }
}
