// Import necessary modules from Minecraft server API
import { world, ItemStack, system } from '@minecraft/server';

//Credits to Kaiōga for the code

// Subscribe to the 'startup' event to register custom components
system.beforeEvents.startup.subscribe(eventData => {
    // Register a custom component named kai:on_player_destroy for slab destruction
    eventData.blockComponentRegistry.registerCustomComponent('rustic:on_player_destroy', {
        // Define behavior when a player destroys the slab
        onPlayerDestroy(e) {
            // Destructure event data for easier access
            const { player, dimension } = e;

            if (player.getGameMode() == "creative") return;

            // Extract destroyed block permutation from event data
            const { destroyedBlockPermutation: perm } = e;

            // Check if player and equipment are valid
            if (!player || !player.getComponent('equippable')) {
                return;
            }

            // Get the item in the player's main hand
            const selectedItem = player.getComponent('equippable').getEquipment('Mainhand');

            // Check if the selected item is a pickaxe
            if (!selectedItem) {
                return;
            }

            // Use destroyedBlockPermutation to get the ItemStack directly
            const slabItem = perm.getItemStack(1);
            if (slabItem) {
                // Spawn the item at the destroyed block location
                dimension.spawnItem(slabItem, e.block.location);
            }
        }
    });
});