import { system, world } from "@minecraft/server";
import { cachedPlayers } from './pvp.js';

const overworld = world.getDimension("overworld");
const nether = world.getDimension("minecraft:nether");
const TELEPORT_LOCATION = { x: 0, y: 200, z: 0 };
const regionMin = { x: 835, y: -60, z: -1214 };
const regionMax = { x: 1235, y: 200, z: -814 };
const exclusionZones = [[-3003, 0, 3017, -2932, 20, 2983]];

let tickCounter = 0;

function runCommand(command) {
  try {
    overworld.runCommand(command);
  } catch {}
}

function sendClearLagMessage(message) {
  runCommand(`tellraw @a {"rawtext":[{"text":"§l§2[SERVER] §r§a${message}"}]}`);
}

system.runInterval(() => {
  if (!nether) return;
  const playersInNether = nether.getPlayers();
  for (const player of playersInNether) {
    if (player?.isValid()) {
      player.teleport(TELEPORT_LOCATION, { dimension: overworld });
    }
  }
}, 100);

system.runInterval(() => {
  tickCounter += 40;

  const xpOrbs = overworld.getEntities({ type: "minecraft:xp_orb" });
  if (xpOrbs.length > 90) xpOrbs.forEach(orb => orb.remove());

  const droppedItems = overworld.getEntities({ type: "minecraft:item" });
  if (droppedItems.length > 370) {
    droppedItems.forEach(item => item.teleport({ x: 1000, y: 7, z: 1005 }));
    sendClearLagMessage("Removed excess dropped items!");
  }

  const arrows = overworld.getEntities({ type: "minecraft:arrow" });
  if (arrows.length > 40) {
    arrows.forEach(arrow => arrow.remove());
    sendClearLagMessage("Removed excess arrows!");
  }

  for (const player of cachedPlayers) {
    const { x, y, z } = player.location;
    const isInExclusion = exclusionZones.some(([x1, y1, z1, x2, y2, z2]) =>
      x >= Math.min(x1, x2) && x <= Math.max(x1, x2) &&
      y >= Math.min(y1, y2) && y <= Math.max(y1, y2) &&
      z >= Math.min(z1, z2) && z <= Math.max(z1, z2)
    );

    if (!isInExclusion) {
      if (player.hasTag("red")) player.removeTag("red");
      if (player.hasTag("blue")) player.removeTag("blue");
    }
  }

  if (tickCounter >= 200) tickCounter = 0;
}, 60);

console.warn("Clear lag system initialized with 2 intervals only!");