// Import audio files as modules so Vite bundles them
import chestCloseUrl from "../../sfx/sfx_chest_close.wav";
import chestOpenUrl from "../../sfx/sfx_chest_open.wav";
import clickUrl from "../../sfx/sfx_click.wav";
import clockUrl from "../../sfx/sfx_clock.wav";
import keyUrl from "../../sfx/sfx_key.wav";
import loseUrl from "../../sfx/sfx_lose.wav";
import stepUrl from "../../sfx/sfx_step.wav";
import winUrl from "../../sfx/sfx_win.wav";

const soundFiles = {
    chestClose: chestCloseUrl,
    chestOpen: chestOpenUrl,
    click: clickUrl,
    clock: clockUrl,
    key: keyUrl,
    lose: loseUrl,
    step: stepUrl,
    win: winUrl,
};

const sounds = {};
for (const [name, filePath] of Object.entries(soundFiles)) {
    const audio = new Audio(filePath);
    audio.preload = "auto";
    sounds[name] = audio;
}

let audioPrimed = false;

function playAudio(audio, volume = 1) {
    const instance = audio.cloneNode();
    instance.volume = volume;
    instance.currentTime = 0;
    const promise = instance.play();
    if (promise && typeof promise.catch === "function") {
        promise.catch(() => {});
    }
}

export function primeSfx() {
    if (audioPrimed) {
        return;
    }

    audioPrimed = true;
    for (const audio of Object.values(sounds)) {
        const probe = audio.cloneNode();
        probe.volume = 0;
        const promise = probe.play();
        if (promise && typeof promise.then === "function") {
            promise
                .then(() => {
                    probe.pause();
                    probe.currentTime = 0;
                })
                .catch(() => {});
        }
    }
}

export function playSfx(name, volume = 1) {
    const audio = sounds[name];
    if (!audio) {
        return;
    }

    playAudio(audio, volume);
}