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:golden_chest") return;
    if (!chest.getProperty('msft:open') && (!itemStack || itemStack.typeId != "msft:golden_key")) event.cancel = true;
    else
    system.run(()=>{
        if (!chest.getProperty('msft:open')) {
            player.runCommandAsync('/clear @s msft:golden_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:golden_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 = "§6§lGolden Chest";

    const potentialItems = [
        // Materiali Comuni
        { id: 'minecraft:iron_ingot', count: getRandomInt(1, 5), probability: 0.30 },
        { id: 'minecraft:golden_carrot', count: getRandomInt(2, 5), probability: 0.35 },
        { id: 'minecraft:gold_ingot', count: getRandomInt(1, 4), probability: 0.35 },
        { id: 'minecraft:iron_nugget', count: getRandomInt(2, 5), probability: 0.32 },
        { id: 'minecraft:emerald', count: getRandomInt(1, 3), probability: 0.29 },
        { id: 'minecraft:experience_bottle', count: getRandomInt(1, 4), probability: 0.18 },

        // Materiali Rari
        { id: 'minecraft:diamond', count: 1, probability: 0.18 },
        { id: 'msft:empowered_repair_stone', count: 1, probability: 0.25 },

        // Pozioni & Gemme
        { id: 'msft:green_gemstone', count: 1, probability: 0.18 },
        { id: 'msft:yellow_gemstone', count: 1, probability: 0.22 },
        { id: 'msft:big_stamina_potion', count: 1, probability: 0.13 },

        // Armi Rare
        { id: 'msft:diamond_glaives', count: 1, probability: 0.015 },
        { id: 'msft:diamond_battleaxe', count: 1, probability: 0.015 },
        { id: 'msft:diamond_katana', count: 1, probability: 0.025 },

        // Utility
        { id: 'minecraft:name_tag', count: 1, probability: 0.035 },

        // 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.35 },
        { id: 'msft:codex_book_medium', count: 1, probability: 0.35 },
    ];

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

    // Libri incantati con probabilità personalizzate
    if (Math.random() < 0.02) {
        items.push(createEnchantedBook('sharpness', 3));
    }
    if (Math.random() < 0.03) {
        items.push(createEnchantedBook('unbreaking', 1));
    }
    if (Math.random() < 0.01) {
        items.push(createEnchantedBook('fire_aspect', 1));
    }

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

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

        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,
        enchantment: {
            id,
            level
        }
    };
}
