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

// Subscribe to the 'worldInitialize' event to register custom components
world.afterEvents.playerPlaceBlock.subscribe(eventData => {
    const { block } = eventData;

    if (!block.hasTag('pu_biomes:custom_grass')) return;

    system.run(() => {
        const { x, y, z } = block.location;
        const range = 1;

        const allowedBlocks = new Set([
            'minecraft:air', 'minecraft:glass', 'minecraft:torch', 'minecraft:end_rod', 'minecraft:lightning_rod', 
            'minecraft:glowstone', 'minecraft:sea_lantern', 'minecraft:redstone_lamp', 'minecraft:lantern', 'minecraft:campfire', 
            'minecraft:soul_campfire', 'minecraft:beacon', 'minecraft:shroomlight', 'minecraft:jack_o_lantern', 'minecraft:soul_lantern', 
            'minecraft:glass_pane', 'minecraft:stained_glass', 'minecraft:stained_glass_pane', 'minecraft:leaves', 'minecraft:iron_bars', 
            'minecraft:chain', 'minecraft:ice', 'minecraft:packed_ice', 'minecraft:blue_ice', 'minecraft:slime_block', 
            'minecraft:honey_block', 'minecraft:trapdoor', 'minecraft:glass_bottle', 'minecraft:hopper', 'minecraft:rail', 
            'minecraft:detector_rail', 'minecraft:activator_rail', 'minecraft:powered_rail', 'minecraft:scaffolding', 'minecraft:vines', 
            'minecraft:carpet', 'minecraft:ladder', 'minecraft:snow_layer', 'minecraft:iron_trapdoor', 'minecraft:tripwire', 
            'minecraft:tripwire_hook', 'minecraft:banner', 'minecraft:web', 'minecraft:chorus_plant', 'minecraft:chorus_flower', 
            'minecraft:end_gateway', 'minecraft:end_portal', 'minecraft:end_portal_frame', 'minecraft:barrier', 'minecraft:structure_void', 
            'minecraft:bamboo', 'minecraft:flower_pot', 'minecraft:cobweb', 'minecraft:conduit', 'minecraft:conduit_power', 
            'minecraft:soul_torch', 'minecraft:soul_fire', 'minecraft:candle', 'minecraft:candle_cake', 'minecraft:azalea', 
            'minecraft:flowering_azalea'
        ]);

        for (let dx = -range; dx <= range; dx++) {
            for (let dy = -range; dy <= range; dy++) {
                for (let dz = -range; dz <= range; dz++) {
                    if (dx === 0 && dy === 0 && dz === 0) continue; // Skip source block

                    const target = block.dimension.getBlock({ x: x + dx, y: y + dy, z: z + dz });
                    if (!target) continue;

                    if (target.typeId === 'minecraft:dirt' || target.typeId === 'pu_biomes:grass') {
                        const above = target.above();
                        if (!above) continue;

                        if (target.typeId === 'pu_biomes:grass' && !allowedBlocks.has(above.typeId)) {
                            target.setType('minecraft:dirt');
                        } else if (target.typeId === 'minecraft:dirt' && allowedBlocks.has(above.typeId)) {
                            target.setType(block.typeId);
                        }
                    }
                }
            }
        }
    });
});

world.beforeEvents.playerInteractWithBlock.subscribe(eventData => {
    const { block, player, blockFace, itemStack } = eventData;

    if (!itemStack || blockFace === 'down') {
        return;
    }

    if (!block.hasTag('pu_biomes:custom_grass')) {
        return;
    }

    const toolMapping = {
        'minecraft:is_shovel': { blockType: 'minecraft:grass_path', sound: 'use.grass' },
        'minecraft:is_hoe': { blockType: 'minecraft:farmland', sound: 'use.gravel' }
    };

    let matched = false;
    for (const [tag, action] of Object.entries(toolMapping)) {
        if (itemStack.hasTag(tag)) {

            system.run(() => {
                block.setType(action.blockType);
                player.playSound(action.sound);
                reduceDurability(itemStack, player);
            });

            matched = true;
            break;
        }
    }

    if (!matched) {
    }
});

function reduceDurability(itemStack, player) {
    const durability = itemStack.getComponent('durability');
    if (!durability) return;

    durability.damage++;

    const equipment = player.getComponent('equippable');
    if (durability.damage >= durability.maxDurability) {
        player.playSound('random.break');
        equipment.setEquipment('Mainhand', new ItemStack('minecraft:air', 1));
    } else {
        equipment.setEquipment('Mainhand', itemStack);
    }
}