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 != "gs_ce:haunted_chest") return;
    if (!chest.getProperty('gs_ce:open') && (!itemStack || itemStack.typeId != "gs_ce:key")) event.cancel = true;
    else
    system.run(()=>{
        world.playSound("haunted_chest_open", chest.location);
        if (!chest.getProperty('gs_ce:open')) {
            player.runCommandAsync('/clear @s gs_ce:key 0 1')
            chest.setProperty('gs_ce:open', true)
        }
    })
});

world.afterEvents.entitySpawn.subscribe((event) => {
    const entity = event.entity;
    if (entity.typeId === 'gs_ce:haunted_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;
    const items = [
        { id: 'minecraft:emerald', count: getRandomInt(1, 16) }
    ];

    // Add enchanted books
    const numBooks = 1 + (Math.random() < 0.4 ? 1 : 0) + (Math.random() < 0.2 ? 1 : 0);
    for (let i = 0; i < numBooks; i++) {
        
        
        items.push({ 
            id: 'minecraft:enchanted_book', 
            count: 1
        });
    }

    const resinEquipment = [
        // Tools
        { id: 'gs_ce:resin_sword', probability: 0.3 },
        { id: 'gs_ce:resin_pickaxe', probability: 0.3 },
        { id: 'gs_ce:resin_axe', probability: 0.3 },
        { id: 'gs_ce:resin_shovel', probability: 0.3 },
        { id: 'gs_ce:resin_hoe', probability: 0.3 },
        // Armor
        { id: 'gs_ce:resin_helmet', probability: 0.25 },
        { id: 'gs_ce:resin_chestplate', probability: 0.25 },
        { id: 'gs_ce:resin_leggings', probability: 0.25 },
        { id: 'gs_ce:resin_boots', probability: 0.25 }
    ];

    resinEquipment.forEach(equipment => {
        if (Math.random() < equipment.probability) {
            items.push({ id: equipment.id, count: 1 });
        }
    });

    if (Math.random() < 0.3) {
        items.push({ id: 'minecraft:emerald', count: getRandomInt(5, 32) });
    }

    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.id.includes('resin_')) {
            const durabilityComp = itemStack.getComponent('durability');
            if (durabilityComp) {
                durabilityComp.damage += getRandomInt(1, 100);
            }
        }

        if (item.id === 'minecraft:enchanted_book') {
            try {
                const enchantment = getRandomItem([
                'aqua_affinity',
                'bane_of_arthropods',
                'blast_protection',
                'depth_strider',
                'efficiency',
                'feather_falling',
                'fire_aspect',
                'fire_protection',
                'flame',
                'fortune',
                'frost_walker',
                'infinity',
                'knockback',
                'looting',
                'luck_of_the_sea',
                'lure',
                'mending',
                'power',
                'protection',
                'punch',
                'respiration',
                'sharpness',
                'silk_touch',
                'smite',
                'soul_speed',
                'swift_sneak',
                'thorns',
                'unbreaking'
            ]);
                const enchantable = itemStack.getComponent('enchantable');
                if (enchantable) {
                    enchantable.addEnchantment({
                        type: new EnchantmentType(enchantment),
                        level: 1
                    });
                }
            } catch (e) {
            }
        }

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