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

system.runInterval(() => {
    const dimensions = ["overworld", "nether", "the_end"];
    for (const dimId of dimensions) {
        try {
            const dim = world.getDimension(dimId);
            const critters = dim.getEntities({
                type: "mebesm:smiling_critters"
            }).concat(dim.getEntities({
                type: "mebesm:nightmare_critters"
            }));

            for (const mob of critters) {
                if (!mob.isValid()) continue;
                const nearFire = dim.getEntities({
                    location: mob.location,
                    maxDistance: 10,
                    type: "mebesm:fire"
                }).length > 0;

                if (nearFire && !mob.hasTag("fear_fire")) {
                    mob.addTag("fear_fire");
                    try { mob.triggerEvent("mebesm:start_flee"); } catch { }
                } else if (!nearFire && mob.hasTag("fear_fire")) {
                    mob.removeTag("fear_fire");
                    try { mob.triggerEvent("mebesm:stop_flee"); } catch { }
                }
            }
        } catch { }
    }
}, 5);