const soundFiles = {
    chestClose: "/sfx/sfx_chest_close.wav",
    chestOpen: "/sfx/sfx_chest_open.wav",
    click: "/sfx/sfx_click.wav",
    clock: "/sfx/sfx_clock.wav",
    key: "/sfx/sfx_key.wav",
    lose: "/sfx/sfx_lose.wav",
    step: "/sfx/sfx_step.wav",
    win: "/sfx/sfx_win.wav",
};

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);
}