import { system, TicksPerSecond } from "@minecraft/server";

// Fill these array's with sound string ids
const soundPools ={ 
    blank: ["mythicus_tw:blank"],
    uneasy: ["mythicus_tw:whisper_uneasy"],
    scared: ["mythicus_tw:whisper_scared"],
    terrified: ["mythicus_tw:whisper_terrified"]
}

function getSoundSettings(fearLevel) {
    //Tweak these numbers (20,60) for when you want certain pools to activate
    if (fearLevel <= 25) {
        return { pool: undefined, minDelay: 25, maxDelay: 50 }; //Tweak your delays between sounds, these are in seconds
    }
    else if (fearLevel <= 50) {
        return { pool: soundPools.uneasy, minDelay: 30, maxDelay: 60 }; //Tweak your delays between sounds, these are in seconds
    } else if (fearLevel <= 90) {
        return { pool: soundPools.scared, minDelay: 20, maxDelay: 40 };
    } else {
        return { pool: soundPools.terrified, minDelay: 8, maxDelay: 25 };
    }
}

// This runs when a player first joins the world and repeats on the desired delay for that soundpool
export function scheduleAmbient(player, fearLevel) {
    const { pool, minDelay, maxDelay } = getSoundSettings(fearLevel);

    if (pool && Math.random() < (0.15 + 0.003 * fearLevel)) {
        const sound = pool[Math.floor(Math.random() * pool.length)];
        const randomLocation = chooseRandomLocation(player, 4);
        player.playSound(sound, randomLocation);
    }

    const fearCheck = player.getDynamicProperty("mythicus_tw:fear.amount") ?? 0;
    const delay = Math.floor(
        minDelay + Math.random() * (maxDelay - minDelay)
    ) * TicksPerSecond;

    system.runTimeout(() => scheduleAmbient(player, fearCheck), delay);
}

// Function to choose a random location around the player
function chooseRandomLocation(player, radius) { 
    const angle = Math.random() * Math.PI * 2;
    const offsetX = Math.cos(angle) * radius;
    const offsetZ = Math.sin(angle) * radius;

    const pos = player.getHeadLocation();
    return {
        x: pos.x + offsetX,
        y: pos.y,
        z: pos.z + offsetZ
    };
}
