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


export function initCreepers() {

    
    const chance = 1 / 36; 
    const forebodingCheck = fo.scoreChapter3; 
    const checkInterval = 6017; 

    let CreeperFlag = false 

    
    function getDistance(pos1, pos2) {
        return Math.sqrt(
            Math.pow(pos1.x - pos2.x, 2) +
            Math.pow(pos1.y - pos2.y, 2) +
            Math.pow(pos1.z - pos2.z, 2)
        );
    }

    function maybeTriggerCreeperExplosion() {

        
        if (fo.forebodingScore >= forebodingCheck && Math.random() < (chance * fo.netProbabilityModifier) && CreeperFlag != true) { 
            CreeperFlag = true
            
        }

        if (CreeperFlag) {
            const players = fo.overworld.getPlayers();
            if (players.length === 0) return;

            
            const selectedPlayer = players[Math.floor(Math.random() * players.length)];

            
            const creepers = fo.overworld.getEntities({
                type: "minecraft:creeper",
                location: selectedPlayer.location,
                maxDistance: 64,
                minDistance: 32,
            });

            
            const validCreepers = creepers.filter(creeper => {
                
                for (const player of players) {
                    if (getDistance(player.location, creeper.location) < 32) {
                        return false; 
                    }
                }
                return true; 
            });

            if (validCreepers.length > 0) {
                const randomCreeper = validCreepers[Math.floor(Math.random() * validCreepers.length)];
                randomCreeper.triggerEvent("minecraft:start_exploding_forced");
                
                CreeperFlag = false
                return; 

            }
        }
    }

    
    system.runInterval(maybeTriggerCreeperExplosion, checkInterval);

}