import * as BABYLON from "babylonjs";

/**
 * Check which chest the player is looking at
 * @param {BABYLON.Scene} scene
 * @param {BABYLON.Camera} fpCamera
 * @param {number} maxDistance
 * @returns {{chest: BABYLON.Mesh, index: string} | null}
 */
export function checkChestRaycast(scene, fpCamera, maxDistance = 50) {
    const targetRay = fpCamera.getForwardRay(maxDistance);
    const targetPick = scene.pickWithRay(targetRay, (mesh) => mesh.name.startsWith('chest_'));
    
    if (targetPick && targetPick.hit && targetPick.pickedMesh) {
        const coords = targetPick.pickedMesh.name.split('_').slice(1).join(',');
        return { mesh: targetPick.pickedMesh, index: coords };
    }
    return null;
}

/**
 * Check if player is near exit door
 * @param {{x: number, y: number, z: number}} playerPos
 * @param {BABYLON.Vector3} exitPos
 * @param {number} threshold
 * @returns {boolean}
 */
export function checkExitProximity(playerPos, exitPos, threshold = 2) {
    const cellSize = 2; // Default cell size
    const dist = Math.hypot(playerPos.x - exitPos.x, playerPos.z - exitPos.z);
    return dist < cellSize * threshold;
}

/**
 * Highlight or unhighlight chest
 * @param {BABYLON.Mesh | null} mesh
 */
export function setChestHighlight(mesh) {
    // Reset previous highlight
    const allChests = document.querySelectorAll('[data-chest-highlighted="true"]');
    allChests.forEach(el => {
        const prev = window.mazeGameApi?.getMeshByName?.(el.getAttribute('data-mesh-name'));
        if (prev) {
            prev.renderOutline = false;
        }
    });

    if (!mesh) return;

    // Apply new highlight
    mesh.outlineColor = new BABYLON.Color3(0.85, 0.85, 0.85);
    mesh.outlineWidth = 0.08;
    mesh.renderOutline = true;
}
