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



export function initNoPause() {
    
    const
        forebodingScoreCheck3 = fo.scoreChapter3,
        forebodingScoreCheck4 = fo.scoreChapter4,
        forebodingScoreCheck5 = fo.scoreChapter5,
        forebodingScoreCheck7 = -fo.scoreChapter7s,
        maxMobSteps = 16, 
        maxEntitiesToMove = 20,
        lenienceTicks = 100, 
        chapt03Chance = 1 / 3, 
        Capt03MinElapsedTime = 72000, 
        P82Chance = 1 / 8, 
        P82MinElapsedTime = 216000, 


        FURNACE_LIST_PROPERTY = "furnace_locations";


    let eventChancesRare = 1 / 80; 
    let eventChancesUncommon = 1 / 40; 
    let stillnessEventFlag = fo.randomTick;

    
    system.runInterval(() => {

        eventChancesRare = (1 / 80) * fo.netProbabilityModifier

        stillnessEventFlag = fo.randomTick;

    }, 2949)


    const noGoBlocks = [
        "_wall",
        "_fence",
        "water",
        "lava",
        "fire",
        "sweet_berry_bush",
        "cactus",
        "magma",
        "bubble_column",
        "powder_snow",
        "cobweb",
        "short_grass",
        "tall_grass",
        "fern",
        "sapling",
        "torch",
        "vine",
        "ladder",
        "trapdoor",
        "door",
        "crop",
        "carrots",
        "potatoes",
        "beetroot",
        "wheat",
        "melon",
        "pumpkin",
        "stem",
        "cocoa",
        "bamboo",
        "sugar_cane",
        "nether_wart",
        "fungus",
        "_roots",
        "_sprouts",
        "_lichen",
        "mushroom",
        "flower",
        "carpet",
        "lever",
        "button"
    ];

    const flyingTypes = [
        "minecraft:allay",
        "minecraft:bee",
        "minecraft:parrot",
        "minecraft:phantom",
        "minecraft:vex",
        "minecraft:bat",
        "minecraft:ghast"
    ];

    const weatherOptions = [
        { condition: "Clear", weight: 7 },
        { condition: "Rain", weight: 3 },
        { condition: "Thunder", weight: 1 }
    ];

    const effectsDamage = [
        { effectId: "minecraft:poison", amplifier: 0, ticksPerDamage: 25 },
        { effectId: "minecraft:poison", amplifier: 1, ticksPerDamage: 12 },
        { effectId: "minecraft:poison", amplifier: 2, ticksPerDamage: 12 },
        { effectId: "minecraft:poison", amplifier: 3, ticksPerDamage: 10 },
        { effectId: "minecraft:wither", amplifier: 0, ticksPerDamage: 40 },
        { effectId: "minecraft:wither", amplifier: 1, ticksPerDamage: 20 },
        { effectId: "minecraft:wither", amplifier: 2, ticksPerDamage: 10 },
        { effectId: "minecraft:wither", amplifier: 3, ticksPerDamage: 10 },
    ];

    const hostilePool = [
        "minecraft:zombie",
        "minecraft:skeleton",
        "minecraft:creeper",
        "minecraft:spider"
    ];

    const projectilesA = [
        { id: "minecraft:arrow", despawnTimer: 2400 },
        { id: "minecraft:egg", despawnTimer: 100 },
        { id: "minecraft:evocation_fang", despawnTimer: 100 },
        { id: "minecraft:fishing_hook", despawnTimer: 100 },
        { id: "minecraft:fireworks_rocket", despawnTimer: 100 },
        { id: "minecraft:lightning_bolt", despawnTimer: 100 },
        { id: "minecraft:llama_spit", despawnTimer: 100 },
        { id: "minecraft:shulker_bullet", despawnTimer: 150 },
        { id: "minecraft:snowball", despawnTimer: 100 },
        { id: "minecraft:wind_charge_projectile", despawnTimer: 100 },
        { id: "minecraft:breeze_wind_charge_projectile", despawnTimer: 100 },
        { id: "minecraft:dragon_fireball", despawnTimer: 100 },

    ];

    const projectilesB = [
        { id: "minecraft:ender_pearl", effect: "teleport" }, 
        { id: "minecraft:large_fireball", effect: "explosion" }, 
        { id: "minecraft:small_fireball", effect: "fire" }, 
        { id: "minecraft:wither_skull", effect: "explosion" }, 
        { id: "minecraft:wither_skull_dangerous", effect: "explosion" }, 
    ];

    const projectileEffectHandlers = {
        "minecraft:ender_pearl": (pos, player) => {
            const dim = player.dimension;

            
            const offsets = [
                { x: 0, y: 1, z: 0 },  
                { x: 0, y: 0, z: -1 }, 
                { x: 1, y: 0, z: 0 },  
                { x: 0, y: 0, z: 1 },  
                { x: -1, y: 0, z: 0 }, 
                { x: 0, y: -1, z: 0 }  
            ];

            for (const offset of offsets) {
                const checkPos = {
                    x: pos.x + offset.x,
                    y: pos.y + offset.y,
                    z: pos.z + offset.z
                };

                const block = dim.getBlock(checkPos);

                
                if (block?.isAir) {
                    try {
                        player.teleport(checkPos);
                        system.runTimeout(() => {
                            player.applyDamage(5, { cause: "fall" });
                            player.dimension.playSound("mob.shulker.teleport", checkPos)
                        }, 1)
                        return;
                    } catch (e) {
                        console.log(`[Teleport Fail] Could not teleport player: ${e}`);
                        return;
                    };
                }
            }

            
            console.log(`[Teleport Fail] No valid air block found near ender pearl landing.`);
        },

        "minecraft:large_fireball": (pos, player) => {
            player.dimension.createExplosion(pos, 1, { causesFire: true });
        },

        "minecraft:small_fireball": (pos, player) => {
            const blockAbove = { x: pos.x, y: pos.y + 1, z: pos.z }
            const block = player.dimension.getBlockAbove(blockAbove);
            if (block?.isAir) {
                block.setType("minecraft:fire");
            }
        },

        "minecraft:wither_skull": (pos, player) => {
            player.dimension.createExplosion(pos, 1, { causesFire: false });
        },

        "minecraft:wither_skull_dangerous": (pos, player) => {
            player.dimension.createExplosion(pos, 1, { causesFire: false });
        },
    };

    const furnacesTable = [
        { id: "minecraft:furnace", slots: 3, speed: 200, fuelConsumption: 1, process: "all" },
        { id: "minecraft:lit_furnace", slots: 3, speed: 200, fuelConsumption: 1, process: "all" },
        { id: "minecraft:blast_furnace", slots: 3, speed: 100, fuelConsumption: 2, process: "ores" },
        { id: "minecraft:lit_blast_furnace", slots: 3, speed: 100, fuelConsumption: 2, process: "ores" },
        { id: "minecraft:smoker", slots: 3, speed: 100, fuelConsumption: 2, process: "food" },
        { id: "minecraft:lit_smoker", slots: 4, speed: 100, fuelConsumption: 2, process: "food" },
        { id: "minecraft:brewing_stand", slots: 4, speed: 200, fuelConsumption: 1, process: "potions" },
    ];

    const furnaceFuel = [
        { id: "minecraft:lava_bucket", operationTime: 20000 },
        { id: "minecraft:coal_block", operationTime: 16000 },
        { id: "minecraft:dried_kelp_block", operationTime: 4000 },
        { id: "minecraft:blaze_rod", operationTime: 2400 },
        { id: "minecraft:coal", operationTime: 1600 },
        { id: "minecraft:charcoal", operationTime: 1600 },
        { id: "boat", operationTime: 1200 },
        { id: "minecraft:bamboo_mosaic", operationTime: 300 },
        { id: "minecraft:bamboo_mosaic_slab", operationTime: 300 },
        { id: "minecraft:bamboo_mosaic_stairs", operationTime: 300 },
        { id: "minecraft:chiseled_bookshelf", operationTime: 300 },
        { id: "minecraft:bamboo_block", operationTime: 300 },
        { id: "minecraft:stripped_bamboo_block", operationTime: 300 },
        { id: "minecraft:oak_log", operationTime: 300 },
        { id: "minecraft:spruce_log", operationTime: 300 },
        { id: "minecraft:birch_log", operationTime: 300 },
        { id: "minecraft:jungle_log", operationTime: 300 },
        { id: "minecraft:acacia_log", operationTime: 300 },
        { id: "minecraft:dark_oak_log", operationTime: 300 },
        { id: "minecraft:mangrove_log", operationTime: 300 },
        { id: "minecraft:cherry_log", operationTime: 300 },
        { id: "minecraft:pale_oak_log", operationTime: 300 },
        { id: "minecraft:stripped_oak_log", operationTime: 300 },
        { id: "minecraft:stripped_spruce_log", operationTime: 300 },
        { id: "minecraft:stripped_birch_log", operationTime: 300 },
        { id: "minecraft:stripped_jungle_log", operationTime: 300 },
        { id: "minecraft:stripped_acacia_log", operationTime: 300 },
        { id: "minecraft:stripped_dark_oak_log", operationTime: 300 },
        { id: "minecraft:stripped_mangrove_log", operationTime: 300 },
        { id: "minecraft:stripped_cherry_log", operationTime: 300 },
        { id: "minecraft:stripped_pale_oak_log", operationTime: 300 },
        { id: "minecraft:oak_wood", operationTime: 300 },
        { id: "minecraft:spruce_wood", operationTime: 300 },
        { id: "minecraft:birch_wood", operationTime: 300 },
        { id: "minecraft:jungle_wood", operationTime: 300 },
        { id: "minecraft:acacia_wood", operationTime: 300 },
        { id: "minecraft:dark_oak_wood", operationTime: 300 },
        { id: "minecraft:mangrove_wood", operationTime: 300 },
        { id: "minecraft:cherry_wood", operationTime: 300 },
        { id: "minecraft:pale_oak_wood", operationTime: 300 },
        { id: "minecraft:stripped_oak_wood", operationTime: 300 },
        { id: "minecraft:stripped_spruce_wood", operationTime: 300 },
        { id: "minecraft:stripped_birch_wood", operationTime: 300 },
        { id: "minecraft:stripped_jungle_wood", operationTime: 300 },
        { id: "minecraft:stripped_acacia_wood", operationTime: 300 },
        { id: "minecraft:stripped_dark_oak_wood", operationTime: 300 },
        { id: "minecraft:stripped_mangrove_wood", operationTime: 300 },
        { id: "minecraft:stripped_cherry_wood", operationTime: 300 },
        { id: "minecraft:stripped_pale_oak_wood", operationTime: 300 },
        { id: "minecraft:oak_planks", operationTime: 300 },
        { id: "minecraft:spruce_planks", operationTime: 300 },
        { id: "minecraft:birch_planks", operationTime: 300 },
        { id: "minecraft:jungle_planks", operationTime: 300 },
        { id: "minecraft:acacia_planks", operationTime: 300 },
        { id: "minecraft:dark_oak_planks", operationTime: 300 },
        { id: "minecraft:mangrove_planks", operationTime: 300 },
        { id: "minecraft:cherry_planks", operationTime: 300 },
        { id: "minecraft:pale_oak_planks", operationTime: 300 },
        { id: "minecraft:bamboo_planks", operationTime: 300 },
        { id: "minecraft:oak_double_slab", operationTime: 300 },
        { id: "minecraft:oak_slab", operationTime: 300 },
        { id: "minecraft:spruce_double_slab", operationTime: 300 },
        { id: "minecraft:spruce_slab", operationTime: 300 },
        { id: "minecraft:birch_double_slab", operationTime: 300 },
        { id: "minecraft:birch_slab", operationTime: 300 },
        { id: "minecraft:jungle_double_slab", operationTime: 300 },
        { id: "minecraft:jungle_slab", operationTime: 300 },
        { id: "minecraft:acacia_double_slab", operationTime: 300 },
        { id: "minecraft:acacia_slab", operationTime: 300 },
        { id: "minecraft:dark_oak_double_slab", operationTime: 300 },
        { id: "minecraft:dark_oak_slab", operationTime: 300 },
        { id: "minecraft:mangrove_double_slab", operationTime: 300 },
        { id: "minecraft:mangrove_slab", operationTime: 300 },
        { id: "minecraft:cherry_double_slab", operationTime: 300 },
        { id: "minecraft:cherry_slab", operationTime: 300 },
        { id: "minecraft:pale_oak_double_slab", operationTime: 300 },
        { id: "minecraft:pale_oak_slab", operationTime: 300 },
        { id: "minecraft:bamboo_double_slab", operationTime: 300 },
        { id: "minecraft:bamboo_slab", operationTime: 300 },
        { id: "minecraft:oak_stairs", operationTime: 300 },
        { id: "minecraft:spruce_stairs", operationTime: 300 },
        { id: "minecraft:birch_stairs", operationTime: 300 },
        { id: "minecraft:jungle_stairs", operationTime: 300 },
        { id: "minecraft:acacia_stairs", operationTime: 300 },
        { id: "minecraft:dark_oak_stairs", operationTime: 300 },
        { id: "minecraft:mangrove_stairs", operationTime: 300 },
        { id: "minecraft:cherry_stairs", operationTime: 300 },
        { id: "minecraft:pale_oak_stairs", operationTime: 300 },
        { id: "minecraft:bamboo_stairs", operationTime: 300 },
        { id: "minecraft:wooden_pressure_plate", operationTime: 300 },
        { id: "minecraft:spruce_pressure_plate", operationTime: 300 },
        { id: "minecraft:birch_pressure_plate", operationTime: 300 },
        { id: "minecraft:jungle_pressure_plate", operationTime: 300 },
        { id: "minecraft:acacia_pressure_plate", operationTime: 300 },
        { id: "minecraft:dark_oak_pressure_plate", operationTime: 300 },
        { id: "minecraft:mangrove_pressure_plate", operationTime: 300 },
        { id: "minecraft:cherry_pressure_plate", operationTime: 300 },
        { id: "minecraft:pale_oak_pressure_plate", operationTime: 300 },
        { id: "minecraft:bamboo_pressure_plate", operationTime: 300 },
        { id: "minecraft:wooden_button", operationTime: 100 },
        { id: "minecraft:spruce_button", operationTime: 100 },
        { id: "minecraft:birch_button", operationTime: 100 },
        { id: "minecraft:jungle_button", operationTime: 100 },
        { id: "minecraft:acacia_button", operationTime: 100 },
        { id: "minecraft:dark_oak_button", operationTime: 100 },
        { id: "minecraft:mangrove_button", operationTime: 100 },
        { id: "minecraft:cherry_button", operationTime: 100 },
        { id: "minecraft:pale_oak_button", operationTime: 100 },
        { id: "minecraft:bamboo_button", operationTime: 100 },
        { id: "minecraft:trapdoor", operationTime: 300 },
        { id: "minecraft:spruce_trapdoor", operationTime: 300 },
        { id: "minecraft:birch_trapdoor", operationTime: 300 },
        { id: "minecraft:jungle_trapdoor", operationTime: 300 },
        { id: "minecraft:acacia_trapdoor", operationTime: 300 },
        { id: "minecraft:dark_oak_trapdoor", operationTime: 300 },
        { id: "minecraft:mangrove_trapdoor", operationTime: 300 },
        { id: "minecraft:cherry_trapdoor", operationTime: 300 },
        { id: "minecraft:pale_oak_trapdoor", operationTime: 300 },
        { id: "minecraft:bamboo_trapdoor", operationTime: 300 },
        { id: "minecraft:fence_gate", operationTime: 300 },
        { id: "minecraft:spruce_fence_gate", operationTime: 300 },
        { id: "minecraft:birch_fence_gate", operationTime: 300 },
        { id: "minecraft:jungle_fence_gate", operationTime: 300 },
        { id: "minecraft:acacia_fence_gate", operationTime: 300 },
        { id: "minecraft:dark_oak_fence_gate", operationTime: 300 },
        { id: "minecraft:mangrove_fence_gate", operationTime: 300 },
        { id: "minecraft:cherry_fence_gate", operationTime: 300 },
        { id: "minecraft:pale_oak_fence_gate", operationTime: 300 },
        { id: "minecraft:bamboo_fence_gate", operationTime: 300 },
        { id: "minecraft:oak_fence", operationTime: 300 },
        { id: "minecraft:spruce_fence", operationTime: 300 },
        { id: "minecraft:birch_fence", operationTime: 300 },
        { id: "minecraft:jungle_fence", operationTime: 300 },
        { id: "minecraft:acacia_fence", operationTime: 300 },
        { id: "minecraft:dark_oak_fence", operationTime: 300 },
        { id: "minecraft:mangrove_fence", operationTime: 300 },
        { id: "minecraft:cherry_fence", operationTime: 300 },
        { id: "minecraft:pale_oak_fence", operationTime: 300 },
        { id: "minecraft:bamboo_fence", operationTime: 300 },
        { id: "minecraft:mangrove_roots", operationTime: 300 },
        { id: "minecraft:crafting_table", operationTime: 300 },
        { id: "minecraft:cartography_table", operationTime: 300 },
        { id: "minecraft:fletching_table", operationTime: 300 },
        { id: "minecraft:smithing_table", operationTime: 300 },
        { id: "minecraft:loom", operationTime: 300 },
        { id: "minecraft:bookshelf", operationTime: 300 },
        { id: "minecraft:lectern", operationTime: 300 },
        { id: "minecraft:composter", operationTime: 300 },
        { id: "minecraft:chest", operationTime: 300 },
        { id: "minecraft:trapped_chest", operationTime: 300 },
        { id: "minecraft:barrel", operationTime: 300 },
        { id: "minecraft:daylight_detector", operationTime: 300 },
        { id: "minecraft:jukebox", operationTime: 300 },
        { id: "minecraft:noteblock", operationTime: 300 },
        { id: "minecraft:standing_banner", operationTime: 300 },
        { id: "minecraft:wall_banner", operationTime: 300 },
        { id: "minecraft:banner", operationTime: 300 },
        { id: "minecraft:fishing_rod", operationTime: 300 },
        { id: "minecraft:crossbow", operationTime: 200 },
        { id: "minecraft:bow", operationTime: 200 },
        { id: "minecraft:wooden_door", operationTime: 200 },
        { id: "minecraft:spruce_door", operationTime: 200 },
        { id: "minecraft:birch_door", operationTime: 200 },
        { id: "minecraft:jungle_door", operationTime: 200 },
        { id: "minecraft:acacia_door", operationTime: 200 },
        { id: "minecraft:dark_oak_door", operationTime: 200 },
        { id: "minecraft:mangrove_door", operationTime: 200 },
        { id: "minecraft:cherry_door", operationTime: 200 },
        { id: "minecraft:pale_oak_door", operationTime: 200 },
        { id: "minecraft:bamboo_door", operationTime: 200 },
        { id: "minecraft:wooden_door", operationTime: 200 },
        { id: "minecraft:spruce_door", operationTime: 200 },
        { id: "minecraft:birch_door", operationTime: 200 },
        { id: "minecraft:jungle_door", operationTime: 200 },
        { id: "minecraft:acacia_door", operationTime: 200 },
        { id: "minecraft:dark_oak_door", operationTime: 200 },
        { id: "minecraft:mangrove_door", operationTime: 200 },
        { id: "minecraft:standing_sign", operationTime: 200 },
        { id: "minecraft:spruce_standing_sign", operationTime: 200 },
        { id: "minecraft:birch_standing_sign", operationTime: 200 },
        { id: "minecraft:jungle_standing_sign", operationTime: 200 },
        { id: "minecraft:acacia_standing_sign", operationTime: 200 },
        { id: "minecraft:darkoak_standing_sign", operationTime: 200 },
        { id: "minecraft:mangrove_standing_sign", operationTime: 200 },
        { id: "minecraft:cherry_standing_sign", operationTime: 200 },
        { id: "minecraft:pale_oak_standing_sign", operationTime: 200 },
        { id: "minecraft:bamboo_standing_sign", operationTime: 200 },
        { id: "minecraft:wall_sign", operationTime: 200 },
        { id: "minecraft:spruce_wall_sign", operationTime: 200 },
        { id: "minecraft:birch_wall_sign", operationTime: 200 },
        { id: "minecraft:jungle_wall_sign", operationTime: 200 },
        { id: "minecraft:acacia_wall_sign", operationTime: 200 },
        { id: "minecraft:darkoak_wall_sign", operationTime: 200 },
        { id: "minecraft:mangrove_wall_sign", operationTime: 200 },
        { id: "minecraft:cherry_wall_sign", operationTime: 200 },
        { id: "minecraft:pale_oak_wall_sign", operationTime: 200 },
        { id: "minecraft:bamboo_wall_sign", operationTime: 200 },
        { id: "minecraft:oak_sign", operationTime: 200 },
        { id: "minecraft:spruce_sign", operationTime: 200 },
        { id: "minecraft:birch_sign", operationTime: 200 },
        { id: "minecraft:jungle_sign", operationTime: 200 },
        { id: "minecraft:acacia_sign", operationTime: 200 },
        { id: "minecraft:dark_oak_sign", operationTime: 200 },
        { id: "minecraft:mangrove_sign", operationTime: 200 },
        { id: "minecraft:cherry_sign", operationTime: 200 },
        { id: "minecraft:pale_oak_sign", operationTime: 200 },
        { id: "minecraft:bamboo_sign", operationTime: 200 },
        { id: "minecraft:oak_hanging_sign", operationTime: 200 },
        { id: "minecraft:spruce_hanging_sign", operationTime: 200 },
        { id: "minecraft:birch_hanging_sign", operationTime: 200 },
        { id: "minecraft:jungle_hanging_sign", operationTime: 200 },
        { id: "minecraft:acacia_hanging_sign", operationTime: 200 },
        { id: "minecraft:dark_oak_hanging_sign", operationTime: 200 },
        { id: "minecraft:mangrove_hanging_sign", operationTime: 200 },
        { id: "minecraft:cherry_hanging_sign", operationTime: 200 },
        { id: "minecraft:pale_oak_hanging_sign", operationTime: 200 },
        { id: "minecraft:bamboo_hanging_sign", operationTime: 200 },
        { id: "minecraft:wooden_pickaxe", operationTime: 200 },
        { id: "minecraft:wooden_shovel", operationTime: 200 },
        { id: "minecraft:wooden_hoe", operationTime: 200 },
        { id: "minecraft:wooden_axe", operationTime: 200 },
        { id: "minecraft:wooden_sword", operationTime: 200 },
        { id: "minecraft:bowl", operationTime: 200 },
        { id: "minecraft:oak_sapling", operationTime: 100 },
        { id: "minecraft:spruce_sapling", operationTime: 100 },
        { id: "minecraft:birch_sapling", operationTime: 100 },
        { id: "minecraft:jungle_sapling", operationTime: 100 },
        { id: "minecraft:acacia_sapling", operationTime: 100 },
        { id: "minecraft:dark_oak_sapling", operationTime: 100 },
        { id: "minecraft:cherry_sapling", operationTime: 100 },
        { id: "minecraft:pale_oak_sapling", operationTime: 100 },
        { id: "minecraft:stick", operationTime: 100 },
        { id: "minecraft:deadbush", operationTime: 100 },
        { id: "minecraft:azalea", operationTime: 100 },
        { id: "minecraft:leaf_litter", operationTime: 100 },
        { id: "minecraft:short_dry_grass", operationTime: 100 },
        { id: "minecraft:tall_dry_grass", operationTime: 100 },
        { id: "minecraft:bamboo", operationTime: 50 },
        { id: "minecraft:scaffolding", operationTime: 50 },
    ];

    const furnaceRecipes = [
        
        { product: "minecraft:baked_potato", ingredient: "minecraft:potato", recipe: "food" },
        { product: "minecraft:dried_kelp", ingredient: "minecraft:kelp", recipe: "food" },
        { product: "minecraft:cooked_beef", ingredient: "minecraft:beef", recipe: "food" },
        { product: "minecraft:cooked_porkchop", ingredient: "minecraft:porkchop", recipe: "food" },
        { product: "minecraft:cooked_mutton", ingredient: "minecraft:mutton", recipe: "food" },
        { product: "minecraft:cooked_chicken", ingredient: "minecraft:chicken", recipe: "food" },
        { product: "minecraft:cooked_rabbit", ingredient: "minecraft:rabbit", recipe: "food" },
        { product: "minecraft:cooked_cod", ingredient: "minecraft:cod", recipe: "food" },
        { product: "minecraft:cooked_salmon", ingredient: "minecraft:salmon", recipe: "food" },

        
        { product: "minecraft:iron_ingot", ingredient: "minecraft:raw_iron", recipe: "ores" },
        { product: "minecraft:copper_ingot", ingredient: "minecraft:raw_copper", recipe: "ores" },
        { product: "minecraft:gold_ingot", ingredient: "minecraft:raw_gold", recipe: "ores" },
        { product: "minecraft:gold_ingot", ingredient: "minecraft:nether_gold_ore", recipe: "ores" },
        { product: "minecraft:netherite_scrap", ingredient: "minecraft:ancient_debris", recipe: "ores" },
        
        { product: "minecraft:redstone", ingredient: "minecraft:redstone_ore", recipe: "ores" },
        { product: "minecraft:redstone", ingredient: "minecraft:deepslate_redstone_ore", recipe: "ores" },
        { product: "minecraft:coal", ingredient: "minecraft:coal_ore", recipe: "ores" },
        { product: "minecraft:coal", ingredient: "minecraft:deepslate_coal_ore", recipe: "ores" },
        { product: "minecraft:emerald", ingredient: "minecraft:emerald_ore", recipe: "ores" },
        { product: "minecraft:emerald", ingredient: "minecraft:deepslate_emerald_ore", recipe: "ores" },
        { product: "minecraft:lapis_lazuli", ingredient: "minecraft:lapis_ore", recipe: "ores" },
        { product: "minecraft:lapis_lazuli", ingredient: "minecraft:deepslate_lapis_ore", recipe: "ores" },
        { product: "minecraft:diamond", ingredient: "minecraft:diamond_ore", recipe: "ores" },
        { product: "minecraft:diamond", ingredient: "minecraft:deepslate_diamond_ore", recipe: "ores" },
        { product: "minecraft:quartz", ingredient: "minecraft:quartz_ore", recipe: "ores" },
        { product: "minecraft:iron_ingot", ingredient: "minecraft:iron_ore", recipe: "ores" },
        { product: "minecraft:iron_ingot", ingredient: "minecraft:deepslate_iron_ore", recipe: "ores" },
        { product: "minecraft:copper_ingot", ingredient: "minecraft:copper_ore", recipe: "ores" },
        { product: "minecraft:copper_ingot", ingredient: "minecraft:deepslate_copper_ore", recipe: "ores" },
        { product: "minecraft:gold_ingot", ingredient: "minecraft:gold_ore", recipe: "ores" },
        { product: "minecraft:gold_ingot", ingredient: "minecraft:deepslate_gold_ore", recipe: "ores" },
        
        { product: "minecraft:iron_nugget", ingredient: "minecraft:iron_shovel", recipe: "ores" },
        { product: "minecraft:iron_nugget", ingredient: "minecraft:iron_pickaxe", recipe: "ores" },
        { product: "minecraft:iron_nugget", ingredient: "minecraft:iron_axe", recipe: "ores" },
        { product: "minecraft:iron_nugget", ingredient: "minecraft:iron_hoe", recipe: "ores" },
        { product: "minecraft:iron_nugget", ingredient: "minecraft:iron_sword", recipe: "ores" },
        { product: "minecraft:iron_nugget", ingredient: "minecraft:chainmail_helmet", recipe: "ores" },
        { product: "minecraft:iron_nugget", ingredient: "minecraft:chainmail_chestplate", recipe: "ores" },
        { product: "minecraft:iron_nugget", ingredient: "minecraft:chainmail_leggings", recipe: "ores" },
        { product: "minecraft:iron_nugget", ingredient: "minecraft:chainmail_boots", recipe: "ores" },
        { product: "minecraft:iron_nugget", ingredient: "minecraft:iron_helmet", recipe: "ores" },
        { product: "minecraft:iron_nugget", ingredient: "minecraft:iron_chestplate", recipe: "ores" },
        { product: "minecraft:iron_nugget", ingredient: "minecraft:iron_leggings", recipe: "ores" },
        { product: "minecraft:iron_nugget", ingredient: "minecraft:iron_boots", recipe: "ores" },
        { product: "minecraft:iron_nugget", ingredient: "minecraft:iron_horse_armor", recipe: "ores" },
        { product: "minecraft:gold_nugget", ingredient: "minecraft:golden_shovel", recipe: "ores" },
        { product: "minecraft:gold_nugget", ingredient: "minecraft:golden_pickaxe", recipe: "ores" },
        { product: "minecraft:gold_nugget", ingredient: "minecraft:golden_axe", recipe: "ores" },
        { product: "minecraft:gold_nugget", ingredient: "minecraft:golden_hoe", recipe: "ores" },
        { product: "minecraft:gold_nugget", ingredient: "minecraft:golden_sword", recipe: "ores" },
        { product: "minecraft:gold_nugget", ingredient: "minecraft:golden_helmet", recipe: "ores" },
        { product: "minecraft:gold_nugget", ingredient: "minecraft:golden_chestplate", recipe: "ores" },
        { product: "minecraft:gold_nugget", ingredient: "minecraft:golden_leggings", recipe: "ores" },
        { product: "minecraft:gold_nugget", ingredient: "minecraft:golden_boots", recipe: "ores" },
        { product: "minecraft:gold_nugget", ingredient: "minecraft:golden_horse_armor", recipe: "ores" },
        { product: "minecraft:copper_nugget", ingredient: "minecraft:copper_shovel", recipe: "ores" },
        { product: "minecraft:copper_nugget", ingredient: "minecraft:copper_pickaxe", recipe: "ores" },
        { product: "minecraft:copper_nugget", ingredient: "minecraft:copper_axe", recipe: "ores" },
        { product: "minecraft:copper_nugget", ingredient: "minecraft:copper_hoe", recipe: "ores" },
        { product: "minecraft:copper_nugget", ingredient: "minecraft:copper_sword", recipe: "ores" },
        { product: "minecraft:copper_nugget", ingredient: "minecraft:copper_helmet", recipe: "ores" },
        { product: "minecraft:copper_nugget", ingredient: "minecraft:copper_chestplate", recipe: "ores" },
        { product: "minecraft:copper_nugget", ingredient: "minecraft:copper_leggings", recipe: "ores" },
        { product: "minecraft:copper_nugget", ingredient: "minecraft:copper_boots", recipe: "ores" },

        
        { product: "minecraft:stone", ingredient: "minecraft:cobblestone", recipe: "furnace" },
        { product: "minecraft:smooth_stone", ingredient: "minecraft:stone", recipe: "furnace" },
        { product: "minecraft:cracked_stone_bricks", ingredient: "minecraft:stone_bricks", recipe: "furnace" },
        { product: "minecraft:deepslate", ingredient: "minecraft:cobbled_deepslate", recipe: "furnace" },
        { product: "minecraft:cracked_deepslate_bricks", ingredient: "minecraft:deepslate_bricks", recipe: "furnace" },
        { product: "minecraft:cracked_deepslate_tiles", ingredient: "minecraft:deepslate_tiles", recipe: "furnace" },
        { product: "minecraft:smooth_sandstone", ingredient: "minecraft:sandstone", recipe: "furnace" },
        { product: "minecraft:smooth_red_sandstone", ingredient: "minecraft:red_sandstone", recipe: "furnace" },
        { product: "minecraft:cracked_nether_bricks", ingredient: "minecraft:nether_brick", recipe: "furnace" },
        { product: "minecraft:cracked_polished_blackstone_bricks", ingredient: "minecraft:polished_blackstone_bricks", recipe: "furnace" },
        { product: "minecraft:smooth_quartz", ingredient: "minecraft:quartz_block", recipe: "furnace" },
        { product: "minecraft:hardened_clay", ingredient: "minecraft:clay", recipe: "furnace" },
        { product: "minecraft:white_glazed_terracotta", ingredient: "minecraft:white_terracotta", recipe: "furnace" },
        { product: "minecraft:orange_glazed_terracotta", ingredient: "minecraft:orange_terracotta", recipe: "furnace" },
        { product: "minecraft:magenta_glazed_terracotta", ingredient: "minecraft:magenta_terracotta", recipe: "furnace" },
        { product: "minecraft:light_blue_glazed_terracotta", ingredient: "minecraft:light_blue_terracotta", recipe: "furnace" },
        { product: "minecraft:yellow_glazed_terracotta", ingredient: "minecraft:yellow_terracotta", recipe: "furnace" },
        { product: "minecraft:lime_glazed_terracotta", ingredient: "minecraft:lime_terracotta", recipe: "furnace" },
        { product: "minecraft:pink_glazed_terracotta", ingredient: "minecraft:pink_terracotta", recipe: "furnace" },
        { product: "minecraft:gray_glazed_terracotta", ingredient: "minecraft:gray_terracotta", recipe: "furnace" },
        { product: "minecraft:silver_glazed_terracotta", ingredient: "minecraft:light_gray_terracotta", recipe: "furnace" },
        { product: "minecraft:cyan_glazed_terracotta", ingredient: "minecraft:cyan_terracotta", recipe: "furnace" },
        { product: "minecraft:purple_glazed_terracotta", ingredient: "minecraft:purple_terracotta", recipe: "furnace" },
        { product: "minecraft:blue_glazed_terracotta", ingredient: "minecraft:blue_terracotta", recipe: "furnace" },
        { product: "minecraft:brown_glazed_terracotta", ingredient: "minecraft:brown_terracotta", recipe: "furnace" },
        { product: "minecraft:green_glazed_terracotta", ingredient: "minecraft:green_terracotta", recipe: "furnace" },
        { product: "minecraft:red_glazed_terracotta", ingredient: "minecraft:red_terracotta", recipe: "furnace" },
        { product: "minecraft:black_glazed_terracotta", ingredient: "minecraft:black_terracotta", recipe: "furnace" },
        { product: "minecraft:glass", ingredient: "minecraft:sand", recipe: "furnace" },
        { product: "minecraft:sponge", ingredient: "minecraft:wet_sponge", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:oak_log", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:spruce_log", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:birch_log", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:jungle_log", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:acacia_log", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:dark_oak_log", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:mangrove_log", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:cherry_log", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:pale_oak_log", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:oak_wood", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:spruce_wood", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:birch_wood", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:jungle_wood", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:acacia_wood", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:dark_oak_wood", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:mangrove_wood", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:cherry_wood", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:pale_oak_wood", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:stripped_oak_log", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:stripped_spruce_log", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:stripped_birch_log", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:stripped_jungle_log", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:stripped_acacia_log", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:stripped_dark_oak_log", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:stripped_mangrove_log", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:stripped_cherry_log", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:stripped_pale_oak_log", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:stripped_oak_wood", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:stripped_spruce_wood", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:stripped_birch_wood", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:stripped_jungle_wood", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:stripped_acacia_wood", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:stripped_dark_oak_wood", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:stripped_mangrove_wood", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:stripped_cherry_wood", recipe: "furnace" },
        { product: "minecraft:charcoal", ingredient: "minecraft:stripped_pale_oak_wood", recipe: "furnace" },
        { product: "minecraft:popped_chorus_fruit", ingredient: "minecraft:chorus_fruit", recipe: "furnace" },
        { product: "minecraft:lime_dye", ingredient: "minecraft:sea_pickle", recipe: "furnace" },
        { product: "minecraft:green_dye", ingredient: "minecraft:cactus", recipe: "furnace" },
        { product: "minecraft:brick", ingredient: "minecraft:clay_ball", recipe: "furnace" },
        { product: "minecraft:netherbrick", ingredient: "minecraft:netherrack", recipe: "furnace" },
        { product: "minecraft:resin_brick", ingredient: "minecraft:resin_clump", recipe: "furnace" },
        { product: "minecraft:leaf_litter", ingredient: "minecraft:oak_leaves", recipe: "furnace" },
        { product: "minecraft:leaf_litter", ingredient: "minecraft:spruce_leaves", recipe: "furnace" },
        { product: "minecraft:leaf_litter", ingredient: "minecraft:birch_leaves", recipe: "furnace" },
        { product: "minecraft:leaf_litter", ingredient: "minecraft:jungle_leaves", recipe: "furnace" },
        { product: "minecraft:leaf_litter", ingredient: "minecraft:acacia_leaves", recipe: "furnace" },
        { product: "minecraft:leaf_litter", ingredient: "minecraft:dark_oak_leaves", recipe: "furnace" },
        { product: "minecraft:leaf_litter", ingredient: "minecraft:mangrove_leaves", recipe: "furnace" },
        { product: "minecraft:leaf_litter", ingredient: "minecraft:cherry_leaves", recipe: "furnace" },
        { product: "minecraft:leaf_litter", ingredient: "minecraft:pale_oak_leaves", recipe: "furnace" },
        { product: "minecraft:leaf_litter", ingredient: "minecraft:azalea_leaves", recipe: "furnace" },
        { product: "minecraft:leaf_litter", ingredient: "minecraft:azalea_leaves_flowered", recipe: "furnace" },
    ];


    let
        lastRealTime = world.getDynamicProperty("lastRealTime"),
        lastTick = system.currentTick,
        currentRealTime = Date.now(),
        currentTick = lastTick,
        paused = false; 

    
    system.runInterval(() => {

        const forebodingScore = fo.forebodingScore;
        currentRealTime = Date.now();

        if (forebodingScore >= forebodingScoreCheck3 || forebodingScore <= forebodingScoreCheck7) {
            const player = world.getAllPlayers()[0];
            if (!player) return;

            currentTick = system.currentTick;

            
            const ticksPassed = currentTick - lastTick;

            
            const actualTimePassed = currentRealTime - lastRealTime;
            const ExpectedTicksPassed = Math.round(actualTimePassed / 50);

            if (ticksPassed != ExpectedTicksPassed) {
                
            }

            
            if (ExpectedTicksPassed > (ticksPassed + lenienceTicks)) {
                if (!paused) {
                    
                    paused = true;
                    

                    P82forebearerSafeGuard(ExpectedTicksPassed);

                    
                    if (forebodingScore < forebodingScoreCheck4) {
                        if (ExpectedTicksPassed < Capt03MinElapsedTime || Math.random() > chapt03Chance) return;
                    };

                    
                    advanceTime(ExpectedTicksPassed, forebodingScore);
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    system.runJob(moveMobAround(player, ExpectedTicksPassed));
                    
                    system.runJob(despawnItems(player, ExpectedTicksPassed));
                    
                    system.runTimeout(() => {
                        system.runJob(respawnCycle(player, ExpectedTicksPassed));
                    }, 1)
                    
                    WeatherChange(player, ExpectedTicksPassed);
                    
                    randomTickChanger(ExpectedTicksPassed);
                    
                    
                    stopSound(player, ExpectedTicksPassed, forebodingScore);
                    
                    
                    blockExplode(player);
                    
                    system.runJob(CreepersExplosion(player));
                    
                    
                    handleFallingBlocks(player, ExpectedTicksPassed);
                    
                    otherFallingEntities(player, ExpectedTicksPassed);
                    
                    
                    projectilesSim(player, ExpectedTicksPassed);
                    
                    eyeOfEnderLogic(player, ExpectedTicksPassed);
                    
                    
                    system.runJob(workingFurnaces(player, ExpectedTicksPassed));
                    


                    
                    
                    if (Math.random() < eventChancesRare) doorOpenCloses(player);
                    
                    if (Math.random() < eventChancesUncommon) playRandomNoises(player);
                    
                    
                    P82EventsLogic(player, forebodingScore, ExpectedTicksPassed);
                    P82giveBook(player, forebodingScore, ExpectedTicksPassed);

                }
            } else if (paused) {
                
                paused = false;
                
            }

            
            lastRealTime = currentRealTime;
            world.setDynamicProperty("lastRealTime", lastRealTime)
            lastTick = currentTick;
        } else {
            lastRealTime = currentRealTime;
            world.setDynamicProperty("lastRealTime", lastRealTime) 
        }

    }, 5); 

    

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

    
    function getFallDistance(ExpectedTicksPassed, maxFallDistance) {
        let velocity = 0;
        let distance = 0;

        for (let t = 0; t < ExpectedTicksPassed && distance < maxFallDistance; t++) {
            velocity += -0.08;
            velocity *= 0.98;
            if (velocity < -3.92) velocity = -3.92;
            distance += -velocity;
        }

        return distance;
    }

    
    function thrownPhysics(startPos, dir, ticks, entity, accelerationI, dragI, dragII) {
        

        const
            maxIterations = Math.min(ticks, 300),
            dimension = entity.dimension;

        let
            acceleration = accelerationI, 
            dragH = dragI, 
            dragV = dragII, 
            pos = { ...startPos },
            velocity = dir, 

            landingLocation;

        for (let i = 0; i < maxIterations && pos.y > dimension.heightRange.min; i++) {
            
            pos.x += velocity.x;
            pos.y += velocity.y;
            pos.z += velocity.z;

            
            velocity.y -= acceleration;

            
            velocity.x *= dragH;
            velocity.y *= dragV;
            velocity.z *= dragH;

            
            const block = dimension.getBlock({
                x: pos.x,
                y: pos.y,
                z: pos.z
            });

            landingLocation = {
                x: pos.x,
                y: pos.y,
                z: pos.z
            };

            if (block && !block.isAir && !block.isLiquid) {
                
                
                return landingLocation;
            }
        }

        
        
        return landingLocation;
    };

    
    function removeFurnaceFromList(furnaceLoc, allFurnaceLocations) {
        const updatedLocations = allFurnaceLocations.filter(loc =>
            !(loc.x === furnaceLoc.x &&
                loc.y === furnaceLoc.y &&
                loc.z === furnaceLoc.z &&
                loc.dimensionId === furnaceLoc.dimensionId)
        );
        world.setDynamicProperty(FURNACE_LIST_PROPERTY, JSON.stringify(updatedLocations));
        

    };



    

    
    function advanceTime(ExpectedTicksPassed, forebodingScore) {

        if (forebodingScore >= forebodingScoreCheck3) {

            
            if (world.gameRules.doDayLightCycle) {
                fo.overworld.runCommand(`time add ${ExpectedTicksPassed}`)
            }

        } else if (forebodingScore <= forebodingScoreCheck7) {

            fo.overworld.runCommand(`time add ${-ExpectedTicksPassed * 6}`)

        }
    }

    
    function* moveMobAround(player, ExpectedTicksPassed) {

        const playerLocation = player.location;
        const steps = Math.min(
            maxMobSteps,
            Math.floor(ExpectedTicksPassed / (lenienceTicks * 4))
        );

        

        
        
        
        if (player.isFalling || player.isGliding || player.isJumping || player.isSwimming || player.isClimbing) {
            entityIsFalling(player, ExpectedTicksPassed);
        };


        

        
        const nearbyEntities = player.dimension.getEntities({
            location: playerLocation,
            maxDistance: 32,
            families: ["mob"],
            excludeTypes: ["minecraft:player", "minecraft:npc", "minecraft:shulker", "minecraft:armor_stand"],
        });

        system.runJob(ageMob(ExpectedTicksPassed, nearbyEntities));
        system.runJob(effectRemoval(player, nearbyEntities, ExpectedTicksPassed));
        system.runJob(tradeRefill(nearbyEntities, ExpectedTicksPassed));

        let movedCount = 0;

        for (const entity of nearbyEntities) {
            try {
                
                
                const leashComponent = entity.getComponent("minecraft:leashable");
                const isLeashed = leashComponent?.isLeashed ?? false;

                if (isLeashed) {
                    if (!entity.isFalling) {
                        moveEntityAfterFall(entity, player, Math.min(steps, 2), movedCount);
                    }
                    continue;
                }

                if (leashComponent?.isLeashed) continue;

                
                if (entity.isFalling) {
                    entityIsFalling(entity, ExpectedTicksPassed);
                };

                
                system.runTimeout(() => {
                    try {
                        if (!entity || !entity.isValid) return;

                        
                        const blockBelow = player.dimension.getBlock({
                            x: Math.floor(entity.location.x),
                            y: Math.floor(entity.location.y) - 1,
                            z: Math.floor(entity.location.z)
                        });

                        if (!entity.isOnGround && !entity.isFalling && blockBelow?.isAir) {
                            if (flyingTypes.includes(entity.typeId)) {
                                moveFlyingEntity(entity, steps, movedCount);
                                return;
                            }
                        }

                        moveEntityAfterFall(entity, player, steps, movedCount);

                        if (movedCount > 0) {
                            
                        }
                    } catch (e) { }
                }, 2);
            } catch (e) { }
            yield;
        }

    }

    
    
    function entityIsFalling(entity, ExpectedTicksPassed) {
        const
            dimension = entity.dimension,
            startPos = entity.location;

        let
            calculatedFallDistance,
            calculatedLanding,
            hitBlock;

        if (entity.typeId !== "minecraft:player") {
            const
                maxFallDistance = Math.max(Math.min(160, (startPos.y - dimension.heightRange.min)), 0),
                rayOptions = {
                    maxDistance: calculatedFallDistance,
                    includeLiquidBlocks: false,
                    includePassableBlocks: false
                };

            calculatedFallDistance = getFallDistance(ExpectedTicksPassed, maxFallDistance);
            hitBlock = dimension.getBlockBelow(entity.location, rayOptions);

        } else {
            
            const
                dir = entity.getVelocity(),
                acceleration = 0.08,
                dragH = 0.91,
                dragV = 0.98;

            calculatedLanding = thrownPhysics(startPos, dir, ExpectedTicksPassed, entity, acceleration, dragH, dragV);

            

            
            if (!entity.isFalling && entity.isGliding) {

                hitBlock = dimension.getBlock(calculatedLanding);

            } else {

                
                const
                    maxFallDistance = Math.max(Math.min(160, (calculatedLanding.y - dimension.heightRange.min)), 0),
                    rayOptions = {
                        maxDistance: calculatedFallDistance,
                        includeLiquidBlocks: false,
                        includePassableBlocks: false
                    };

                calculatedFallDistance = getFallDistance(Math.max(ExpectedTicksPassed - 300, 0), maxFallDistance);
                hitBlock = dimension.getBlockBelow({
                    x: calculatedLanding.x,
                    y: calculatedLanding.y + 1,
                    z: calculatedLanding.z
                }, rayOptions);
                

            };
        }

        if (!hitBlock) {
            
            const destY = Math.max(startPos.y - calculatedFallDistance + 1, dimension.heightRange.min + 1);
            entity.teleport({ x: startPos.x, y: destY, z: startPos.z }, {
                dimension: dimension,
                rotation: entity.getRotation(),
            });
            return;
        }

        const landingY = hitBlock.location.y + 1;
        const fallDistance = Math.floor(startPos.y - landingY);
        const destination = {
            x: hitBlock.location.x,
            y: landingY,
            z: hitBlock.location.z
        };
        const destinationBlock = dimension.getBlock(destination);

        try {
            entity.teleport(destination, {
                dimension: dimension,
                rotation: entity.getRotation()
            });

            
            if (!destinationBlock.isLiquid && !destinationBlock.isWaterlogged) {
                
                if (entity.typeId === "minecraft:player") {
                    const chestSlot = entity.getComponent("minecraft:equippable")?.getEquipment("chest");
                    if (chestSlot && chestSlot.typeId === "minecraft:elytra") {
                        
                        return;
                    }
                };

                const damage = Math.floor(fallDistance - 3);
                if (damage > 0) {
                    entity.applyDamage(damage, { cause: "fall" });
                    
                } else {
                    
                }
            } else {
                
            }
        } catch (e) {
            console.log(`Failed to teleport or apply fall damage to ${entity.typeId}: ${e}`);
        }
    };

    function moveEntityAfterFall(entity, player, steps, movedCount) {
        if (movedCount >= maxEntitiesToMove) return;
        if (!entity.isOnGround && entity.isFalling) return;

        const isRiding = entity.getComponent("minecraft:riding");

        if (isRiding) return;

        let currentPos = { ...entity.location };
        currentPos.x = Math.floor(currentPos.x);
        currentPos.y = Math.floor(currentPos.y);
        currentPos.z = Math.floor(currentPos.z);

        let lastValidPos = null;
        let stepsTaken = 0;

        while (stepsTaken < steps) {
            const offsets = [
                { x: 0, z: -1 }, 
                { x: 1, z: 0 },  
                { x: 0, z: 1 },  
                { x: -1, z: 0 }  
            ];
            const offset = offsets[Math.floor(Math.random() * 4)];

            const targetX = currentPos.x + offset.x;
            const targetZ = currentPos.z + offset.z;
            const yLevels = [currentPos.y + 1, currentPos.y, currentPos.y - 1];

            for (const y of yLevels) {
                const
                    airBlock = player.dimension.getBlock({ x: targetX, y, z: targetZ }),
                    belowBlock = player.dimension.getBlock({ x: targetX, y: y - 1, z: targetZ }),
                    aboveBlock = player.dimension.getBlock({ x: targetX, y: y + 1, z: targetZ });

                if (!airBlock || !belowBlock || !aboveBlock) continue;
                if (!airBlock.isAir || !aboveBlock.isAir) continue;
                if (belowBlock.isAir || belowBlock.isLiquid) continue;
                if (noGoBlocks.some(bad => belowBlock.typeId.includes(bad))) continue;

                currentPos = { x: targetX, y, z: targetZ };
                lastValidPos = { ...currentPos };
                break;
            }

            stepsTaken++;
        }

        if (lastValidPos) {
            entity.teleport({
                x: lastValidPos.x + 0.5,
                y: lastValidPos.y,
                z: lastValidPos.z + 0.5
            }, {
                dimension: player.dimension,
                rotation: entity.getRotation()
            });

            movedCount++;
            
        }
    };

    function moveFlyingEntity(entity, steps, movedCount) {
        if (movedCount >= maxEntitiesToMove) return;

        let currentPos = { ...entity.location };
        currentPos.x = Math.floor(currentPos.x);
        currentPos.y = Math.floor(currentPos.y);
        currentPos.z = Math.floor(currentPos.z);

        let lastValidPos = null;
        let stepsTaken = 0;

        const dimension = entity.dimension;

        while (stepsTaken < steps) {
            
            const directions = [
                { x: 1, y: 0, z: 0 },   
                { x: -1, y: 0, z: 0 },  
                { x: 0, y: 0, z: 1 },   
                { x: 0, y: 0, z: -1 },  
                { x: 0, y: 1, z: 0 },   
                { x: 0, y: -1, z: 0 }   
            ];
            const offset = directions[Math.floor(Math.random() * directions.length)];

            const targetX = currentPos.x + offset.x;
            const targetY = currentPos.y + offset.y;
            const targetZ = currentPos.z + offset.z;

            const airBlock = dimension.getBlock({ x: targetX, y: targetY, z: targetZ });
            const aboveBlock = dimension.getBlock({ x: targetX, y: targetY + 1, z: targetZ });
            const belowBlock = dimension.getBlock({ x: targetX, y: targetY - 1, z: targetZ });

            if (!airBlock || !aboveBlock || !belowBlock) {
                stepsTaken++;
                continue;
            }

            if (airBlock.isAir && aboveBlock.isAir && belowBlock.isAir) {
                currentPos = { x: targetX, y: targetY, z: targetZ };
                lastValidPos = { ...currentPos };
            }

            stepsTaken++;
        }

        if (lastValidPos) {
            entity.teleport({
                x: lastValidPos.x + 0.5,
                y: lastValidPos.y,
                z: lastValidPos.z + 0.5
            }, {
                dimension: dimension,
                rotation: entity.getRotation()
            });

            movedCount++;
            
        }
    };

    
    function* ageMob(ExpectedTicksPassed, nearbyEntities) {

        const ageIncrease = Math.floor(ExpectedTicksPassed / 20);

        for (const entity of nearbyEntities) {
            try {
                const
                    ageComponent = entity.getComponent("minecraft:ageable"),
                    ageDuration = ageComponent?.duration;

                if (ageIncrease >= ageDuration) {
                    try {
                        entity.triggerEvent("minecraft:ageable_grow_up");
                        
                    } catch (e) {
                        console.log(`Failed to trigger grow up for ${entity.typeId}: ${e}`);
                    }
                }
            } catch (e) { }
            yield;
        }

    };


    
    function* effectRemoval(player, nearbyEntities, ExpectedTicksPassed) {
        const secondsPassed = Math.floor(ExpectedTicksPassed / 20);

        const entities = [player, ...nearbyEntities];

        for (const entity of entities) {
            try {
                if (!entity || !entity.isValid) continue;

                
                const activeEffects = entity.getEffects();
                for (const effect of activeEffects) {
                    const
                        newDuration = effect.duration - ExpectedTicksPassed,
                        effectType = effect.typeId,
                        effectAmplifier = effect.amplifier;

                    
                    const match = effectsDamage.find(entry =>
                        entry.effectId === effectType && entry.amplifier === effectAmplifier
                    );

                    if (match) {
                        const
                            effectDamageTicks = Math.min(ExpectedTicksPassed, effect.duration),
                            damageInstances = Math.floor(effectDamageTicks / match.ticksPerDamage);
                        if (damageInstances > 0) {
                            try {
                                entity.applyDamage(damageInstances, { cause: "wither" });
                                
                            } catch (e) {
                                console.warn(`Failed to apply ${effectType} damage to ${entity.typeId}: ${e}`);
                            }
                        }
                    };
                    if (newDuration <= 0) {
                        
                        entity.removeEffect(effectType);
                    } else {

                        
                        
                        entity.removeEffect(effectType);
                        system.runTimeout(() => {
                            try {
                                entity.addEffect(effectType, newDuration, {
                                    amplifier: effectAmplifier,
                                    showParticles: false, 
                                });
                            } catch (e) {
                                
                            }
                        }, 3)
                    }
                }

                
                const onFire = entity.getComponent("minecraft:onfire");
                if (onFire && secondsPassed > 15) {
                    const fireDamage = Math.floor(onFire?.onFireTicksRemaining / 20);

                    try {
                        entity.extinguishFire();
                        entity.applyDamage(fireDamage, { cause: "fireTick" });
                        
                    } catch (e) {
                        console.log(`Failed to extinguish fire on ${entity.typeId}: ${e}`);
                    }
                }
            } catch (e) { }
            yield;
        }
    };


    
    function* tradeRefill(nearbyEntities, ExpectedTicksPassed) {

        
        if (ExpectedTicksPassed >= 24000) {

            for (const entity of nearbyEntities) {
                try {
                    if (entity.typeId === "minecraft:villager_v2") {
                        entity.triggerEvent("minecraft:resupply_trades");
                        
                    }
                } catch (e) {
                    console.log(`Failed to restock trades: ${e}`);
                }

                yield;
            }
        }
    };


    
    function* despawnItems(player, ExpectedTicksPassed) {

        if (ExpectedTicksPassed >= 6000) {

            
            const nearbyItems = player.dimension.getEntities({
                location: player.location,
                maxDistance: 128,
                type: "item",
            });
            for (const item of nearbyItems) {
                try { item.remove() } catch (e) { }
                yield;
            }
        }
    };


    
    function* respawnCycle(player, ExpectedTicksPassed) {
        
        if (ExpectedTicksPassed > 24000) {
            const playerDimension = player.dimension;
            const timeOfDay = world.getTimeOfDay();

            const nearbyMobs = playerDimension.getEntities({
                location: player.location,
                maxDistance: 45,
                families: ["undead", "creeper", "witch", "spider", "enderman"],
                excludeTypes: [
                    "minecraft:skeleton_horse",
                    "minecraft:wither",
                    "minecraft:wither_skeleton",
                    "minecraft:zoglin",
                    "minecraft:zombie_horse",
                    "minecraft:zombie_pigman",
                    "minecraft:zombie_villager",
                    "minecraft:zombie_villager_v2",
                ],
            });


            let removedCount = 0;

            
            for (const entity of nearbyMobs) {
                if (!entity.isValid) continue;

                const hasName = !!entity.nameTag;

                const equipComp = entity.getComponent("minecraft:equippable");
                const hasEquipment = equipComp && [
                    "mainhand", "offhand", "head", "chest", "legs", "feet"
                ].some(slot => {
                    try {
                        const item = equipComp.getEquipment(slot);
                        return item && item.typeId !== "minecraft:air";
                    } catch {
                        return false;
                    }
                });

                system.runTimeout(() => {
                    
                    if (!hasName && !hasEquipment) {

                        
                        if (timeOfDay > 14000 && timeOfDay < 22500 && playerDimension.id === "overworld" && Math.random() < 0.2) {
                            const newType = hostilePool[Math.floor(Math.random() * hostilePool.length)];
                            try {
                                const spawned = playerDimension.spawnEntity(newType, entity.location);

                                if (spawned) {
                                    spawned.addEffect("invisibility", 4, {
                                        amplifier: 0,
                                        showParticles: false
                                    });
                                }
                            } catch (e) {
                                console.log(`Failed to spawn ${newType}: ${e}`);
                            }
                        }

                        
                        try {
                            entity.remove();
                            removedCount++;
                        } catch (e) {
                            console.log(`Failed to remove ${entity.typeId}: ${e}`);
                        }
                    }
                }, 1)
                yield;
            }

            if (removedCount > 0) {
                
            }
        }
    };

    
    function WeatherChange(player, ExpectedTicksPassed) {
        if (ExpectedTicksPassed >= 18000) {

            
            const totalWeight = weatherOptions.reduce((sum, w) => sum + w.weight, 0);
            let rand = Math.random() * totalWeight;

            let selectedWeather = "Clear"; 
            for (const option of weatherOptions) {
                rand -= option.weight;
                if (rand <= 0) {
                    selectedWeather = option.condition;
                    break;
                }
            }

            try {
                player.dimension.setWeather(selectedWeather);
                
            } catch (e) {
                console.log(`Failed to change weather: ${e}`);
            }

        }
    };


    
    function randomTickChanger(ExpectedTicksPassed) {
        system.runTimeout(() => {

            const
                currentTickSpeed = world.gameRules.randomTickSpeed,
                targetTickSpeed = Math.floor(Math.min(ExpectedTicksPassed, Math.round(50 / fo.performanceModifier))), 
                ticksToRun = Math.floor(Math.min(Math.round(ExpectedTicksPassed / targetTickSpeed), 600)), 
                ticksToRunStillness = Math.floor(Math.min(Math.round(ExpectedTicksPassed / 20 / targetTickSpeed), 600)); 

            if (!stillnessEventFlag && ExpectedTicksPassed > 6000) {
                world.setDynamicProperty("currentTickSpeed", true)
                world.gameRules.randomTickSpeed = targetTickSpeed;

                system.runTimeout(() => {
                    
                    world.gameRules.randomTickSpeed = currentTickSpeed;

                    world.setDynamicProperty("currentTickSpeed", false)
                }, ticksToRun)
            } else if (ExpectedTicksPassed > 6000) { 
                world.setDynamicProperty("currentTickSpeed", true)
                world.gameRules.randomTickSpeed = targetTickSpeed
                world.gameRules.doFireTick = false; 

                system.runTimeout(() => {
                    
                    world.gameRules.randomTickSpeed = currentTickSpeed;
                    world.gameRules.doFireTick = true

                    world.setDynamicProperty("currentTickSpeed", false)

                }, ticksToRunStillness);
            }

        }, 4)
    };

    
    
    function stopSound(player, ExpectedTicksPassed, forebodingScore) {
        
        if (ExpectedTicksPassed > 4800) {

            player.dimension.runCommand(`stopsound ${player.name}`)
            player.stopMusic();

            system.runTimeout(() => {
                if (forebodingScore > forebodingScoreCheck3) player.playMusic("forefeelM", { volume: 0.01, loop: true });
                if (forebodingScore < forebodingScoreCheck7) player.playMusic("phurpa", { volume: 0.01, loop: true });
                
            }, 1)

            
        }

    };

    
    
    function blockExplode(player) {
        const dimension = player.dimension;
        const explosionPower = 4;
        const searchRadius = 60;

        
        const primedTNTs = dimension.getEntities({
            location: player.location,
            maxDistance: searchRadius,
            type: "minecraft:tnt"
        });

        const tntMinecarts = dimension.getEntities({
            location: player.location,
            maxDistance: searchRadius,
            type: "minecraft:tnt_minecart",
        });

        
        const allExplosives = [...primedTNTs, ...tntMinecarts];

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

        for (const tnt of allExplosives) {
            if (!tnt?.isValid) continue;

            
            const ignitedComp = tnt.getComponent("minecraft:is_ignited");
            if (tnt.typeId === "minecraft:tnt_minecart" && !ignitedComp) continue;


            const pos = tnt.location;

            try {
                tnt.remove();

                dimension.createExplosion(pos, explosionPower, {
                    breaksBlocks: true,
                    causesFire: false,
                    allowUnderwater: false
                });

                

            } catch (e) {
                console.warn(`Failed to explode TNT at ${JSON.stringify(pos)}: ${e}`);
            }
        }

        
        system.runTimeout(() => blockExplode(player), 4);
    }

    
    function* CreepersExplosion(player) {
        const dimension = player.dimension;
        const playerLoc = player.location;

        const creepers = dimension.getEntities({
            location: playerLoc,
            maxDistance: 6,
            type: "minecraft:creeper"
        });

        for (const creeper of creepers) {
            if (!creeper?.isValid) continue;

            const
                creeperLoc = creeper.location,
                dx = playerLoc.x - creeperLoc.x,
                dy = (playerLoc.y + 1.5) - creeperLoc.y, 
                dz = playerLoc.z - creeperLoc.z,
                mag = Math.sqrt(dx * dx + dy * dy + dz * dz),

                direction = {
                    x: dx / mag,
                    y: dy / mag,
                    z: dz / mag
                };

            
            const blockBetween = dimension.getBlockFromRay(creeperLoc, direction, {
                maxDistance: 6,
                includePassableBlocks: false
            });

            const hasLOS = !blockBetween || blockBetween.isAir;
            if (!hasLOS) continue;

            if (!hasWalkablePath(creeper, player)) {
                continue; 
            }

            

            let explodePos = {
                x: playerLoc.x - (dx / mag) * 3,
                y: playerLoc.y - (dy / mag) * 3,
                z: playerLoc.z - (dz / mag) * 3
            };

            
            explodePos.x = Math.max(Math.min(explodePos.x, creeperLoc.x), playerLoc.x);
            explodePos.y = Math.max(Math.min(explodePos.y, creeperLoc.y), playerLoc.y);
            explodePos.z = Math.max(Math.min(explodePos.z, creeperLoc.z), playerLoc.z);

            const
                isCharged = creeper.getComponent("minecraft:is_charged"),
                explosionPower = isCharged ? 6 : 3;

            
            try {
                dimension.createExplosion(explodePos, explosionPower, {
                    breaksBlocks: true,
                    causesFire: false,
                    allowUnderwater: false,
                    source: creeper
                });
                creeper.remove();

                
            } catch (e) {
                console.log(`Failed to explode simulated creeper: ${e}`);
            }
            yield;
        }
    }

    
    function hasWalkablePath(creeper, player) {
        const dim = creeper.dimension;
        const from = creeper.location;
        const to = player.location;

        const dx = to.x - from.x;
        const dz = to.z - from.z;
        const distanceXZ = Math.sqrt(dx * dx + dz * dz);

        
        if (distanceXZ > 6) return false;

        
        const steps = Math.min(3, Math.floor(distanceXZ));

        for (let i = 1; i <= steps; i++) {
            const x = Math.floor(from.x + (dx / distanceXZ) * i);
            const z = Math.floor(from.z + (dz / distanceXZ) * i);

            
            for (let dy = -4; dy <= 1; dy++) {
                const y = Math.floor(from.y + dy);
                const foot = dim.getBlock({ x, y, z });
                const below = dim.getBlock({ x, y: y - 1, z });
                const head = dim.getBlock({ x, y: y + 1, z });

                const isBadSurface = below && noGoBlocks.some(bad => below.typeId?.includes(bad));

                const isWalkable =
                    below && !below.isAir && !below.isLiquid && !isBadSurface &&
                    foot?.isAir &&
                    head?.isAir;

                if (isWalkable) return true;
            }
        }

        return false;
    }


    
    function handleFallingBlocks(player, ExpectedTicksPassed) {
        const dimension = player.dimension,

            fallingBlocks = dimension.getEntities({
                location: player.location,
                maxDistance: 60,
                type: "minecraft:falling_block"
            });

        
        const columnOffsets = new Map();


        for (const fallingBlock of fallingBlocks) {
            const
                startPos = fallingBlock.location,
                maxFallDistance = Math.max(Math.min(160, (startPos.y - dimension.heightRange.min)), 0),
                fallDistanceEstimate = getFallDistance(ExpectedTicksPassed / 2, maxFallDistance), 
                rayOptions = {
                    maxDistance: fallDistanceEstimate,
                    includeLiquidBlocks: false,
                    includePassableBlocks: true
                },

                hitBlock = dimension.getBlockBelow(startPos, rayOptions);

            let landingY;
            if (!hitBlock) {
                
                landingY = Math.max(startPos.y - fallDistanceEstimate + 1, dimension.heightRange.min + 1);
            } else {
                landingY = hitBlock.location.y + 1;
            }

            
            const key = `${Math.floor(startPos.x)}:${Math.floor(startPos.z)}`;
            const yOffset = columnOffsets.get(key) ?? 0;
            columnOffsets.set(key, yOffset + 1);

            const landingPos = {
                x: startPos.x,
                y: landingY + 2 + yOffset, 
                z: startPos.z
            };

            try {
                fallingBlock.teleport(landingPos, {
                    dimension: dimension,
                    rotation: fallingBlock.getRotation()
                });
                
            } catch (e) {
                console.log(`Failed to teleport falling block: ${e}`);
            }
        }
    };


    
    function otherFallingEntities(player, ExpectedTicksPassed) {
        const dimension = player.dimension,

            fallingEntities = dimension.getEntities({
                location: player.location,
                maxDistance: 60,
                families: [
                    "minecraft:inanimate",
                ]
            }),

            itemEntities = dimension.getEntities({
                location: player.location,
                maxDistance: 60,
                type: "minecraft:item"

            });

        
        const allOtherEntities = [...fallingEntities, ...itemEntities];

        for (const fallingEntity of allOtherEntities) {
            if (!fallingEntity.isFalling || !fallingEntity.isValid) continue;

            const
                startPos = fallingEntity.location,
                maxFallDistance = Math.max(Math.min(160, (startPos.y - dimension.heightRange.min)), 0),
                fallDistanceEstimate = getFallDistance(ExpectedTicksPassed / 2, maxFallDistance),
                rayOptions = {
                    maxDistance: fallDistanceEstimate,
                    includeLiquidBlocks: false,
                    includePassableBlocks: false,
                },

                hitBlock = dimension.getBlockBelow(startPos, rayOptions);

            let landingY;
            if (!hitBlock) {
                
                landingY = Math.max(startPos.y - fallDistanceEstimate + 1, dimension.heightRange.min + 1);
            } else {
                landingY = hitBlock.location.y + 1;
            }


            const landingPos = {
                x: startPos.x,
                y: landingY, 
                z: startPos.z
            };

            try {
                fallingEntity.teleport(landingPos, {
                    dimension: dimension,
                    rotation: fallingEntity.getRotation()
                });
                
            } catch (e) {
                console.log(`Failed to teleport falling entity: ${e}`);
            }
        }

    };


    
    function projectilesSim(player, ExpectedTicksPassed) {
        if (ExpectedTicksPassed < 100) return;
        const dimension = player.dimension;
        const entities = dimension.getEntities({
            location: player.location,
            maxDistance: 45,
        });

        
        const entityTypes = projectilesA.map(e => e.id);
        const nearbyProjectiles = entities.filter(e => entityTypes.includes(e.typeId));

        const projectileMap = new Map(
            projectilesA.map(p => [p.id, p.despawnTimer])
        );

        for (const entity of nearbyProjectiles) {
            if (!entity) continue;

            const despawnTime = projectileMap.get(entity.typeId);

            if (despawnTime && ExpectedTicksPassed >= despawnTime) {
                try {
                    entity.remove();
                    
                } catch (e) {
                    console.log(`Failed to remove projectile ${entity.typeId}: ${e}`);
                }
            }
        }

        
        const entityTypes2 = projectilesB.map(e => e.id);
        const nearbyProjectiles2 = entities.filter(e => entityTypes2.includes(e.typeId));

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

        const rayOptions = {
            maxDistance: 45,
            includeLiquidBlocks: true,
            includePassableBlocks: true
        };

        
        for (const entity of nearbyProjectiles2) {
            if (!entity || !entity.isValid) continue;

            const typeId = entity.typeId;

            const newPos = { ...entity.location };
            const dir = entity.getVelocity();
            if (!dir) {
                
                continue;
            }

            
            let
                blockHit,
                landingPos;

            if (entity.typeId === "minecraft:ender_pearl") {
                const
                    acceleration = 0.03,
                    dragH = 0.99,
                    dragV = 0.99;

                landingPos = thrownPhysics(newPos, dir, ExpectedTicksPassed, entity, acceleration, dragH, dragV);

            } else {
                blockHit = player.dimension.getBlockFromRay(newPos, dir, rayOptions);

                if (!blockHit) {
                    
                    entity.remove() 
                    continue;
                }

                landingPos = {
                    x: blockHit.location.x,
                    y: blockHit.location.y,
                    z: blockHit.location.z
                };

            }

            


            
            const effectHandler = projectileEffectHandlers[typeId];
            if (effectHandler) {
                try {
                    effectHandler(landingPos, player);
                    entity.remove(); 
                    
                } catch (e) {
                    console.log(`Failed to apply effect for ${typeId}: ${e}`);
                }
            } else {
                
            }
        }


    };


    
    function eyeOfEnderLogic(player, ExpectedTicksPassed) {
        const dimension = player.dimension;
        const eyeOfEnders = dimension.getEntities({
            location: player.location,
            maxDistance: 45,
            type: "minecraft:eye_of_ender_signal"
        });

        for (const eyeOfEnder of eyeOfEnders) {
            
            if (ExpectedTicksPassed > 6240) {
                eyeOfEnder.remove();
                continue;
            }
            
            
            if (Math.random() > 0.05) {
                dimension.spawnItem(new ItemStack("minecraft:ender_eye", 1), eyeOfEnder.location);
            }
            eyeOfEnder.remove();

        }

    };


    
    function* workingFurnaces(player, ExpectedTicksPassed) {
        const playerPos = player.location;
        const playerDim = player.dimension.id;

        const allFurnaceLocations = JSON.parse(world.getDynamicProperty(FURNACE_LIST_PROPERTY) || "[]");

        const nearbyFurnaces = allFurnaceLocations.filter(loc => {
            return loc.dimensionId === playerDim &&
                getDistance(loc, playerPos) <= 55;
        });

        for (const furnaceLoc of nearbyFurnaces) {
            const block = player.dimension.getBlock({
                x: furnaceLoc.x,
                y: furnaceLoc.y,
                z: furnaceLoc.z
            });

            const furnaceMeta = furnacesTable.find(f => f.id === block.typeId);
            if (!furnaceMeta) {

                removeFurnaceFromList(furnaceLoc, allFurnaceLocations);
                continue;
            };

            const container = block.getComponent("minecraft:inventory");
            if (!container) continue;

            const slots = container.container;
            const fuelSlot = slots.getSlot(1); 
            const inputSlot = slots.getSlot(0); 
            const outputSlot = slots.getSlot(2); 

            if (!inputSlot || !inputSlot.hasItem() || !fuelSlot || !fuelSlot.hasItem()) continue;

            
            const recipe = furnaceRecipes.find(r =>
                r.ingredient === inputSlot?.getItem().typeId &&
                (r.recipe === furnaceMeta.process || furnaceMeta.process === "all")
            );
            if (!recipe) continue;

            
            const fuelItemId = fuelSlot?.getItem().typeId;
            const fuel = furnaceFuel.find(f => fuelItemId.includes(f.id));
            
            if (!fuel) continue;

            
            
            
            
            

            
            const maxOps = Math.floor(ExpectedTicksPassed / furnaceMeta.speed);
            const itemsPerFuel = fuel.operationTime / (furnaceMeta.speed * furnaceMeta.fuelConsumption);
            const maxOpsFuel = Math.floor(maxOps / itemsPerFuel) * itemsPerFuel; 
            const actualOps = Math.min(maxOpsFuel, inputSlot.amount);

            if (actualOps <= 0 || !actualOps) continue;

            let fuelOpsCap;

            if (fuelSlot && fuelSlot.hasItem()) {
                const totalBurnTimeAvailable = fuelSlot.amount * fuel.operationTime;
                fuelOpsCap = Math.floor(totalBurnTimeAvailable / (furnaceMeta.speed * furnaceMeta.fuelConsumption)); 

            } else {
                
                
                continue;
            }

            let itemOutputCap;

            
            if (!outputSlot || !outputSlot.hasItem()) {
                itemOutputCap = new ItemStack(recipe.product).maxAmount;

            } else {
                const existingItem = outputSlot.getItem();

                if (existingItem?.typeId === recipe.product) {
                    const maxStackSize = new ItemStack(recipe.product).maxAmount;
                    itemOutputCap = maxStackSize - outputSlot.amount;
                } else {
                    
                    
                    
                    continue;
                }
            }

            
            
            const finalOps = Math.min(actualOps, fuelOpsCap, itemOutputCap)



            
            if (inputSlot.amount === finalOps) {
                slots.setItem(0, undefined); 
            } else {
                inputSlot.amount -= finalOps;
            }

            const fuelUsed = Math.ceil((finalOps * furnaceMeta.speed * furnaceMeta.fuelConsumption) / fuel.operationTime);

            if (fuelSlot.amount === fuelUsed) {
                slots.setItem(1, undefined); 
            } else {
                fuelSlot.amount -= fuelUsed;
            }

            
            if (!outputSlot || !outputSlot.hasItem()) {
                slots.setItem(2, new ItemStack(recipe.product, finalOps));
            } else {
                const existingItem = outputSlot.getItem();

                if (existingItem?.typeId === recipe.product) {
                    const maxStack = new ItemStack(recipe.product).maxAmount;
                    outputSlot.amount = Math.min(outputSlot.amount + finalOps, maxStack);
                } else {
                    
                }
            }

            
            yield;
        }
    };



    

    function delayedLogs(player,) {

        world.sendMessage({
            translate: "Fo.PhantomPlayer01",
            with: [`Pilot1782`]
        });

        if (Math.random() < 0.2) deadMessages(player);

        world.sendMessage({
            translate: "Fo.PhantomPlayer03",
            with: [`Pilot1782`]
        });

        if (Math.random() < 0.4) delayedLogs(player);

    }

    function deadMessages(player) {

        const messages = [
            { translate: "Fo.PhantomPlayer04a", with: ["Pilot1782"] },
            { translate: "Fo.PhantomPlayer04b", with: ["Pilot1782"] },
            { translate: "Fo.PhantomPlayer04c", with: ["Pilot1782", player.name] },
            { translate: "Fo.PhantomPlayer04d", with: ["Pilot1782"] },
            { translate: "Fo.PhantomPlayer04e", with: ["Pilot1782"] }
        ];

        
        const msg = messages[Math.floor(Math.random() * messages.length)];

        world.sendMessage(msg);

        if (Math.random() < 0.2) deadMessages(player);
    }

    function P82ContinuedSession() {

        if (Math.random() < 0.1) deadMessages(player);

        world.scoreboard.getObjective("Online").addScore("Pilot1782", 0) 

        const randomLogOffDelay = Math.max(Math.floor(Math.random() * 8401), 3002); 

        if (Math.random() < 0.1) { 
            const deathMessageDelay = Math.max(Math.floor(Math.random() * (randomLogOffDelay - 1200)), 123); 

            system.runTimeout(() => {
                const messages = [
                    { translate: "Fo.PhantomPlayer04a", with: ["Pilot1782"] },
                    { translate: "Fo.PhantomPlayer04b", with: ["Pilot1782"] },
                    { translate: "Fo.PhantomPlayer04d", with: ["Pilot1782"] },
                    { translate: "Fo.PhantomPlayer04e", with: ["Pilot1782"] }
                ];

                
                const msg = messages[Math.floor(Math.random() * messages.length)];

                world.sendMessage(msg);

            }, deathMessageDelay)
        }


        system.runTimeout(() => {
            world.scoreboard.getObjective("Online").removeParticipant("Pilot1782"); 
            world.sendMessage({
                translate: "Fo.PhantomPlayer03",
                with: [`Pilot1782`]
            });
        }, randomLogOffDelay)
    }

    
    function P82forebearerSafeGuard(ExpectedTicksPassed) {
        if (ExpectedTicksPassed < 1800) return; 

        const overworld = fo.overworld;

        const P82Stalker = overworld.getEntities({
            type: "fo:forebearer",
            name: "Pilot1782"
        });

        if (P82Stalker.length !== 0) {
            P82Stalker[0].runCommand(`/spreadplayers ${P82Stalker[0].location.x} ${P82Stalker[0].location.z} 1 60 @s 50`);
        }
    }


    function P82EventsLogic(player, forebodingScore, ExpectedTicksPassed) {
        if (forebodingScore < forebodingScoreCheck3 || forebodingScore >= forebodingScoreCheck5 || ExpectedTicksPassed < P82MinElapsedTime) return;

        let
            saved = world.getDynamicProperty("P82Data"),
            P82Data = saved ? JSON.parse(saved) : false;

        if (!P82Data.isPresent) return;
        if (Math.random() > (P82Chance * P82Data.intensity)) return;

        const players = world.getAllPlayers();
        if (players.length > 1) return;

        const isOnline = world.scoreboard.getObjective("Online").hasParticipant("Pilot1782");

        system.runTimeout(() => {
            if (Math.random() <= 0.7 || isOnline) {
                if (isOnline) {
                    world.sendMessage({
                        translate: "Fo.PhantomPlayer03",
                        with: [`Pilot1782`]
                    });
                };

                delayedLogs(player);

                if (isOnline) {
                    world.sendMessage({
                        translate: "Fo.PhantomPlayer01",
                        with: [`Pilot1782`]
                    });
                };
            } else P82ContinuedSession();
        }, 1)

    };

    function P82giveBook(player, forebodingScore, ExpectedTicksPassed) {
        if (forebodingScore < forebodingScoreCheck5 || ExpectedTicksPassed < P82MinElapsedTime) return;

        let
            saved = world.getDynamicProperty("P82Data"),
            P82Data = saved ? JSON.parse(saved) : false;

        if (!P82Data.isPresent || !P82Data.bookActive || P82Data.bookGiven) return;

        
        const chestLocations = JSON.parse(world.getDynamicProperty("chest_locations") || "[]");
        if (chestLocations.length === 0) return;

        const
            playerPos = player.location,
            dimension = player.dimension,
            chestMaxDistance = 32;

        const nearbyChests = chestLocations.filter(chestPos => {
            if (chestPos.dimension !== dimension.id) return false;

            const distance = Math.sqrt(
                Math.pow(chestPos.x - playerPos.x, 2) +
                Math.pow(chestPos.y - playerPos.y, 2) +
                Math.pow(chestPos.z - playerPos.z, 2)
            );
            return distance <= chestMaxDistance;
        });

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

        
        const
            randomChest = nearbyChests[Math.floor(Math.random() * nearbyChests.length)],
            chestBlock = dimension.getBlock(randomChest);


        if (!chestBlock || chestBlock.typeId !== "minecraft:chest") {
            
            return;
        }

        const isOnline = world.scoreboard.getObjective("Online").hasParticipant("Pilot1782");
        if (!isOnline) delayedLogs(player);

        populateChest(chestBlock, dimension)
        P82Data.bookGiven = true;
        saveProgress(P82Data)
    };

    
    function populateChest(chest, dimension) { 
        const container = chest.getComponent("inventory").container;
        const lootTable = "foP82";

        
        for (let slot = 0; slot < container.size; slot++) {
            const item = container.getItem(slot);
            if (!item) {
                
                dimension.runCommand(`loot replace block ${chest.location.x} ${chest.location.y} ${chest.location.z} slot.container ${slot} loot ${lootTable}`)
                
                return;
            }
        }
    }

    function saveProgress(P82Data) {
        world.setDynamicProperty("P82Data", JSON.stringify(P82Data));
    }


}