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

const INTERVAL = 20;
system.runInterval(() => {
  const overworld = world.getDimension("overworld");
  if (!overworld) return;
  const players = overworld.getPlayers();
  if (!players || players.length === 0) return;
  const weather = (typeof overworld.getWeather === "function") ? overworld.getWeather() : "clear";

  for (const player of players) {
    const pos = player.location;
    if (!pos) continue;
    if (pos.y < 59) continue;

    let obstructed = false;
    for (let dx = -3; dx <= 3 && !obstructed; dx++) {
      for (let dz = -3; dz <= 3 && !obstructed; dz++) {
        for (let dy = 1; dy <= 3; dy++) {
          const bx = Math.floor(pos.x + dx);
          const by = Math.floor(pos.y + dy);
          const bz = Math.floor(pos.z + dz);
          const b = overworld.getBlock({ x: bx, y: by, z: bz });
          if (b && b.isValid && !b.isAir) {
            obstructed = true;
            break;
          }
        }
      }
    }
    if (obstructed) continue;

    const foot = overworld.getBlock({ x: Math.floor(pos.x), y: Math.floor(pos.y), z: Math.floor(pos.z) });
    if (foot && foot.typeId && (foot.typeId.includes("water") || foot.typeId.includes("lava"))) continue;

    let chance = 0.1;
    let count = 1;
    if (weather === "clear") { chance = 0.1; count = Math.random() < 0.5 ? 1 : 2; }
    else if (weather === "rain") { chance = 0.3; count = Math.floor(Math.random() * 2) + 2; }
    else if (weather === "thunder") { chance = 0.6; count = Math.floor(Math.random() * 3) + 3; }

    if (Math.random() < chance) {
      for (let i = 0; i < count; i++) {
        const offsetX = (Math.random() - 0.5) * 6;
        const offsetZ = (Math.random() - 0.5) * 6;
        const x = pos.x + offsetX;
        const y = pos.y + Math.random() * 2;
        const z = pos.z + offsetZ;
        overworld.spawnParticle("pa:viento", { x, y, z });
      }
    }
  }
}, INTERVAL);