import { world, BlockPermutation, Vector } from "@minecraft/server"

// Array defining pairs of bottom and top blocks for double plants
const tallBottomDoors = [
    {
        id: "better_on_bedrock:waystone_block_bottom",
        topBit: {
            id: "better_on_bedrock:waystone_top"
        }
    }
]

world.afterEvents.playerPlaceBlock.subscribe(ev => {
    const above = ev.block.above();

    
    // Find a matching bottom door based on the placed block's permutation
    const matchingBottomDoors = tallBottomDoors.find((door) => ev.block.permutation.matches(door.id));

    // Check if the above block is air to place the corresponding top door
    if (matchingBottomDoors != undefined && above.isAir) {
        // Access the corresponding top door ID directly from the structure
        const matchingBottomDoorsId = matchingBottomDoors.topBit.id;

        // Place the corresponding top door
        above.setPermutation(BlockPermutation.resolve(matchingBottomDoorsId));
        above.setPermutation(BlockPermutation.resolve(matchingBottomDoorsId, ev.block.permutation.getAllStates()));
        if(matchingBottomDoors  != undefined){
            above.setPermutation(BlockPermutation.resolve(matchingBottomDoorsId, ev.block.permutation.getAllStates()));
        }
    } else if (matchingBottomDoors != undefined && !above.isAir) {
        // If the above block is not air, break the placed bottom block
        const { x, y, z } = ev.block.location;
        ev.dimension.runCommand(`setblock ${x} ${y} ${z} air[] destroy`);
    }
})

world.afterEvents.playerBreakBlock.subscribe(ev => {
    // Find a matching top door based on the broken block's permutation
    const matchingTopDoor = tallBottomDoors.find((door) => ev.brokenBlockPermutation.matches(door.topBit.id));

    // Break the corresponding bottom block if a matching top door is found
    if (matchingTopDoor) {
        const { x, y, z } = ev.block.location;
        ev.dimension.runCommand(`setblock ${x} ${y - 1} ${z} air[] destroy`);
    }
})
