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







































export function initMixedEvents() {

    
    const

        endermenHitChance = 1 / 90, 
        thunderstormChance = 1 / 60, 
        droppedItemsChance = 1 / 180, 
        camerashakeChance = 1 / 180, 
        endermiteChance = 1 / 270, 
        calm4Chance = 1 / 540, 
        knockbackChance = 1 / 90, 
        activeArmorChance = 1 / 180, 
        arrowShotChance = 1 / 135, 
        movingArmorChance = 0.05, 
        screenGoesBlackChance = 1 / 90, 
        thunderHitChance = 1 / 270, 
        torchesDissapear = 1 / 270, 
        fireworkChance = 1 / 90, 
        raidAttemptChance = 1 / 135, 
        poisonChance = 1 / 5, 

        FOREBODINGCHECK1 = fo.scoreChapter3, 
        FOREBODINGCHECK2 = fo.scoreChapter4, 
        FOREBODINGCHECK3 = fo.scoreChapter5, 
        FOREBODINGCHECK7 = fo.scoreChapter7s, 
        INTERVAL1 = 799, 
        INTERVAL2 = 1603, 

        overworld = fo.overworld,
        nether = fo.nether,
        theEnd = fo.theEnd;

    let  
        eventActiveArmor = false,
        eventArrowShot = false,
        eventAttemptedRaid = false,
        eventCalm4 = false,
        eventCage = false,
        eventPlayerTp = false;


    
    function isPlayerUnderground(player) {
        const startY = Math.floor(player.location.y);
        const maxY = Math.min(startY + 120, player.dimension.heightRange.max - 1);

        const blockAbove = player.dimension.getBlockAbove(player.location, {
            maxDistance: maxY - startY
        });

        return !!blockAbove;
    }

    
    function attemptRaid(overworldPlayers) {

        const players = overworldPlayers;

        
        const playersNearVillagers = players.filter(player => {
            const villagersNearby = overworld.getEntities({
                type: "minecraft:villager",
                location: player.location,
                maxDistance: 62
            });
            return villagersNearby.length > 0; 
        });

        
        if (playersNearVillagers.length === 0) return;

        
        const player = playersNearVillagers[Math.floor(Math.random() * playersNearVillagers.length)];

        player.addEffect("raid_omen", 1, { showParticles: false })

        

    }

    
    function getPositionAround(center, radius) {
        const angle = Math.random() * Math.PI * 2;
        const distance = radius;
        return {
            x: center.x + Math.cos(angle) * distance,
            y: center.y,
            z: center.z + Math.sin(angle) * distance,
        };
    }

    
    function getPositionAroundMinMax(center, minDistance, maxDistance, dimension) {
        const angle = Math.random() * Math.PI * 2;
        const distanceXZ = minDistance + Math.random() * (maxDistance - minDistance);
        const distanceY = (Math.random() - 0.5) * (maxDistance - minDistance); 

        return {
            x: center.x + Math.cos(angle) * distanceXZ,
            y: Math.max(Math.min(center.y + distanceY, dimension.heightRange.max), dimension.heightRange.min), 
            z: center.z + Math.sin(angle) * distanceXZ,
        };
    }

    
    function lightingStrike(thunderPos) {

        try {

            const thunderblock = overworld.getTopmostBlock(thunderPos, 260)

            overworld.spawnEntity("minecraft:lightning_bolt", thunderblock.above(1).location);




        } catch (error) {
            
        }

    };

    
    
    function countPlayerGroups(players) {

        if (players.length === 0) return 0;

        const
            groups = [],
            processed = new Set();

        for (const player of players) {
            if (processed.has(player.id)) continue;

            
            const currentGroup = [player];
            processed.add(player.id);

            
            let checkIndex = 0;
            while (checkIndex < currentGroup.length) {
                const checkPlayer = currentGroup[checkIndex];

                for (const otherPlayer of players) {
                    if (!processed.has(otherPlayer.id)) {
                        const distance = Math.sqrt(
                            Math.pow(checkPlayer.location.x - otherPlayer.location.x, 2) +
                            Math.pow(checkPlayer.location.z - otherPlayer.location.z, 2)
                        );

                        if (distance <= 100) {
                            currentGroup.push(otherPlayer);
                            processed.add(otherPlayer.id);
                        }
                    }
                }
                checkIndex++;
            }

            groups.push(currentGroup);
        }

        return groups.length;

    }

    
    function spawnMoonInFront(player, players) {
        const
            rotation = player.getRotation(),
            yaw = rotation.y * (Math.PI / 180),
            playerPos = player.location,
            PARTICLE_DISTANCE = 25;

        
        const moonPos = {
            x: playerPos.x + Math.sin(yaw) * PARTICLE_DISTANCE,
            y: playerPos.y,
            z: playerPos.z + Math.cos(yaw) * PARTICLE_DISTANCE
        };

        
        for (const visitor of players) {
            if (visitor.id === player.id) continue; 

            const dist = Math.sqrt(
                Math.pow(visitor.location.x - moonPos.x, 2) +
                Math.pow(visitor.location.z - moonPos.z, 2)
            );

            if (dist < SAFE_RADIUS) {
                
                return false;
            }
        }

        const topmostBlock = overworld.getTopmostBlock({ x: moonPos.x, z: moonPos.z });

        
        overworld.runCommand(
            `particle ${"fo_moon2"} ${moonPos.x} ${Math.max(topmostBlock.y + 1, 63)} ${moonPos.z}`
        );
        

        return true;
    }

    function StartBlockBreaking(player) {
        const px = Math.floor(player.location.x);
        const pz = Math.floor(player.location.z);
        const playerFeetY = Math.floor(player.location.y);

        let airBlockY = null;
        const scannedBlocks = [];

        
        for (let y = playerFeetY - 1; y >= playerFeetY - 24; y--) {
            const block = overworld.getBlock({ x: px, y, z: pz });
            if (!block) break;

            scannedBlocks.push(block);

            if (block.isAir) {
                airBlockY = y;
                break;
            }
        }

        if (airBlockY === null) return;
        if (playerFeetY <= airBlockY + 1) return;

        

        
        const validBlocks = new Set(fo.validMinedBlocks);

        for (let i = 0; i < scannedBlocks.length - 1; i++) {
            const block = scannedBlocks[i];

            if (block.isAir) continue; 
            if (!validBlocks.has(block.typeId)) return;
        }

        
        eventCage = true;


        

        const
            BREAKINGSOUNDINTERVAL = 6, 
            BREAKINTERVAL = BREAKINGSOUNDINTERVAL * 4,
            validBlocksMap = new Map(
                fo.ValidMinedBlocksArray.map(b => [b.id, b])
            );

        const startDimension = player.dimension.id;
        const startX = Math.floor(player.location.x);
        const startY = Math.floor(player.location.y);
        const startZ = Math.floor(player.location.z);


        for (let i = playerFeetY - (airBlockY + 1); i >= 0; i--) {
            system.runTimeout(() => {
                


                if (playerInvalidated()) {
                    
                    return;
                }

                
                const block = overworld.getBlock({
                    x: px,
                    y: airBlockY + 1 + i,
                    z: pz
                });

                if (!block) {
                    
                    return;
                }

                

                const data = validBlocksMap.get(block.typeId);
                if (!data) {
                    
                    return;
                }

                const breakingSoundInterval = system.runInterval(() => {
                    if (playerInvalidated()) {
                        
                        system.clearRun(breakingSoundInterval);
                        return;
                    }

                    overworld.playSound(data.beingBrokenSound, block.location, { volume: 2 });
                }, BREAKINGSOUNDINTERVAL);

                system.runTimeout(() => {
                    if (playerInvalidated()) {
                        system.clearRun(breakingSoundInterval);
                        return;
                    }
                    

                    overworld.runCommand(`setblock ${block.location.x} ${block.location.y} ${block.location.z} air destroy`);
                    system.clearRun(breakingSoundInterval);

                }, BREAKINTERVAL);

            }, i * BREAKINTERVAL + 2);


        }

        function playerInvalidated() {
            if (!player.isValid) return true;
            if (player.dimension.id !== startDimension) return true;
            if (playerMoved()) return true;
            return false;
        }

        function playerMoved() {
            if (!player.isValid) return true;

            const x = Math.floor(player.location.x);
            const y = Math.floor(player.location.y);
            const z = Math.floor(player.location.z);

            return (
                x !== startX ||
                z !== startZ ||
                Math.abs(y - startY) > 0
            );
        }



    };


    
    system.runInterval(() => {
        const
            forebodingScore = fo.forebodingScore,
            probabilityModifier = fo.netProbabilityModifier,
            LastChIntensityMod = fo.forebodingScore > fo.scoreChapter5 ? 1.25 : 0,

            worldPlayers = world.getAllPlayers();

        
        if (forebodingScore >= 0 && worldPlayers.length > 0) Chapter01(probabilityModifier, worldPlayers);

        if (worldPlayers.length === 0 || forebodingScore === 0 || forebodingScore === -1) return; 

        const
            overworldPlayers = overworld.getPlayers(),
            netherPlayers = nether.getPlayers();

        
        if (forebodingScore >= FOREBODINGCHECK1) Chapter03(forebodingScore, probabilityModifier, LastChIntensityMod, worldPlayers, overworldPlayers, netherPlayers);

        
        if (forebodingScore >= FOREBODINGCHECK2) Chapter04(forebodingScore, probabilityModifier, LastChIntensityMod, worldPlayers, overworldPlayers, netherPlayers);


        
        if (forebodingScore >= FOREBODINGCHECK3) Chapter05(forebodingScore, probabilityModifier, worldPlayers, overworldPlayers, netherPlayers);

        
        if (forebodingScore <= FOREBODINGCHECK7) Chapter07(forebodingScore, probabilityModifier, worldPlayers, overworldPlayers, netherPlayers);

    }, INTERVAL1);


    
    function Chapter01(probabilityModifier, worldPlayers) {
        

        
        if (Math.random() <= endermenHitChance) {
            
            for (const player of worldPlayers) {
                const endermen = player.dimension.getEntities({
                    location: player.location,
                    maxDistance: 48,
                    type: "minecraft:enderman"
                });
                for (const enderman of endermen) {
                    enderman.applyDamage(0.01, {
                        cause: "entityAttack",
                        damagingEntity: player,
                    })
                }
            }

        };

    };

    
    function Chapter03(forebodingScore, probabilityModifier, LastChIntensityMod, worldPlayers, overworldPlayers, netherPlayers) {
        
        if (forebodingScore < (FOREBODINGCHECK1 + INTERVAL1)) {
            world.playMusic("forefeelM", { fade: 10, volume: 0.01, loop: true });
        };

        
        

        
        if (Math.random() <= thunderstormChance * (1 + LastChIntensityMod)) {

            overworld.setWeather("Thunder", 1200); 
            
        }

        
        if (Math.random() <= droppedItemsChance * (probabilityModifier + LastChIntensityMod)) {

            overworld.runCommand(`execute at @s run loot spawn ^ ^ ^45 loot foreboding_blocks`)

            
        }

        
        if (Math.random() <= (camerashakeChance * (probabilityModifier + LastChIntensityMod))) {

            const player = worldPlayers[Math.floor(Math.random() * worldPlayers.length)]; 

            player.runCommand(`camerashake add @r 1 0.3 rotational`)

            
        }

        
        if (Math.random() <= (endermiteChance * probabilityModifier)) {

            const player = worldPlayers[Math.floor(Math.random() * worldPlayers.length)]; 

            player.runCommand(`execute at @r run summon endermite ^ ^ ^-5 facing @p`) 

            
        };

        
        if (Math.random() <= calm4Chance) {
            system.runTimeout(() => {
                const players = [...overworldPlayers].filter(player => player.location.y < 20); 

                if (players.length === 0) return;

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

                if (!isPlayerUnderground(player)) return;

                player.playSound("calm4"); 

                
            }, 5)
        };

        
        if (Math.random() <= (knockbackChance * probabilityModifier)) {
            const player = worldPlayers[Math.floor(Math.random() * worldPlayers.length)]; 

            const distance = 0.6; 
            const knockbackPos = {
                x: (Math.random() * distance - (distance / 2)),
                z: (Math.random() * distance - (distance / 2)),
            };

            
            player.applyKnockback({ x: knockbackPos.x, z: knockbackPos.z }, 0);

            
        }

        
        if (Math.random() <= (activeArmorChance * (probabilityModifier + LastChIntensityMod)) || eventActiveArmor) {
            eventActiveArmor = true;
            const player = worldPlayers[Math.floor(Math.random() * worldPlayers.length)]; 

            const armorStands = player.dimension.getEntities({
                type: "armor_stand",
                location: player.location,
                minDistance: 36,
            })

            if (armorStands.length !== 0) {
                const armorStand = armorStands[Math.floor(Math.random() * armorStands.length)]; 
                const
                    animations = [
                        "animation.armor_stand.athena_pose",
                        "animation.armor_stand.brandish_pose",
                        "animation.armor_stand.cancan_a_pose",
                        "animation.armor_stand.cancan_b_pose",
                        "animation.armor_stand.default_pose",
                        "animation.armor_stand.entertain_pose",
                        "animation.armor_stand.hero_pose",
                        "animation.armor_stand.honor_pose",
                        "animation.armor_stand.no_pose",
                        "animation.armor_stand.riposte_pose",
                        "animation.armor_stand.salute_pose",
                        "animation.armor_stand.solemn_pose",
                        "animation.armor_stand.wiggle",
                        "animation.armor_stand.zombie_pose"
                    ],
                    animation = animations[Math.floor(Math.random() * animations.length)]; 

                armorStand.playAnimation(animation, {
                    nextState: animation,
                });

                if (Math.random() <= movingArmorChance) {
                    system.runTimeout(() => {
                        armorStand.runCommand(`spreadplayers ~ ~ 1 6 @s ~3`);
                    }, 1)
                }

                eventActiveArmor = false;
            }


        };

        
        if (Math.random() <= (arrowShotChance * (probabilityModifier + LastChIntensityMod)) || eventArrowShot) {
            eventArrowShot = true;
            const
                player = worldPlayers[Math.floor(Math.random() * worldPlayers.length)], 
                dim = player.dimension,
                maxAttempts = 10,

                target = player.location;

            for (let i = 0; i < maxAttempts; i++) {
                const
                    theta = Math.random() * 2 * Math.PI,      
                    phi = Math.acos(2 * Math.random() - 1),   
                    x = Math.sin(phi) * Math.cos(theta),
                    y = Math.max(Math.cos(phi), 0),
                    z = Math.sin(phi) * Math.sin(theta),

                    distance = 32,
                    origin = {
                        x: target.x + x * distance,
                        y: target.y + y * distance,
                        z: target.z + z * distance
                    },

                    nearTarget = {
                        x: target.x + (Math.random() * 6) - 3,
                        y: target.y + (Math.random() * 2) + 2,
                        z: target.z + (Math.random() * 6) - 3
                    },

                    dir = {
                        x: nearTarget.x - origin.x,
                        y: nearTarget.y - origin.y,
                        z: nearTarget.z - origin.z
                    };

                const
                    blockBetween = dim.getBlockFromRay(origin, dir, {
                        includeLiquidBlocks: false,
                        includePassableBlocks: false,
                        maxDistance: distance,
                    }),
                    hasLOS = !blockBetween || blockBetween.isAir;
                if (!hasLOS) continue;

                
                const
                    arrow = dim.spawnEntity("minecraft:arrow", origin),
                    mag = Math.sqrt(dir.x ** 2 + dir.y ** 2 + dir.z ** 2),
                    speed = 8.0; 

                arrow.applyImpulse({
                    x: (dir.x / mag) * speed,
                    y: (dir.y / mag) * speed,
                    z: (dir.z / mag) * speed
                });
                eventArrowShot = false;
                
                break;
            }
        };

        
        if (Math.random() <= (fireworkChance * (probabilityModifier + LastChIntensityMod))) {

            const
                player = worldPlayers[Math.floor(Math.random() * worldPlayers.length)], 
                dimension = player.dimension,
                aroundPos = getPositionAroundMinMax(player.location, 8, 16, dimension),
                block = dimension.getBlock(aroundPos);
            if (!block) return;
            const
                launchPos = block.location,
                splashPotionPos = {
                    x: launchPos.x,
                    y: launchPos.y + 3,
                    z: launchPos.z,
                },

                
                splashPotion = dimension.spawnEntity("minecraft:splash_potion", splashPotionPos);
        };


    };

    
    function Chapter04(forebodingScore, probabilityModifier, LastChIntensityMod, worldPlayers, overworldPlayers, netherPlayers) {
        
        if (Math.random() <= (screenGoesBlackChance * Math.min(probabilityModifier, 1.5))) {

            const player = worldPlayers[Math.floor(Math.random() * worldPlayers.length)]; 

            player.runCommand(`camera @r fade time 0 0.01 0`)

            
        }

        
        if (Math.random() <= (thunderHitChance * (probabilityModifier + LastChIntensityMod))) {
            system.runTimeout(() => {
                const players = [...overworldPlayers].filter(player => player.location.y > 40); 

                if (players.length === 0) return;

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

                if (isPlayerUnderground(player)) return;

                
                const viewDirection = player.getViewDirection();

                
                const distance = 2 + Math.random() * 3; 
                const thunderPos = {
                    x: player.location.x + viewDirection.x * distance,
                    y: player.location.y + viewDirection.y * distance,
                    z: player.location.z + viewDirection.z * distance,
                };
                const thunderblock = overworld.getTopmostBlock(thunderPos, 260)
                const thunderblockAbove = {
                    x: thunderblock.x,
                    y: thunderblock.y + 1,
                    z: thunderblock.z,
                };

                overworld.spawnEntity("minecraft:lightning_bolt", thunderblockAbove);

                
            }, 2)
        }

        
        if (Math.random() <= (torchesDissapear * Math.min((probabilityModifier + LastChIntensityMod), 2))) {
            system.runTimeout(() => {
                const players = [...overworldPlayers].filter(player => player.location.y < 20); 

                if (players.length === 0) return;

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

                if (!isPlayerUnderground(player)) return;

                const dim = player.dimension;
                const base = player.location;

                const offsets = [];
                for (let x = -32; x < 32; x += 16) {
                    for (let y = -32; y < 32; y += 16) {
                        for (let z = -32; z < 32; z += 16) {
                            offsets.push({
                                from: [x, y, z],
                                to: [
                                    Math.min(x + 15, 32),
                                    Math.min(y + 15, 32),
                                    Math.min(z + 15, 32)
                                ]
                            });
                        }
                    }
                };

                const { min: minDY, max: maxDY } = dim.heightRange; 

                offsets.forEach((offset, i) => {
                    system.runTimeout(() => {
                        try {
                            const fromY = Math.floor(base.y + offset.from[1]);
                            const toY = Math.floor(base.y + offset.to[1]);

                            
                            if (toY < minDY || fromY > maxDY) return;

                            const from = {
                                x: Math.floor(base.x + offset.from[0]),
                                y: Math.max(minDY, fromY),
                                z: Math.floor(base.z + offset.from[2])
                            };

                            const to = {
                                x: Math.floor(base.x + offset.to[0]),
                                y: Math.min(maxDY, toY),
                                z: Math.floor(base.z + offset.to[2])
                            };

                            
                            const center = {
                                x: (from.x + to.x) / 2,
                                y: (from.y + to.y) / 2,
                                z: (from.z + to.z) / 2
                            };

                            
                            const volume = new BlockVolume(from, to);
                            dim.fillBlocks(volume, "minecraft:light_block_0", {
                                blockFilter: { includeTypes: ["minecraft:torch"] },
                                ignoreChunkBoundErrors: true
                            });
                        } catch (e) { console.warn(`error:${e} at vanishing torches`) };
                    }, i); 
                });

            }, 2)
        };

        
        if (Math.random() <= (fireworkChance * probabilityModifier)) {
            const players = [...overworldPlayers].filter(player => player.location.y > 59); 
            if (players.length === 0) return;

            const
                player = players[Math.floor(Math.random() * players.length)], 
                aroundPos = getPositionAround(player.location, 36),
                
                topBlock = overworld.getTopmostBlock(aroundPos, 90);
            if (!topBlock) return;
            const
                launchPos = topBlock.location,
                fireworkPos = {
                    x: launchPos.x + 0.5,
                    y: launchPos.y + 1,
                    z: launchPos.z + 0.5,
                },

                
                firework = overworld.spawnEntity("minecraft:fireworks_rocket", fireworkPos);
        };

        
        if (overworldPlayers.length > 0 && !eventCage) {
            for (const player of overworldPlayers) {
                const health = player.getComponent("health");
                if (!health) continue;
                if (health > 8 || player.location.y > 40 || player.location.y < overworld.heightRange.min + 25) continue;

                
                const
                    px = player.location.x,
                    py = player.location.y,
                    pz = player.location.z,

                    standingBlock = overworld.getBlock({
                        x: px,
                        y: py - 1,
                        z: pz
                    }),

                    directions = [
                        { x: 1, z: 0 },
                        { x: -1, z: 0 },
                        { x: 0, z: 1 },
                        { x: 0, z: -1 },
                    ];

                if (standingBlock.isAir || standingBlock.isLiquid) continue;

                let unblockedCount = 0;

                for (const dir of directions) {
                    
                    const feetBlock = overworld.getBlock({
                        x: px + dir.x,
                        y: py,
                        z: pz + dir.z
                    });

                    
                    const faceBlock = overworld.getBlock({
                        x: px + dir.x,
                        y: py + 1,
                        z: pz + dir.z
                    });

                    if (feetBlock.isAir || faceBlock.isAir || feetBlock.isLiquid || faceBlock.isLiquid) {
                        unblockedCount++
                        break;
                    };

                }

                if (unblockedCount > 0) continue;
                

                StartBlockBreaking(player);

            }
        }

    };


    
    function Chapter05(forebodingScore, probabilityModifier, worldPlayers, overworldPlayers, netherPlayers) {
        
        if (!eventAttemptedRaid && forebodingScore < (FOREBODINGCHECK3 + INTERVAL1)) {

            eventAttemptedRaid = true; 
            attemptRaid(overworldPlayers);

        };

        
        if (Math.random() <= (raidAttemptChance)) {

            attemptRaid(overworldPlayers);

        };

        
        if (!eventCalm4 && forebodingScore >= FOREBODINGCHECK3 + (fo.durationChapter5 * 0.5) && forebodingScore < (FOREBODINGCHECK3 + (fo.durationChapter5 * 0.5) + INTERVAL1)) {

            eventCalm4 = true; 

            const players = worldPlayers;

            
            for (const player of players) {

                player.playSound("calm4")

            }

            

            if (overworldPlayers.length !== 0) {

                overworld.runCommand(`effect @e[type=!player] levitation 30 1 true`)
                overworld.runCommand(`effect @e[type=!player] slow_falling 60 1 true`)

            }

            if (netherPlayers.length !== 0) {

                nether.runCommand(`effect @e[type=!player] levitation 30 1 true`)
                nether.runCommand(`effect @e[type=!player] slow_falling 60 1 true`)

            }

        }

        
        if (!eventPlayerTp && forebodingScore >= 1367999 && forebodingScore < (1367999 + INTERVAL1)) {

            eventPlayerTp = true; 

            const players = overworldPlayers;

            
            for (const player of players) {

                player.playSound("forgotten_lullaby");

            }

            
            system.runTimeout(() => {

                overworld.runCommand(`camera @a[r=99999999] fade time 0 1 0`);
                world.gameRules.showCoordinates = false;

                for (const player of players) {

                    player.runCommand(`spreadplayers ~ ~ 56 112 @s`)
                    player.runCommand(`tp @s ~ ~1 ~`)

                }

            }, 200)

        };

        
        for (const player of worldPlayers) {
            const playerHealthComp = player.getComponent("health");
            const playerHungerComp = player.getComponent("minecraft:player.hunger");

            if (!playerHealthComp || !playerHungerComp) continue;

            const
                playerCurrentHealth = playerHealthComp.currentValue,
                playerCurrentHunger = playerHungerComp.currentValue,
                playerMaxHealth = playerHealthComp.effectiveMax;

            if (playerCurrentHealth < playerMaxHealth && playerCurrentHunger >= 18) {

                const
                    playerExhaustionComp = player.getComponent("minecraft:player.exhaustion"),
                    playerCurrentExhaustion = playerExhaustionComp.currentValue;

                playerHealthComp.setCurrentValue(Math.min(playerMaxHealth, playerCurrentHealth + 1));
                playerExhaustionComp.setCurrentValue(playerCurrentExhaustion + 6); 

            }

        }


    };

    function Chapter07(forebodingScore, probabilityModifier, worldPlayers, overworldPlayers, netherPlayers) {
        
        

        
        if (forebodingScore % 2 === 0) {
            for (const player of worldPlayers) {
                const playerHealthComp = player.getComponent("health");
                const playerHungerComp = player.getComponent("minecraft:player.hunger");

                if (!playerHealthComp || !playerHungerComp) continue;

                const
                    playerCurrentHealth = playerHealthComp.currentValue,
                    playerCurrentHunger = playerHungerComp.currentValue,
                    playerMaxHealth = playerHealthComp.effectiveMax;

                if (playerCurrentHealth < playerMaxHealth && playerCurrentHunger >= 18) {

                    const
                        playerExhaustionComp = player.getComponent("minecraft:player.exhaustion"),
                        playerCurrentExhaustion = playerExhaustionComp.currentValue;

                    playerHealthComp.setCurrentValue(Math.min(playerMaxHealth, playerCurrentHealth + 1));
                    playerExhaustionComp.setCurrentValue(playerCurrentExhaustion + 12); 

                }
            }
        }

        
        system.runTimeout(() => {
            const players = [...overworldPlayers].filter(player => player.location.y > 40); 

            if (players.length === 0) return;

            const playerMultiplayer = countPlayerGroups(players);

            const totalThunderHits = (10 + Math.floor(Math.random() * 8)) * playerMultiplayer; 

            let thunderDelay = 0;
            for (let i = 0; i < totalThunderHits; i++) {
                thunderDelay = thunderDelay + 40 + Math.floor(Math.random() * 60); 

                system.runTimeout(() => {

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

                    const thunderRadius = 11 + Math.floor(Math.random() * 45);
                    const thunderPos = getPositionAround(player.location, thunderRadius);

                    lightingStrike(thunderPos);


                }, thunderDelay / playerMultiplayer);
            }

        }, 3)

        
        system.runTimeout(() => {
            const players = [...overworldPlayers].filter(player => player.location.y <= 40); 

            if (players.length === 0) return;

            const playerMultiplayer = countPlayerGroups(players);

            const totalExplosions = (8 + Math.floor(Math.random() * 6)) * playerMultiplayer;

            const ExplosionOptions = {
                allowUnderwater: true,
                breaksBlocks: false,
                causesFire: true,
            };
            const explosionRadiusRange = 3; 

            let explosionsDelay = 0;
            for (let i = 0; i < totalExplosions; i++) {
                explosionsDelay = explosionsDelay + 60 + Math.floor(Math.random() * 80); 

                system.runTimeout(() => {

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

                    const explosionRadius = 11 + Math.floor(Math.random() * 45);

                    const ExplosionPos = getPositionAround(player.location, explosionRadius);

                    
                    const offsetY = (Math.random() * 60 - 30); 

                    
                    const explosionLocation = {
                        x: ExplosionPos.x,
                        y: Math.min(Math.max(ExplosionPos.y + offsetY, -60), 55),
                        z: ExplosionPos.z,
                    };

                    
                    overworld.createExplosion(explosionLocation, explosionRadiusRange, ExplosionOptions);
                    


                }, explosionsDelay / playerMultiplayer);
            }
        }, 7)

        
        system.runTimeout(() => {
            const timeOfDay = world.getTimeOfDay();

            if (timeOfDay >= 16670 && timeOfDay <= 22300) { 

                const players = [...overworldPlayers].filter(player => player.location.y > 40); 

                if (players.length === 0) return;

                const player = players[Math.floor(Math.random() * players.length)]; 
                spawnMoonInFront(player, players);

            }
        }, 11)

        
        if (Math.random() <= (poisonChance * probabilityModifier)) {
            system.runTimeout(() => {
                

                if (overworldPlayers.length === 0) return;

                const player = overworldPlayers[Math.floor(Math.random() * overworldPlayers.length)]; 

                
                const
                    cows = overworld.getEntities({ type: "minecraft:cow", location: player.location, maxDistance: 32, }),
                    chickens = overworld.getEntities({ type: "minecraft:chicken", location: player.location, maxDistance: 32, }),
                    rabbits = overworld.getEntities({ type: "minecraft:rabbit", location: player.location, maxDistance: 32, }),
                    sheep = overworld.getEntities({ type: "minecraft:sheep", location: player.location, maxDistance: 32, });

                
                const livestock = [...cows, ...chickens, ...rabbits, ...sheep];

                if (livestock.length === 0) return;

                const animal = livestock[Math.floor(Math.random() * livestock.length)]; 

                animal.addEffect("wither", 1200, {
                    amplifier: 0,
                });

                
            }, 3)
        };

        
        system.runTimeout(() => {

            if (overworldPlayers.length === 0) return;

            const cows = overworld.getEntities({ type: "minecraft:cow" });

            

            if (cows.length > 40) return;

            const
                playerMultiplayer = countPlayerGroups(overworldPlayers),
                totalCows = Math.max((1 + Math.floor(Math.random() * 3)) * playerMultiplayer, 15),
                cowRadius = 35 + Math.floor(Math.random() * 15);

            

            for (let i = 0; i < totalCows; i++) {
                let cowAttempt = 0,
                    validCowBlock = false;

                const player = overworldPlayers[Math.floor(Math.random() * overworldPlayers.length)]; 

                while (cowAttempt < 10 && !validCowBlock) {

                    const cowPos = getPositionAround(player.location, cowRadius);

                    
                    const offsetY = (Math.random() * 60 - 30); 

                    
                    const cowLocation = {
                        x: cowPos.x,
                        y: Math.min(Math.max(cowPos.y + offsetY, -60), 55),
                        z: cowPos.z,
                    };

                    const cowBlock = overworld.getBlock(cowLocation);

                    if (cowBlock && cowBlock.typeId === "minecraft:air") {

                        validCowBlock = true;
                        overworld.runCommand(`summon cow ${cowLocation.x} ${cowLocation.y} ${cowLocation.z}`);

                        


                    };

                    cowAttempt++
                }

            }

        }, 9)

    };

}
