// replaces the current block with the most common nearby blocks
import { world } from "@minecraft/server";

world.beforeEvents.worldInitialize.subscribe((Initiate) => {
    Initiate.blockComponentRegistry.registerCustomComponent("ecbl_bc:replace_by_common", {
        onTick: (e) => {
            const location = e.block.location;
            const dimension = e.dimension;
            const points = [
                { x: location.x + 1, y: location.y, z: location.z },
                { x: location.x - 1, y: location.y, z: location.z },
                { x: location.x, y: location.y, z: location.z + 1 },
                { x: location.x, y: location.y, z: location.z - 1 }
            ];

            const blockCounts = {};
            for (const point of points) {
                const block = dimension.getBlock(point);
                if (block) {
                    const typeId = block?.typeId;
                    if (typeId && typeId !== "minecraft:air") {
                        blockCounts[typeId] = (blockCounts[typeId] || 0) + 1;
                    }
                }
            }
            if (Object.keys(blockCounts).length === 0) { e.block.setType('minecraft:air'); return; }
            const mostCommon = Object.keys(blockCounts).reduce((a, b) => blockCounts[a] > blockCounts[b] ? a : b);

            if (mostCommon) {
                e.block.setType(mostCommon);
            }
        }
    });
});