
import { world } from '@minecraft/server';

world.beforeEvents.worldInitialize.subscribe(eventData => {
    eventData.blockComponentRegistry.registerCustomComponent('kai:on_interact_red_sand_layer', {
        onPlayerInteract(e) {
            const { block, player } = e;
            const equipment = player.getComponent('equippable');
            const selectedItem = equipment.getEquipment('Mainhand');
            if (selectedItem && selectedItem.typeId === 'block:top_red_sand') {
                const permutation = block.permutation;
                const currentLayerLevel = permutation.getState('kai:layer_level');
                if (currentLayerLevel <= 6) {
                    e.cancel = true;
                    const newLayerLevel = currentLayerLevel + 1;
                    const newPermutation = permutation.withState('kai:layer_level', newLayerLevel);
                    block.setPermutation(newPermutation);
                    if (player.getGameMode() !== "creative") {
                        if (selectedItem.amount > 1) {
                            selectedItem.amount -= 1;
                            equipment.setEquipment('Mainhand', selectedItem);
                        } else {
                            equipment.setEquipment('Mainhand', undefined);
                        }
                    }
                }
            }
        }
    });
});