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

world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
    blockComponentRegistry.registerCustomComponent("cb:trap_chain_detector", {
        onTick({ block }) {
            let aboveBlock = block.dimension.getBlock({ 
                x: block.location.x, 
                y: block.location.y + 1, 
                z: block.location.z 
            });

            let hasChain = aboveBlock?.typeId === "minecraft:chain";
            let currentStage = block.permutation.getState("crabbersdelight:crab_trap");

            let currentProperties = block.permutation.getAllStates();

            if (hasChain && currentStage !== 1) {
                currentProperties["crabbersdelight:crab_trap"] = 1;
                let newPermutation = BlockPermutation.resolve("crabbersdelight:crab_trap", currentProperties);
                block.setPermutation(newPermutation);
            } 
            else if (!hasChain && currentStage !== 0) {
                currentProperties["crabbersdelight:crab_trap"] = 0;
                let defaultPermutation = BlockPermutation.resolve("crabbersdelight:crab_trap", currentProperties);
                block.setPermutation(defaultPermutation);
            }
        }
    });
});