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

world.beforeEvents.worldInitialize.subscribe((Initiate) => {
    Initiate.blockComponentRegistry.registerCustomComponent("ecbl_bc:on_place_naturally", {
        onTick(event) {
            const { block, dimension } = event;

            dimension.setBlockType(block.location, block.typeId.replace("_rootplacer", ""));
            dimension.setBlockType(block.below().location, block.typeId.replace("_rootplacer", ""));
        },
    });
});


//SECURITY SYSTEM! If for some reason the tick component doesn't work, this will prevent any major problems.
system.runInterval(() => {
    for (const player of world.getPlayers()) {
        const location = player.location;
        const dimension = player.dimension;

        const centerX = Math.floor(location.x);
        const centerY = Math.floor(location.y);
        const centerZ = Math.floor(location.z);

        for (let dx = -5; dx <= 5; dx++) {
            for (let dz = -5; dz <= 5; dz++) {
                const checkLoc = {
                    x: centerX + dx,
                    y: centerY,
                    z: centerZ + dz,
                };

                const block = dimension.getBlock(checkLoc);
                if (block && block.typeId.includes("_rootplacer")) {
                    const newTypeId = block.typeId.replace("_rootplacer", "");
                    dimension.setBlockType(checkLoc, newTypeId);
                    dimension.setBlockType(block.below().location, newTypeId);
                }
            }
        }
    }
}, 0);