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

const OVERWORLD = "minecraft:overworld";
const GROUP_RADIUS = 32;
const WARNING_TIME = 30 * 20;
const ECLIPSE_TIME = 120 * 20;

let groups = [];

/* ---------------- UTILIDADES ---------------- */

function randInterval() {
  return (10 * 60 + Math.random() * 10 * 60) * 20;
}

function dist(a, b) {
  return Math.sqrt(
    (a.x - b.x) ** 2 +
    (a.z - b.z) ** 2
  );
}

function validPlayer(p) {
  return p.dimension.id === OVERWORLD && p.location.y > 64;
}

function hasTintedGlass(p) {
  const d = p.dimension;
  const l = p.location;
  for (let i = 1; i <= 5; i++) {
    const b = d.getBlock({ x: l.x | 0, y: (l.y + i) | 0, z: l.z | 0 });
    if (b?.typeId === "minecraft:tinted_glass") return true;
  }
  return false;
}

/* ---------------- AGRUPAR JUGADORES ---------------- */

function buildGroups() {
  groups = [];
  const players = world.getPlayers().filter(validPlayer);

  players.forEach(p => {
    let g = groups.find(gr =>
      gr.players.some(o => dist(o.location, p.location) <= GROUP_RADIUS)
    );

    if (!g) {
      g = {
        players: [],
        state: "IDLE",
        timer: randInterval(),
        type: "NORMAL"
      };
      groups.push(g);
    }
    g.players.push(p);
  });
}

/* ---------------- EVENTOS ---------------- */

function startWarning(g) {
  g.state = "WARNING";
  g.timer = WARNING_TIME;
  g.type = Math.random() < 0.5 ? "NORMAL" : "CORRUPT";

  g.players.forEach(p => {
    p.runCommandAsync("playsound minecraft:portal.ambient @p");
    p.runCommandAsync("playsound minecraft:beacon.ambient @p");
  });
}

function startEclipse(g) {
  g.state = "ECLIPSE";
  g.timer = ECLIPSE_TIME;

  g.players.forEach(p => {
    p.runCommandAsync("playsound minecraft:ambient.weather.thunder @p");
  });
}

function endEclipse(g) {
  const dim = g.players[0].dimension;

  const mobs = dim.getEntities().filter(e =>
    e.typeId === "pa:piglin_ecliptor" ||
    e.typeId === "pa:verdugo_ecliptor"
  );

  mobs.forEach(e => {
    e.addEffect("levitation", 40, { amplifier: 1 });
    dim.spawnParticle("minecraft:explosion_emitter", e.location);
    system.runTimeout(() => e.kill(), 40);
  });

  g.players.forEach(p =>
    p.runCommandAsync("playsound minecraft:entity.wither.death @p")
  );

  g.state = "IDLE";
  g.timer = randInterval();
}

/* ---------------- LOOP PRINCIPAL ---------------- */

system.runInterval(() => {
  buildGroups();

  groups.forEach(g => {
    const dim = g.players[0].dimension;

    if (g.state === "IDLE") {
      g.timer--;
      if (g.timer <= 0) startWarning(g);
    }

    if (g.state === "WARNING") {
      g.timer--;

      g.players.forEach(p => {
        dim.spawnParticle("mid:eclipse", {
          x: p.location.x,
          y: 75,
          z: p.location.z
        });
      });

      if (g.timer <= 0) startEclipse(g);
    }

    if (g.state === "ECLIPSE") {
      g.timer--;

      g.players.forEach(p => {
        dim.spawnParticle("mid:eclipse", { x: p.location.x, y: 75, z: p.location.z });

        if (g.type === "CORRUPT" && !hasTintedGlass(p)) {
          dim.spawnParticle("mid:lluvia_de_almas", p.location);
          dim.spawnParticle("mid:niebla_ecliptora", p.location);

          if (Math.random() < 0.01)
            dim.spawnEntity("pa:piglin_ecliptor", p.location);

          if (Math.random() < 0.005)
            dim.spawnEntity("pa:verdugo_ecliptor", p.location);
        }
      });

      if (g.timer <= 0) endEclipse(g);
    }
  });
}, 1);