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

const espera = 6000; 
const vida_mob = 3600; 

system.runInterval(() => {
    for (const player of world.getPlayers()) {
        if (!player.isValid()) continue;

        if (player.hasTag("marca_sacrificio")) {
            if (!player.hasTag("marca_notificada")) {
                player.sendMessage("§4The Brand of Sacrifice burns... You are now being hunted.");
                player.runCommandAsync("playsound ambient.weather.thunder @s");
                player.addTag("marca_notificada");
            }

            const tempo = world.getTimeOfDay();
            const noite = tempo >= 13000 && tempo <= 23000;
            const id_caça = `hunt_${player.id}`;

            if (noite) {
                const last = player.getDynamicProperty("last_brand_spawn") ?? 0;
                
                if (system.currentTick - last >= espera) {
                    const dim = player.dimension;
                    const pos = player.location;
                    const mobs = ["nb:incubus", "nb:caveira", "nb:caveira"];

                    mobs.forEach(tipo => {
                        try {
                            const mob = dim.spawnEntity(tipo, { 
                                x: pos.x + Math.random() * 8 - 4, 
                                y: pos.y, 
                                z: pos.z + Math.random() * 8 - 4 
                            });
                            
                            mob.addTag(id_caça);
                            mob.runCommandAsync("effect @s slowness 999 255 true");
                            mob.runCommandAsync("particle nb:ds_charge ~ ~1 ~");

                            system.runTimeout(() => {
                                if (mob.isValid()) mob.runCommandAsync("effect @s clear");
                            }, 60);

                            system.runTimeout(() => {
                                if (mob.isValid()) mob.applyDamage(9999);
                            }, vida_mob);
                        } catch (e) {}
                    });

                    player.setDynamicProperty("last_brand_spawn", system.currentTick);
                }
            } else {
                const caça = player.dimension.getEntities({ tags: [id_caça] });
                for (const mob of caça) {
                    if (mob.isValid()) {
                        mob.runCommandAsync("particle minecraft:large_smoke_particle ~ ~1 ~");
                        mob.applyDamage(9999);
                    }
                }
            }
        }
    }
}, 20);