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

const PARTICLE_RADIUS = 5;
const PARTICLE_LIFETIME_TICKS = Math.floor(6.6 * 20); // 192 ticks, sincronizado con max_lifetime

// Verifica si un bloque puede generar niebla
function canSpawnFog(block, dimension) {
  if (!block) return false;

  const pos = block.location;
  const neighborOffsets = [
    { x: 0, y: 1, z: 0 },
    { x: 0, y: -1, z: 0 },
    { x: 1, y: 0, z: 0 },
    { x: -1, y: 0, z: 0 },
    { x: 0, y: 0, z: 1 },
    { x: 0, y: 0, z: -1 }
  ];

  for (const offset of neighborOffsets) {
    const neighborPos = { x: pos.x + offset.x, y: pos.y + offset.y, z: pos.z + offset.z };
    const neighbor = dimension.getBlock(neighborPos);
    if (!neighbor) continue;
    if (neighbor.typeId === "minecraft:snow_layer") return true;
  }

  const below = dimension.getBlock({ x: pos.x, y: pos.y - 1, z: pos.z });
  if (below?.typeId === "minecraft:podzol") return true;

  return false;
}

// Generar niebla
function spawnFog() {
  for (const player of world.getPlayers()) {
    const dimension = player.dimension;

    for (let x = -10; x <= 10; x++) {
      for (let y = -3; y <= 3; y++) {
        for (let z = -10; z <= 10; z++) {
          const blockPos = {
            x: Math.floor(player.location.x + x),
            y: Math.floor(player.location.y + y),
            z: Math.floor(player.location.z + z)
          };
          const block = dimension.getBlock(blockPos);
          if (!block || block.typeId !== "pa:rocas") continue;

          if (canSpawnFog(block, dimension)) {
            const randPos = {
              x: player.location.x + (Math.random() - 0.5) * PARTICLE_RADIUS * 2,
              y: player.location.y + Math.random() * 2,
              z: player.location.z + (Math.random() - 0.5) * PARTICLE_RADIUS * 2
            };
            dimension.spawnParticle("pa:niebla", randPos);
            return; // una sola partícula por ciclo
          }
        }
      }
    }
  }
}

// Ejecutar cada PARTICLE_LIFETIME_TICKS para que aparezca justo al morir la anterior
system.runInterval(spawnFog, PARTICLE_LIFETIME_TICKS);