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

const activatedPlayers = new Set();

/**
 * Detecta bloques alrededor del jugador y aplica efectos si encuentra suficientes.
 * @param {import("@minecraft/server").Player} player 
 */
export function detectBlocks(player) {
    const BLOCK_ID = "dungeon:tomb";
    const SCOREBOARD = "tombstest";
    const RANGE = 7.25;
    const MAX_Y = 319;
    const MIN_Y = -60;
    const REQUIRED_COUNT = 4;

    const { x, y, z } = player.location;
    const dim = world.getDimension(player.dimension.id);

    const startX = Math.floor(x - RANGE);
    const endX = Math.floor(x + RANGE);
    const startY = Math.max(Math.floor(y - 4), MIN_Y);
    const endY = Math.min(Math.floor(y + 1), MAX_Y);
    const startZ = Math.floor(z - RANGE);
    const endZ = Math.floor(z + RANGE);

    let count = 0;

    outer: for (let xi = startX; xi <= endX; xi++) {
        for (let yi = startY; yi <= endY; yi++) {
            for (let zi = startZ; zi <= endZ; zi++) {
                const block = dim.getBlock({ x: xi, y: yi, z: zi });
                if (block?.typeId === BLOCK_ID && ++count >= REQUIRED_COUNT) {
                    break outer;
                }
            }
        }
    }

    const isActivated = activatedPlayers.has(player.name);

    if (count >= REQUIRED_COUNT && !isActivated) {
        activatedPlayers.add(player.name);
        player.runCommand(`fog @s push "dungeon:cemetery_fog" cemetery`);
        player.runCommand(`tag @s add cursedcementery`);
        player.runCommand(`scoreboard players set @s ${SCOREBOARD} ${count}`);
    } else if (count < REQUIRED_COUNT && isActivated) {
        activatedPlayers.delete(player.name);
        player.runCommand(`scoreboard players set @s ${SCOREBOARD} 0`);
        player.runCommand(`tag @s remove cursedcementery`);
        player.runCommand(`fog @s remove cemetery`);
    }
}
