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

// === CONFIG ===
const EFFECTS = [
  { id: "minecraft:weakness", duration: 50, amplifier: 255 },
  { id: "minecraft:fire_resistance", duration: 50, amplifier: 255 },
  { id: "minecraft:resistance", duration: 50, amplifier: 255 },
  { id: "minecraft:instant_health", duration: 50, amplifier: 255 },
];

const RANK_TAGS = ["gwim:VIP","gwim:VIPPlus","gwim:Elite","gwim:ElitePlus","gwim:God"];

const exclusionZones = [
  [835, -60, -1214, 1235, 200, -814],
  [-910, 4, 919, -1097, 200, 1088],
  [-2974, 3, 2987, -2936, 20, 3013],
  [4921, 98, 4921, 5079, 15, 5079],
];

const ZONE_CENTER = { x: 4028, y: 5, z: 4000 };
const ZONE_RADIUS_SQ = 60 * 60;

const allowedTags = new Set(["gwim:VIP","gwim:VIPPlus","gwim:Elite","gwim:ElitePlus","gwim:God","gwim:Admin","gwim:Owner"]);

// === HELPERS ===
function isInZone(pos, center) {
  const dx = pos.x - center.x;
  const dz = pos.z - center.z;
  return dx*dx + dz*dz <= ZONE_RADIUS_SQ;
}

// === EVENTS ===
world.afterEvents.playerJoin.subscribe((event) => {
  const player = event.player;
  if (player.hasTag("gwim:VIP") && !player.hasTag("VIPPurchased")) {
    player.addTag("VIPPurchased");
  }
});

// === SYSTEMS ===

// 1️⃣ Effects + VIP enforcement (every 2 ticks instead of 1)
system.runInterval(() => {
  if (!cachedPlayers.length) return;

  for (const player of cachedPlayers) {
    const loc = player.location;
    const tagsArr = player.getTags();
    if (!tagsArr.length) continue;
    const tags = new Set(tagsArr);

    // Exclusion zones
    const excluded = player.dimension.id === "minecraft:the_end" ||
      exclusionZones.some(([x1,y1,z1,x2,y2,z2]) =>
        loc.x >= Math.min(x1,x2) && loc.x <= Math.max(x1,x2) &&
        loc.y >= Math.min(y1,y2) && loc.y <= Math.max(y1,y2) &&
        loc.z >= Math.min(z1,z2) && loc.z <= Math.max(z1,z2)
      );
    if (excluded) continue;

    // Apply effects only if missing or wrong amplifier
    for (const { id, duration, amplifier } of EFFECTS) {
      const current = player.getEffect(id);
      if (!current || current.amplifier !== amplifier) {
        player.addEffect(id, duration, { amplifier, showParticles: false });
      }
    }

    // VIP enforcement
    const hasVIP = tags.has("gwim:VIP");
    const hasVIPPurchased = tags.has("VIPPurchased");
    const hasHigherRank = RANK_TAGS.slice(1).some(tag => tags.has(tag));

    if (hasVIPPurchased) {
      if (!hasVIP && !hasHigherRank) player.addTag("gwim:VIP");
    } else {
      if (hasVIP) player.removeTag("gwim:VIP");
      for (const tag of RANK_TAGS.slice(1)) {
        if (tags.has(tag)) player.removeTag(tag);
      }
    }
  }
}, 2);


// 2️⃣ Auto-upgrade ranks (every second, optimized)
system.runInterval(() => {
  const moneyObj = world.scoreboard.getObjective("Money");
  if (!moneyObj || !cachedPlayers.length) return;

  for (const player of cachedPlayers) {
    try {
      const identity = player.scoreboardIdentity;
      const money = moneyObj.hasParticipant(identity) ? moneyObj.getScore(identity) : 0;
      const tagsArr = player.getTags();
      if (!tagsArr.length) continue;
      const tags = new Set(tagsArr);

      const hasVIPPurchased = tags.has("VIPPurchased");
      if (money <= 80_000_000) {
        for (const tag of RANK_TAGS.slice(1)) if (tags.has(tag)) player.removeTag(tag);
        continue;
      }
      if (!hasVIPPurchased) continue;

      let targetTag = "", targetRank = "";
      if (money >= 1_000_000_000) { targetTag = "gwim:God"; targetRank = "§d§l|| GOD ||"; }
      else if (money >= 400_000_000) { targetTag = "gwim:ElitePlus"; targetRank = "§b§lElite+"; }
      else if (money >= 200_000_000) { targetTag = "gwim:Elite"; targetRank = "§b§lElite"; }
      else { targetTag = "gwim:VIPPlus"; targetRank = "§e§lVIP+"; }

      if (!tags.has(targetTag)) {
        for (const tag of RANK_TAGS) if (tag !== targetTag && tags.has(tag)) player.removeTag(tag);
        player.addTag(targetTag);
        player.playSound("random.levelup");
        player.sendMessage(`§aYour rank is now ${targetRank}`);
      }
    } catch (err) {
      console.warn(`Error in auto-rank for ${player.name}: ${err}`);
    }
  }
}, 20);

// 3️⃣ VIP-only zone check (every 5 seconds) remains unchanged
system.runInterval(() => {
  if (!cachedPlayers.length) return;
  for (const player of cachedPlayers) {
    const pos = player.location;
    const tagsArr = player.getTags();
    const tags = new Set(tagsArr);
    const hasPermission = [...allowedTags].some(tag => tags.has(tag));
    const inZone = isInZone(pos, ZONE_CENTER);
    if (inZone && !hasPermission && !tags.has("Lobby")) {
      player.addTag("Lobby");
      player.sendMessage("§cYou don't have any VIP or higher ranks");
    }
  }
}, 100);