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

// Guardamos la última posición de cada jugador
const lastPositions = new Map();
const INTERVAL = 10;

// ❌ Bloquear generación a partir de ±20000
function isBeyondLimit(pos) {
  const absX = Math.abs(pos.x);
  const absZ = Math.abs(pos.z);
  return absX >= 20000 || absZ >= 20000;
}

function spawnLuciérnagaParticles() {
  for (const player of world.getPlayers()) {
    if (player.dimension.id !== "minecraft:the_end") continue;

    const position = player.location;

    // Evitar generación fuera del rango permitido
    if (isBeyondLimit(position)) continue;

    const lastPos = lastPositions.get(player.id) || position;

    // Distancia recorrida
    const dx = position.x - lastPos.x;
    const dy = position.y - lastPos.y;
    const dz = position.z - lastPos.z;
    const movedDistance = Math.sqrt(dx * dx + dy * dy + dz * dz);

    // Si se mueve mucho → más partículas
    const particlesToSpawn = movedDistance > 0.1 ? 3 : 1;

    for (let i = 0; i < particlesToSpawn; i++) {
      const distance = Math.random() * 30 + 10; // 10–40 bloques
      const angle = Math.random() * Math.PI * 2;
      const heightOffset = Math.random() * 15 - 5;
      const particlePosition = {
        x: position.x + Math.cos(angle) * distance,
        y: position.y + heightOffset,
        z: position.z + Math.sin(angle) * distance
      };

      if (Math.random() < 0.3) {
        player.dimension.spawnParticle("pa:nubes_de_vacio", particlePosition);
      }
    }

    // Guardar posición actual
    lastPositions.set(player.id, { x: position.x, y: position.y, z: position.z });
  }
}

system.runInterval(spawnLuciérnagaParticles, INTERVAL);