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

const BLOCK_ARBUSTO_RODANTE = "pa:arbusto_rodante";
const PARTICLE_TORMENTA = "pa:tormenta_de_arena_roja";
const PARTICLE_ARBUSTO = "pa:arbusto_rodante";
const FOG_ID = "mid:fog_tormenta_de_arena_roja";

const CHECK_INTERVAL = 20;
const PARTICLE_INTERVAL = 40;
const DURATION_TORMENTA = 20 * 60;
const COOLDOWN_TORMENTA = 20 * 300;
const SCAN_RADIUS = 12;

let tormentaActiva = false;
let ticksRestantes = 0;
let cooldown = 0;

function hayArenaCerca(pos, dim) {
  for (let x = -1; x <= 1; x++) {
    for (let y = -1; y <= 1; y++) {
      for (let z = -1; z <= 1; z++) {
        const b = dim.getBlock({
          x: pos.x + x,
          y: pos.y + y,
          z: pos.z + z
        });
        if (b?.typeId === "minecraft:red_sand") return true;
      }
    }
  }
  return false;
}

function verificarInicioTormenta() {
  if (tormentaActiva) return;
  if (cooldown > 0) {
    cooldown--;
    return;
  }

  for (const player of world.getPlayers()) {
    const dim = player.dimension;
    const base = player.location;

    for (let x = -SCAN_RADIUS; x <= SCAN_RADIUS; x++) {
      for (let y = -4; y <= 4; y++) {
        for (let z = -SCAN_RADIUS; z <= SCAN_RADIUS; z++) {
          const pos = {
            x: Math.floor(base.x + x),
            y: Math.floor(base.y + y),
            z: Math.floor(base.z + z)
          };
          const block = dim.getBlock(pos);
          if (!block) continue;

          if (block.typeId === BLOCK_ARBUSTO_RODANTE && hayArenaCerca(pos, dim)) {
            iniciarTormenta();
            return;
          }
        }
      }
    }
  }
}

function iniciarTormenta() {
  tormentaActiva = true;
  ticksRestantes = DURATION_TORMENTA;
  cooldown = COOLDOWN_TORMENTA;

  for (const p of world.getPlayers()) {
    p.runCommandAsync(`fog @p push ${FOG_ID}`);
  }
}

function terminarTormenta() {
  tormentaActiva = false;

  for (const p of world.getPlayers()) {
    p.runCommandAsync(`fog @p remove ${FOG_ID}`);
  }
}

function generarEfectosTormenta() {
  for (const player of world.getPlayers()) {
    const dim = player.dimension;

    if (Math.random() < 0.35) {
      dim.spawnParticle(PARTICLE_TORMENTA, {
        x: player.location.x + (Math.random() - 0.5) * 10,
        y: player.location.y + 1,
        z: player.location.z + (Math.random() - 0.5) * 10
      });
    }

    if (Math.random() < 0.12) {
      dim.spawnParticle(PARTICLE_ARBUSTO, {
        x: player.location.x + (Math.random() - 0.5) * 14,
        y: player.location.y,
        z: player.location.z + (Math.random() - 0.5) * 14
      });
    }
  }
}

system.runInterval(() => {
  if (!tormentaActiva) {
    verificarInicioTormenta();
    return;
  }

  if (ticksRestantes <= 0) {
    terminarTormenta();
    return;
  }

  generarEfectosTormenta();
  ticksRestantes -= CHECK_INTERVAL;
}, CHECK_INTERVAL);