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

const DIMENSION = "minecraft:the_end";
const MIN = 20000;
const MAX = 30000;

// Partículas y bloques
const SOUL_RAIN_PARTICLE = "pa:lluvia_de_almas";
const MUSGO_BLOCK = "pa:bloque_de_musgo_balmea";

// Utilidades
function inLimbo(x, z) {
  return x >= MIN && x <= MAX && z >= MIN && z <= MAX;
}

function hasArmor(player) {
  const eq = player.getComponent("minecraft:equippable");
  if (!eq) return false;
  return (
    eq.getEquipment("Head") ||
    eq.getEquipment("Chest") ||
    eq.getEquipment("Legs") ||
    eq.getEquipment("Feet")
  );
}

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

    const { x, y, z } = player.location;
    if (!inLimbo(x, z)) continue;

    /* ======================
       EFECTOS DEL LIMBO
    ====================== */

    player.addEffect("jump_boost", 220, {
      amplifier: 4,
      showParticles: false
    });

    player.addEffect("slow_falling", 220, {
      amplifier: 0,
      showParticles: false
    });

    // Frío si no lleva armadura
    if (!hasArmor(player)) {
      player.addEffect("freezing", 120, {
        showParticles: true
      });
    }

    /* ======================
       SONIDO AMBIENTAL
    ====================== */

    if (Math.random() < 0.08) {
      const sounds = [
        "ambient.soul_sand_valley.loop",
        "ambient.cave",
        "block.sculk_shrieker.shriek"
      ];
      const sound = sounds[Math.floor(Math.random() * sounds.length)];
      player.runCommandAsync(`playsound ${sound} @s ~ ~ ~ 0.6`);
    }

    /* ======================
       LLUVIA DE ALMAS
    ====================== */

    if (Math.random() < 0.4) {
      const count = 6 + Math.floor(Math.random() * 5);
      for (let i = 0; i < count; i++) {
        player.dimension.spawnParticle(
          SOUL_RAIN_PARTICLE,
          {
            x: x + Math.random() * 12 - 6,
            y: y + 14 + Math.random() * 10,
            z: z + Math.random() * 12 - 6
          }
        );
      }
    }

    /* ======================
       MUSGO BALMEA VIVO
    ====================== */

    if (Math.random() < 0.01) {
      const baseX = Math.floor(x + Math.random() * 16 - 8);
      const baseZ = Math.floor(z + Math.random() * 16 - 8);
      const baseY = Math.floor(y - 1);

      // Solo crece si hay aire encima
      player.dimension.runCommandAsync(
        `execute if block ${baseX} ${baseY} ${baseZ} air run setblock ${baseX} ${baseY} ${baseZ} ${MUSGO_BLOCK}`
      );
    }
  }
}, 20);