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

// Blocks that fences should not connect to
const excludedTypes = new Set([
    'minecraft:air',
    'minecraft:wooden_door', 'minecraft:iron_door', 'minecraft:trapdoor',
    'minecraft:glass', 'minecraft:glass_pane',
    'minecraft:acacia_door', 'minecraft:birch_door', 'minecraft:crimson_door', 'minecraft:dark_oak_door',
    'minecraft:jungle_door', 'minecraft:oak_door', 'minecraft:spruce_door', 'minecraft:warped_door',
    'minecraft:mangrove_door', 'minecraft:cherry_door', 'minecraft:bamboo_door',
    'minecraft:acacia_trapdoor', 'minecraft:birch_trapdoor', 'minecraft:crimson_trapdoor', 'minecraft:dark_oak_trapdoor',
    'minecraft:jungle_trapdoor', 'minecraft:oak_trapdoor', 'minecraft:spruce_trapdoor', 'minecraft:warped_trapdoor',
    'minecraft:mangrove_trapdoor', 'minecraft:cherry_trapdoor', 'minecraft:bamboo_trapdoor'
]);

// Helper to recompute connections on any fence block
function updateFenceConnections(block) {
    if (!block?.isValid()) return;

    const neighbors = {
        north: block.north(),
        south: block.south(),
        east:  block.east(),
        west:  block.west()
    };

    const newStates = {
        'pu_biomes:north_picket': neighbors.north && !excludedTypes.has(neighbors.north.typeId) ? 1 : 0,
        'pu_biomes:south_picket': neighbors.south && !excludedTypes.has(neighbors.south.typeId) ? 1 : 0,
        'pu_biomes:east_picket':  neighbors.east  && !excludedTypes.has(neighbors.east.typeId)  ? 1 : 0,
        'pu_biomes:west_picket':  neighbors.west  && !excludedTypes.has(neighbors.west.typeId)  ? 1 : 0,
    };

    const updatedPermutation = BlockPermutation.resolve(block.typeId, {
        ...block.permutation.getAllStates(),
        ...newStates
    });

    block.setPermutation(updatedPermutation);
}

// Register the custom fence component
world.beforeEvents.worldInitialize.subscribe(eventData => {
    eventData.blockComponentRegistry.registerCustomComponent('pu_biomes:fences', {
        onPlace(e) {
            const { block } = e;
            // Clear the item-icon state
            const currentStates = block.permutation.getAllStates();
            block.setPermutation(BlockPermutation.resolve(block.typeId, {
                ...currentStates,
                'pu_biomes:is_item_icon': false
            }));

            // Update this fence and any adjacent fences
            updateFenceConnections(block);
            for (const neighbor of [block.north(), block.south(), block.east(), block.west()]) {
                if (neighbor?.hasTag('pu_biomes:custom_fence')) {
                    updateFenceConnections(neighbor);
                }
            }
        }
    });
});

// When a fence is broken, reconnect adjacent fences
world.afterEvents.playerBreakBlock.subscribe(e => {
    const { block } = e;
    for (const neighbor of [block.north(), block.south(), block.east(), block.west()]) {
        if (neighbor?.hasTag('pu_biomes:custom_fence')) {
            updateFenceConnections(neighbor);
        }
    }
});

// Fires after a player places a block
world.afterEvents.playerPlaceBlock.subscribe(event => {
    const { block: placedBlock } = event;
    // Only trigger if the placed block's type is not in excludedTypes
    if (!excludedTypes.has(placedBlock.typeId)) {
        for (const neighbor of [
            placedBlock.north(),
            placedBlock.south(),
            placedBlock.east(),
            placedBlock.west()
        ]) {
            if (neighbor?.hasTag('pu_biomes:custom_fence')) {
                updateFenceConnections(neighbor);
            }
        }
    }
}); 