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

// Subscribe to the 'worldInitialize' event to register custom components
world.beforeEvents.worldInitialize.subscribe(eventData => {
    // Register a custom component named pu_biomes:custom_foliage
    eventData.blockComponentRegistry.registerCustomComponent('pu_biomes:custom_foliage', {
        // Define behavior when a player places the top snow
        onPlace(e) {
            const { block } = e;
            const permutation = block.permutation;
            const randomRotation = Math.floor(Math.random() * 4);
            const newPermutation = permutation.withState('pu_biomes:random_rotation', randomRotation);
            block.setPermutation(newPermutation);
        }
    });
});

// After a player breaks any block, check if they used shears—if so, drop the block itself
world.afterEvents.playerBreakBlock.subscribe(event => {
    const { itemStackBeforeBreak, brokenBlockPermutation, block } = event;

    // Only trigger if the block was broken with shears
    if (itemStackBeforeBreak?.typeId === 'minecraft:shears') {
        // Grab the original block’s identifier (e.g. 'pu_biomes:bloomheart')
        const blockId = brokenBlockPermutation.type.id;
        // Create a one‐item stack of that block
        const drop = new ItemStack(blockId, 1);
        // Spawn it at the exact coordinates of the broken block
        const { x, y, z } = block.location;
        block.dimension.spawnItem(drop, { x, y, z });
    }
});