/* ============================================================
   DAVID — IRONMAN DRUID BIOME + AUDIO ENGINE
   ============================================================ */

window.addEventListener("heroLoaded", () => {
    startDavidAudio();
});

/* ============================================================
   AUDIO ENGINE
   ============================================================ */

let davidLoops = [];
let davidSFX = [];
let davidSFXTimeout = null;

function startDavidAudio() {
    stopDavidAudio();

    const audioPath = "character-files/audio/";

    const files = [
        "david-bark.wav",
        "david-birds.wav",
        "david-branch.wav",
        "david-crickets.wav",
        "david-forest-loop.mp3",
        "david-growl.wav",
        "david-nature-loop.wav",
        "david-owl.wav",
        "david-scary-wolf.wav",
        "david-swipecard-gone.mp3",
        "david-werewolf-howl.mp3",
        "david-wind-loop.wav",
        "david-wolf-attack.mp3",
        "david-wolf-howl.wav"
    ];

    files.forEach(f => {
        const audio = new Audio(audioPath + f);

        if (f.includes("loop")) {
            audio.loop = true;
            audio.volume = 0.25;
            davidLoops.push(audio);
        } else {
            audio.loop = false;
            audio.volume = 0.35;
            davidSFX.push(audio);
        }
    });

    davidLoops.forEach(a => a.play());
    scheduleNextDavidSFX();
}

function scheduleNextDavidSFX() {
    const delay = Math.random() * 20000; // 0–20 sec

    davidSFXTimeout = setTimeout(() => {
        playRandomDavidSFX();
        scheduleNextDavidSFX();
    }, delay);
}

function playRandomDavidSFX() {
    if (davidSFX.length === 0) return;

    const audio = davidSFX[Math.floor(Math.random() * davidSFX.length)];
    audio.currentTime = 0;
    audio.play();
}

function stopDavidAudio() {
    davidLoops.forEach(a => {
        a.pause();
        a.currentTime = 0;
    });
    davidLoops = [];

    if (davidSFXTimeout) clearTimeout(davidSFXTimeout);
    davidSFXTimeout = null;
}