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


export function initChest() {

    
    const chance = 1 / 45; 
    const forebodingCheck = fo.scoreChapter4; 
    const interval = 4800; 

    let eventflag = false; 

    
    const CHEST_LIST_PROPERTY = "chest_locations";

    
    const chestLoot = [
        "minecraft:dandelion",
        "minecraft:lily_of_the_valley",
        "minecraft:carved_pumpkin",
        "minecraft:rabbit_foot",
        "minecraft:suspicious_stew",
        "minecraft:mushroom_stew",
        "minecraft:rabbit_stew",
        "minecraft:clock",
        "minecraft:dead_fire_coral",
        "minecraft:sugar",
        "minecraft:goat_horn",
        "minecraft:ominous_bottle",
        "minecraft:charcoal",
        "minecraft:pumpkin_pie",
        "minecraft:name_tag",
        "minecraft:music_disc_mellohi"
    ];


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

    
    function isPlayerLookingAtChest(player, chestPos) {
        if (!player || !chestPos) {
            
            return false;
        }

        const playerPos = player.location;
        if (!playerPos) {
            
            return false;
        }

        const playerViewDir = player.getViewDirection();
        if (!playerViewDir) {
            
            return false;
        }

        
        const chestDir = {
            x: chestPos.x - playerPos.x,
            y: chestPos.y - playerPos.y,
            z: chestPos.z - playerPos.z
        };

        
        const chestDirLength = Math.sqrt(chestDir.x ** 2 + chestDir.y ** 2 + chestDir.z ** 2);
        const normalizedChestDir = {
            x: chestDir.x / chestDirLength,
            y: chestDir.y / chestDirLength,
            z: chestDir.z / chestDirLength
        };

        
        const dotProduct = playerViewDir.x * normalizedChestDir.x + playerViewDir.y * normalizedChestDir.y + playerViewDir.z * normalizedChestDir.z;

        
        const angle = Math.acos(dotProduct);

        
        const angleThreshold = (55 * Math.PI) / 180; 

        
        return angle <= angleThreshold;
    }

    
    function placeRandomItemInChest(block) {
        if (!block) {
            
            return;
        }

        
        const inventory = block.getComponent("inventory");
        if (!inventory) {
            
            return;
        }

        
        const randomItem = chestLoot[Math.floor(Math.random() * chestLoot.length)];
        

        
        const itemStack = new ItemStack(randomItem, 1); 

        
        const container = inventory.container;
        if (!container) {
            
            return;
        }

        
        for (let slot = 0; slot < container.size; slot++) {
            const item = container.getItem(slot);
            if (!item) {
                
                container.setItem(slot, itemStack);
                
                return;
            }
        }

        
        
    }

    
    function openRandomChest() {
        const chestLocations = JSON.parse(world.getDynamicProperty(CHEST_LIST_PROPERTY) || "[]");
        

        if (!Array.isArray(chestLocations)) {
            
            return;
        }

        if (chestLocations.length === 0) {
            
            return;
        }

        const players = world.getPlayers();
        

        if (!Array.isArray(players)) {
            
            return;
        }


        const validChests = chestLocations.filter(chestPos => {
            if (!chestPos || typeof chestPos.x === "undefined" || typeof chestPos.y === "undefined" || typeof chestPos.z === "undefined" || !chestPos.dimension) {
                
                return false;
            }

            

            
            return players.every(player => {
                const playerPos = player.location;
                if (!playerPos) {
                    
                    return false;
                }

                
                if (player.dimension.id !== chestPos.dimension) {
                    return false;
                }

                const distance = getDistance(playerPos, chestPos);
                
                const isLooking = isPlayerLookingAtChest(player, chestPos);

                

                return (distance >= 6 && distance <= 32) && !isLooking;
            });
        });

        if (validChests.length === 0) {
            
            return;
        }

        
        const randomChest = validChests[Math.floor(Math.random() * validChests.length)];
        const chestDimension = world.getDimension(randomChest.dimension);
        const block = chestDimension.getBlock(randomChest);

        if (!block || block.typeId !== "minecraft:chest") {
            
            const updatedLocations = chestLocations.filter(loc =>
                !(loc.x === randomChest.x &&
                    loc.y === randomChest.y &&
                    loc.z === randomChest.z &&
                    loc.dimension === randomChest.dimension)
            );
            world.setDynamicProperty(CHEST_LIST_PROPERTY, JSON.stringify(updatedLocations));
            return;
        }

        
        chestDimension.playSound("random.chestopen", block.location, { volume: 2 });
        

        
        placeRandomItemInChest(block);

        
        system.runTimeout(() => {
            chestDimension.playSound("random.chestclosed", block.location, { volume: 2 });
            
        }, 20); 

        eventflag = false 
    }

    
    system.runInterval(() => {
        const probabilityModifier = fo.netProbabilityModifier;

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

    }, interval);


    
    system.runInterval(() => {

        if (eventflag) {
            openRandomChest();
        }

    }, 1800);

}