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



export function initMoon() {

    
    const chance = 1 / 60; 
    const forebodingCheck = 0; 
    const interval = 3601; 

    let eventFlag = false; 

    function getRandomPlayer() {
        const overworld = fo.overworld;
        const players = Array.from(overworld.getPlayers());

        
        const eligiblePlayers = players.filter(player => player.clientSystemInfo?.maxRenderDistance >= 36);

        
        return eligiblePlayers.length > 0 ? eligiblePlayers[Math.floor(Math.random() * eligiblePlayers.length)] : null;
    }

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

        
        const playerLocation = player.location;

        
        const particleLocation = {
            x: playerLocation.x,
            y: 0, 
            z: playerLocation.z
        };


        fo.overworld.spawnParticle("fo_moon", particleLocation);

        eventFlag = false; 

    }


    
    system.runInterval(() => {

        if (eventFlag) return;
        const probabilityModifier = Math.min(fo.netProbabilityModifier, 3);

        if (fo.forebodingScore === forebodingCheck && Math.random() < (chance * probabilityModifier)) {

            eventFlag = true;
            
        }


    }, interval);

    
    system.runInterval(() => {

        if (!eventFlag) return;

        let dayTime = world.getTimeOfDay();

        if (dayTime >= 14000 && dayTime <= 15199) {

            FakeMoon();
            
        }


    }, 1200); 

}