const cameraCtx = {
    smoothedDir: [0, -1]
};

function updateCamera() {
    if (!sceneCtx.camera) return;
    const player = getPlayerPos();
    const dir = getPathDirection(player.x, player.z, cameraCtx.smoothedDir);

    cameraCtx.smoothedDir[0] += (dir[0] - cameraCtx.smoothedDir[0]) * 0.06;
    cameraCtx.smoothedDir[1] += (dir[1] - cameraCtx.smoothedDir[1]) * 0.06;
    const len = Math.sqrt(cameraCtx.smoothedDir[0] * cameraCtx.smoothedDir[0] + cameraCtx.smoothedDir[1] * cameraCtx.smoothedDir[1]) || 1;
    const sx = cameraCtx.smoothedDir[0] / len;
    const sz = cameraCtx.smoothedDir[1] / len;

    const targetX = player.x - sx * CAMERA_OFFSET_Z;
    const targetY = player.y + CAMERA_OFFSET_Y;
    const targetZ = player.z - sz * CAMERA_OFFSET_Z;

    sceneCtx.camera.position.x += (targetX - sceneCtx.camera.position.x) * CAMERA_LERP;
    sceneCtx.camera.position.y += (targetY - sceneCtx.camera.position.y) * CAMERA_LERP;
    sceneCtx.camera.position.z += (targetZ - sceneCtx.camera.position.z) * CAMERA_LERP;

    const lookX = player.x + sx * CAMERA_LOOK_AHEAD;
    const lookZ = player.z + sz * CAMERA_LOOK_AHEAD;
    sceneCtx.camera.lookAt(lookX, player.y + 0.5, lookZ);
}

function snapCameraToPlayer() {
    if (!sceneCtx.camera) return;
    const player = getPlayerPos();
    const dir = getPathDirection(player.x, player.z);
    cameraCtx.smoothedDir[0] = dir[0];
    cameraCtx.smoothedDir[1] = dir[1];

    sceneCtx.camera.position.set(
        player.x - dir[0] * CAMERA_OFFSET_Z,
        player.y + CAMERA_OFFSET_Y,
        player.z - dir[1] * CAMERA_OFFSET_Z
    );
    sceneCtx.camera.lookAt(
        player.x + dir[0] * CAMERA_LOOK_AHEAD,
        player.y + 0.5,
        player.z + dir[1] * CAMERA_LOOK_AHEAD
    );
}
