import { system, world } from "@minecraft/server";
import { fo } from './utilities/fo_constants.js';


export function initNightScream() {

    const CHECK_INTERVAL = 6000; 
    const RUN_INTERVAL = 40; 
    const CHANCE = 1 / 24; 
    const forebodingCheck = fo.scoreChapter4; 
    const TARGET_TIME_START = 13000;
    const TARGET_TIME_END = TARGET_TIME_START + RUN_INTERVAL;
    const SOUND = "fo_mob.ghast.scream";
    const SOUND_VOLUME = 10;
    const SOUND_PITCH = 0.3;
    const SOUND_MIN_DISTANCE = 120;

    const overworld = fo.overworld;

    
    let isIntervalActive = false;
    let intervalId = null;

    function getRandomPlayer() {
        const players = Array.from(overworld.getPlayers());
        return players.length > 0 ? players[Math.floor(Math.random() * players.length)] : null;
    }

    function playSoundFarFromPlayers() {
        const player = getRandomPlayer();
        if (!player) return;

        const playerDimension = player.dimension;

        let validLocation = null;
        let attempts = 20;

        while (attempts-- > 0 && !validLocation) {
            const angle = Math.random() * Math.PI * 2;
            const distance = SOUND_MIN_DISTANCE; 
            const dx = Math.cos(angle) * distance;
            const dz = Math.sin(angle) * distance;

            const x = player.location.x + dx;
            const z = player.location.z + dz;
            const y = 65;

            let safe = true;
            for (const otherPlayer of overworld.getPlayers()) {
                if (Math.hypot(x - otherPlayer.location.x, z - otherPlayer.location.z) < SOUND_MIN_DISTANCE) {
                    safe = false;
                    break;
                }
            }

            if (safe) {
                validLocation = { x, y, z };
                break;
            }
        }

        if (validLocation) {
            playerDimension.playSound(SOUND, validLocation, { volume: SOUND_VOLUME, pitch: SOUND_PITCH });
            
        } else {
            
        }
    }

    system.runInterval(() => {

        if (Math.random() < (CHANCE * fo.netProbabilityModifier) && fo.forebodingScore >= forebodingCheck && !isIntervalActive) {
            
            isIntervalActive = true; 

            intervalId = system.runInterval(() => {
                const currentTime = world.getTimeOfDay();
                
                if (currentTime >= TARGET_TIME_START && currentTime < TARGET_TIME_END) {
                    playSoundFarFromPlayers();
                    system.clearRun(intervalId); 
                    isIntervalActive = false; 
                }
            }, RUN_INTERVAL);
        }
    }, CHECK_INTERVAL);

}
