import { world, system, ItemStack, EnchantmentType } from '@minecraft/server';

world.beforeEvents.playerInteractWithEntity.subscribe((event) => {
    const itemStack = event?.itemStack;
    const chest = event.target;
    const player = event.player
    
    if (chest.typeId != "msft:wooden_chest") return;
    if (!chest.getProperty('msft:open') && (!itemStack || itemStack.typeId != "msft:iron_key")) event.cancel = true;
    else
    system.run(()=>{
        if (!chest.getProperty('msft:open')) {
            player.runCommandAsync('/clear @s msft:iron_key 0 1');
            player.playSound("msft:ambient:chest-opening");
            chest.setProperty('msft:open', true);

            system.runTimeout(() => {
                chest.setProperty('msft:despawn', true);
            }, 1200);
            system.runTimeout(() => {
                const inventory = chest.getComponent("minecraft:inventory").container;

                for (let i = 0; i < inventory.size; i++) {
                    const item = inventory.getItem(i);
                    if (item) {
                        chest.dimension.spawnItem(item, chest.location);
                        inventory.setItem(i, undefined); 
                    }
                }
                chest.remove();
            }, 1220);
        }
    })
});

world.afterEvents.entitySpawn.subscribe((event) => {
    const entity = event.entity;
    if (entity.typeId === 'msft:wooden_chest') {
        fillAirdropInventory(entity);
    }
});

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getRandomItem(items) {
    return items[getRandomInt(0, items.length - 1)];
}

function fillAirdropInventory(entity) {
    const inventory = entity.getComponent('minecraft:inventory').container;
    entity.nameTag = "§8§lWooden Chest";

    const potentialItems = [
        // Materiali Comuni
        { id: 'minecraft:emerald', count: getRandomInt(1, 3), probability: 0.17 },
        { id: 'minecraft:iron_ingot', count: getRandomInt(1, 5), probability: 0.35 },
        { id: 'minecraft:copper_ingot', count: getRandomInt(1, 5), probability: 0.35 },
        { id: 'minecraft:experience_bottle', count: getRandomInt(1, 4), probability: 0.25 },

        // Materiali Rari
        { id: 'minecraft:diamond', count: 1, probability: 0.025 },
        { id: 'minecraft:gold_ingot', count: getRandomInt(1, 4), probability: 0.17 },

        // Pozioni & Gemme
        { id: 'msft:green_gemstone', count: 1, probability: 0.14 },
        { id: 'msft:small_stamina_potion', count: 1, probability: 0.15 },

        // Armi Rare
        { id: 'msft:iron_glaives', count: 1, probability: 0.12 },
        { id: 'msft:iron_battleaxe', count: 1, probability: 0.12 },
        { id: 'msft:iron_hammer', count: 1, probability: 0.12 },

        // Strumenti & Utility
        { id: 'minecraft:chainmail_chestplate', count: 1, probability: 0.16 },

        // Codex
        { id: 'msft:codex_book_heavy', count: 1, probability: 0.15 },
        { id: 'msft:codex_book_long', count: 1, probability: 0.25 },
        { id: 'msft:codex_book_armor', count: 1, probability: 0.25 },
        { id: 'msft:codex_book_medium', count: 1, probability: 0.35 },
    ];

    const items = potentialItems.filter(item => Math.random() < item.probability);

    // Libri Incantati specifici con probabilità
    if (Math.random() < 0.03) {
        items.push(createEnchantedBook('sharpness', 2));
    }
    if (Math.random() < 0.09) {
        items.push(createEnchantedBook('unbreaking', 1));
    }
    if (Math.random() < 0.07) {
        items.push(createEnchantedBook('bane_of_arthropods', 3));
    }

    const validItems = items.filter(item => item.count > 0);

    while (validItems.length > 0) {
        const item = getRandomItem(validItems);
        const itemStack = new ItemStack(item.id, item.count);

        // Enchanted books già configurati
        if (item.enchantment) {
            const enchantable = itemStack.getComponent('enchantable');
            if (enchantable) {
                enchantable.addEnchantment({
                    type: new EnchantmentType(item.enchantment.id),
                    level: item.enchantment.level
                });
            }
        }

        let placed = false;
        while (!placed) {
            const slot = getRandomInt(0, inventory.size - 1);
            if (!inventory.getItem(slot)) {
                inventory.setItem(slot, itemStack);
                placed = true;
            }
        }
        validItems.splice(validItems.indexOf(item), 1);
    }
}

function createEnchantedBook(id, level) {
    return {
        id: 'minecraft:enchanted_book',
        count: 1,
        probability: 1, // è già condizionata esternamente
        enchantment: {
            id,
            level
        }
    };
}
