import { world, system, ItemStack, ItemTypes } from "@minecraft/server";

world.afterEvents.playerBreakBlock.subscribe(event => {
    const { block, player } = event;
    const blockPos = block.location;
    const dimension = player.dimension;

    // Delay to allow the block to drop its items and XP
    system.runTimeout(() => {
        // Retrieve dropped items near the broken block
        const droppedItems = dimension.getEntities({
            type: "minecraft:item",
            location: blockPos,
            maxDistance: 1.5
        });

        // Retrieve XP orbs near the broken block
        const xpOrbs = dimension.getEntities({
            type: "minecraft:xp_orb",
            location: blockPos,
            maxDistance: 1.5
        });

        // Process dropped items
        droppedItems.forEach(itemEntity => {
            const itemStack = itemEntity.getComponent("minecraft:item")?.itemStack;
            if (!itemStack) return;

            const container = player.getComponent("minecraft:inventory")?.container;
            if (container) {
                const remaining = container.addItem(itemStack);
                if (!remaining) {
                    itemEntity.remove(); // Picked up
                } else {
                    player.sendMessage("§cYour inventory is full!");
                    player.playSound("note.bass")
                }
            }
        });

        // Process XP orbs (teleport them to the player)
        xpOrbs.forEach(xpOrb => {
            xpOrb.teleport(player.location, { checkForBlocks: false });
        });

    }, 0.9); // Delay of 0.9 tick to ensure items and XP have dropped
});