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

// ==========================================
// CONFIGURAÇÕES DOS MONSTROS
// ==========================================
const WHITELIST_MOBS = [
    "minecraft:pillager",
    "minecraft:vindicator", 
    "minecraft:evocation_illager",
    "minecraft:vex",
    "minecraft:ravager",
    "minecraft:wither_skeleton",
    "minecraft:blaze",
    "minecraft:warden",
    "minecrart:wither",
    "minecraft:ender_dragon"
];

let isSpawnWindowOpen = false;
let spawnTimerTicks = 0;

const BLOCKED_TICKS = 2 * 60 * 20; // 2 minutos bloqueado
const OPEN_TICKS = 20 * 20;        // 20 segundos liberado

// Função que checa se tem um spawner pertinho de onde o monstro nasceu
function isNearSpawner(dimension, loc) {
    for (let x = -4; x <= 4; x++) {
        for (let y = -4; y <= 4; y++) {
            for (let z = -4; z <= 4; z++) {
                try {
                    const block = dimension.getBlock({ x: loc.x + x, y: loc.y + y, z: loc.z + z });
                    if (block && (block.typeId === "minecraft:mob_spawner" || block.typeId === "minecraft:trial_spawner")) {
                        return true;
                    }
                } catch (e) {
                    // Ignora se o bloco não tiver totalmente carregado
                }
            }
        }
    }
    return false;
}

// Evento que ativa toda vez que algum bicho spawna
world.afterEvents.entitySpawn.subscribe((event) => {
    const entity = event.entity;

    // 1. TRAVA DE ADD-ONS: Se a entidade nao for nativa do Minecraft, ignora completamente
    if (!entity.typeId || !entity.typeId.startsWith("minecraft:")) return;

    // 2. Checa se e um monstro
    if (!entity.hasComponent("minecraft:type_family")) return;
    const families = entity.getComponent("minecraft:type_family").getTypeFamilies();
    if (!families.includes("monster")) return;

    // 3. Checa whitelist
    if (WHITELIST_MOBS.includes(entity.typeId)) return;

    // 4. Janela de spawn
    if (isSpawnWindowOpen) {
        entity.addTag("monstercap:monster_allowed");
        return;
    }
    
    if (entity.hasTag("monstercap:monster_allowed")) return;

    // 5. Spawner
    if (isNearSpawner(entity.dimension, entity.location)) {
        entity.addTag("monstercap:monster_allowed");
        return;
    }

    // Deleta apenas o monstro vanilla
    system.run(() => {
        try {
            entity.remove();
        } catch(e){}
    });
});

// Loop pra contar o tempo e abrir/fechar a janela de spawns
system.runInterval(() => {
    spawnTimerTicks++;
    if (!isSpawnWindowOpen) {
        if (spawnTimerTicks >= BLOCKED_TICKS) {
            isSpawnWindowOpen = true;
            spawnTimerTicks = 0;
        }
    } else {
        if (spawnTimerTicks >= OPEN_TICKS) {
            isSpawnWindowOpen = false;
            spawnTimerTicks = 0;
        }
    }
}, 1);
