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

const DESPAWN_MAX_DISTANCE = 128;
const DESPAWN_MAX_DISTANCE_SQ = DESPAWN_MAX_DISTANCE * DESPAWN_MAX_DISTANCE;
const FAMILY = "monster";
const NAMED_TAG = "otherworldly_permanent";

// Cada 1 segundo revisa todos los mobs
system.runInterval(() => {
  for (const dimName of ["overworld", "nether", "the_end"]) {
    const dimension = world.getDimension(dimName);
    const mobs = dimension.getEntities({ families: [FAMILY] });

    for (const mob of mobs) {
      // Revisar si recibe nombre personalizado y agregar la etiqueta
      const nameable = mob.getComponent("nameable");
      if (
        nameable &&
        nameable.nameTag &&
        nameable.nameTag.length > 0 &&
        nameable.nameTag !== mob.typeId.replace("minecraft:", "") &&
        !mob.hasTag(NAMED_TAG)
      ) {
        mob.addTag(NAMED_TAG);
      }

      // NO borra si tiene la etiqueta "named_permanent"
      if (mob.hasTag(NAMED_TAG)) continue;

      // NO borra si tiene nombre personalizado (por seguridad doble)
      if (
        nameable &&
        nameable.nameTag &&
        nameable.nameTag.length > 0 &&
        nameable.nameTag !== mob.typeId.replace("minecraft:", "")
      ) continue;

      // Borra si no hay ningún jugador cerca
      let nearPlayer = false;
      for (const player of world.getAllPlayers()) {
        const dx = player.location.x - mob.location.x;
        const dy = player.location.y - mob.location.y;
        const dz = player.location.z - mob.location.z;
        if ((dx * dx + dy * dy + dz * dz) <= DESPAWN_MAX_DISTANCE_SQ) {
          nearPlayer = true;
          break;
        }
      }
      if (!nearPlayer) mob.remove();
    }
  }
}, 20);
