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

    const potentialItems = [
        // Materiali Comuni
        { id: 'minecraft:iron_ingot', count: getRandomInt(2, 5), probability: 0.50 },
        { id: 'minecraft:golden_carrot', count: getRandomInt(2, 5), probability: 0.52 },
        { id: 'minecraft:emerald', count: getRandomInt(1, 3), probability: 0.49 },
        { id: 'minecraft:gold_ingot', count: getRandomInt(2, 5), probability: 0.47 },
        { id: 'minecraft:experience_bottle', count: getRandomInt(1, 4), probability: 0.48 },
        { id: 'minecraft:chainmail_chestplate', count: 1, probability: 0.46 },
        { id: 'minecraft:iron_chestplate', count: 1, probability: 0.055 }, // Singolo pezzo di armatura in ferro

        // Materiali Rari
        { id: 'minecraft:diamond', count: getRandomInt(1, 2), probability: 0.075 },
        { id: 'minecraft:emerald', count: getRandomInt(1, 3), probability: 0.67 },

        // Codex
        { id: 'msft:codex_book_heavy', count: 1, probability: 0.55 },
        { id: 'msft:codex_book_long', count: 1, probability: 0.55 },
        { id: 'msft:codex_book_armor', count: 1, probability: 0.55 },
        { id: 'msft:codex_book_medium', count: 1, probability: 0.50 },
        { id: 'msft:codex_book_echo', count: 1, probability: 0.55 },

        // Pozioni & Gemme
        { id: 'msft:small_stamina_potion', count: 1, probability: 0.48 },
        { id: 'msft:big_stamina_potion', count: 1, probability: 0.45 },
        { id: 'msft:green_gemstone', count: 1, probability: 0.47 },
        { id: 'msft:yellow_gemstone', count: 1, probability: 0.44 },
        { id: 'msft:red_gemstone', count: 1, probability: 0.055 },

        // Armi Rare
        { id: 'msft:netherite_glaives', count: 1, probability: 0.043 },
        { id: 'msft:netherite_battleaxe', count: 1, probability: 0.043 },
        { id: 'msft:netherite_katana', count: 1, probability: 0.043 },
        { id: 'msft:netherite_great_hammer', count: 1, probability: 0.043 },
    ];

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

    // Libri incantati con probabilità personalizzate
    if (Math.random() < 0.01) {
        items.push(createEnchantedBook('sharpness', 4));
    }
    if (Math.random() < 0.03) {
        items.push(createEnchantedBook('unbreaking', 1));
    }
    if (Math.random() < 0.005) {
        items.push(createEnchantedBook('mending', 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
        }
    };
}
