import { world, system } from "@minecraft/server";
import { cachedPlayers } from './lag/pvp.js';
let cachedPlayersInZone = [];
let playerScanCooldown = 0;
const PLAYER_SCAN_INTERVAL = 10; // every 10 ticks = 0.5s

const waveMobs = {
  // Waves 1-20 (keep your existing waves)
  1: { "minecraft:zombie": 10 },
  2: { "minecraft:zombie": 8, "minecraft:skeleton": 2 },
  3: { "minecraft:zombie": 10, "minecraft:skeleton": 3 },
  4: { "minecraft:zombie": 9, "minecraft:skeleton": 3, "minecraft:creeper": 2 },
  5: { "minecraft:zombie": 7, "minecraft:skeleton": 4, "minecraft:creeper": 3, "minecraft:spider": 2},
  6: { "minecraft:zombie": 8, "minecraft:skeleton": 4, "minecraft:creeper": 4, "minecraft:spider": 4 },
  7: { "minecraft:zombie": 8, "minecraft:skeleton": 8, "minecraft:creeper": 4, "minecraft:spider": 4 },
  8: { "minecraft:husk": 8, "minecraft:stray": 6, "minecraft:creeper": 6, "minecraft:cave_spider": 4 },
  9: { "minecraft:husk": 10, "minecraft:stray": 10, "minecraft:creeper": 4, "minecraft:drowned": 2, "minecraft:cave_spider": 4 },
  10: { "minecraft:wither": 1, "minecraft:wither_skeleton": 5 },
  11: { "minecraft:husk": 10, "minecraft:stray": 8, "minecraft:creeper": 6, "minecraft:cave_spider": 6, "minecraft:drowned": 4 },
  12: { "minecraft:husk": 10, "minecraft:bogged": 8, "minecraft:creeper": 4, "minecraft:cave_spider": 6, "minecraft:blaze": 4, "minecraft:wither_skeleton": 4 },
  13: { "minecraft:pillager": 7, "minecraft:vindicator": 6, "minecraft:evocation_illager": 5, "minecraft:ravager": 2 },
  14: { "minecraft:wither_skeleton": 8, "minecraft:bogged": 7, "minecraft:creeper": 4, "minecraft:vindicator": 4, "minecraft:breeze": 3, "minecraft:blaze": 3 },
  15: { "minecraft:wither_skeleton": 6, "minecraft:bogged": 8, "minecraft:creeper": 4, "minecraft:cave_spider": 4, "minecraft:witch": 2, "minecraft:breeze": 2,"minecraft:blaze": 3, "minecraft:drowned": 4 },
  16: { "minecraft:wither_skeleton": 5, "minecraft:bogged": 4, "minecraft:stray": 4, "minecraft:creeper": 4, "minecraft:witch": 4, "minecraft:breeze": 5, "minecraft:cave_spider": 4, "minecraft:blaze": 4, "minecraft:evocation_illager": 4 },
  17: { "minecraft:wither_skeleton": 8, "minecraft:bogged": 6, "minecraft:stray": 6, "minecraft:blaze": 8, "minecraft:witch": 6, "minecraft:breeze": 4, "minecraft:ravager": 3 },
  18: { "minecraft:wither_skeleton": 8, "minecraft:bogged": 5, "minecraft:stray": 5, "minecraft:blaze": 7, "minecraft:witch": 7, "minecraft:breeze": 6, "minecraft:vindicator": 3, "minecraft:pillager": 2, "minecraft:evocation_illager": 2, "minecraft:ravager": 1 },
  19: {
    "minecraft:zombie": 3, "minecraft:skeleton": 2, "minecraft:creeper": 4, "minecraft:spider": 5, "minecraft:cave_spider": 3,
    "minecraft:blaze": 5, "minecraft:pillager": 3, "minecraft:evocation_illager": 3, "minecraft:vindicator": 3,
    "minecraft:ravager": 2, "minecraft:stray": 3, "minecraft:drowned": 3, "minecraft:bogged": 3,
    "minecraft:husk": 3, "minecraft:witch": 3, "minecraft:wither_skeleton": 4, "minecraft:breeze": 2
  },
  20: { "minecraft:wither": 1, "minecraft:warden": 1, "minecraft:wither_skeleton": 6 },

  // New waves 21-30
  21: {
    "minecraft:zombie": 2, "minecraft:skeleton": 2, "minecraft:creeper": 4, "minecraft:spider": 2, "minecraft:cave_spider": 3,
    "minecraft:blaze": 3, "minecraft:pillager": 3, "minecraft:evocation_illager": 3, "minecraft:vindicator": 3,
    "minecraft:ravager": 3, "minecraft:stray": 3, "minecraft:drowned": 2, "minecraft:bogged": 3,
    "minecraft:husk": 2, "minecraft:witch": 4, "minecraft:wither_skeleton": 3, "minecraft:breeze": 2
  },
  22: {
    "minecraft:zombie": 8, "minecraft:husk": 8, "minecraft:skeleton": 2, "minecraft:stray": 5, "minecraft:bogged": 5, 
    "minecraft:creeper": 4, "minecraft:cave_spider": 3, "minecraft:spider": 2
  },
  23: {
    "minecraft:wither_skeleton": 8, "minecraft:zombie": 8,
    "minecraft:cave_spider": 4, "minecraft:stray": 6, "minecraft:bogged": 6, "minecraft:vindicator": 4
  },
  24: {
    "minecraft:creeper": 5, "minecraft:blaze": 5, "minecraft:cave_spider": 4, 
    "minecraft:drowned": 4, "minecraft:wither_skeleton": 6, "minecraft:vindicator": 6
  },
  25: {
    "minecraft:pillager": 6, "minecraft:evocation_illager": 4, "minecraft:vindicator": 5,
    "minecraft:ravager": 4, "minecraft:creeper": 3, "minecraft:breeze": 4, "minecraft:blaze": 4
  },
  26: {
    "minecraft:wither_skeleton": 10, "minecraft:creeper": 6, 
    "minecraft:blaze": 5, "minecraft:vindicator": 5, "minecraft:evocation_illager": 5
  },
  27: {
    "minecraft:stray": 4, "minecraft:drowned": 4, "minecraft:blaze": 3, 
    "minecraft:bogged": 4, "minecraft:breeze": 5, "minecraft:cave_spider":3,
    "minecraft:husk": 4, "minecraft:witch": 3, "minecraft:wither_skeleton": 4, "minecraft:creeper": 6
  },
  28: {
    "minecraft:zombie": 20, "minecraft:cave_spider": 10
  },
  29: {
    "minecraft:zombie": 4, "minecraft:skeleton": 2, "minecraft:creeper": 4, "minecraft:spider": 2, "minecraft:cave_spider": 3,
    "minecraft:blaze": 3, "minecraft:pillager": 3, "minecraft:evocation_illager": 3, "minecraft:vindicator": 3,
    "minecraft:ravager": 3, "minecraft:stray": 3, "minecraft:drowned": 2, "minecraft:bogged": 3,
    "minecraft:husk": 4, "minecraft:witch": 4, "minecraft:wither_skeleton": 4, "minecraft:breeze": 2
  },
  30: {
    "minecraft:wither": 2, "minecraft:warden": 2, 
    "minecraft:wither_skeleton": 8, "minecraft:blaze": 8
  },
  31: { "minecraft:creeper": 10, "minecraft:zombie": 40 },
  32: { "minecraft:creeper": 10, "minecraft:skeleton": 40 },
  33: { "minecraft:creeper": 10, "minecraft:husk": 40 },
  34: { "minecraft:creeper": 10, "minecraft:stray": 40 },
  35: { "minecraft:creeper": 10, "minecraft:pillager": 40 },
  36: { "minecraft:creeper": 10, "minecraft:vindicator": 40 },
  37: { "minecraft:creeper": 10, "minecraft:evocation_illager": 40 },
  38: { "minecraft:creeper": 10, "minecraft:blaze": 35, "minecraft:ravager": 5 },
  39: { "minecraft:creeper": 10, "minecraft:wither_skeleton": 40 },
  40: {
    "minecraft:warden": 3,
    "minecraft:creeper": 6,
    "minecraft:wither": 3,
    "minecraft:wither_skeleton": 8,
    "minecraft:blaze": 8
  }
};

const spawnLocations = [
  [1012, 2, -998], [1021, 1, -1002], [1021, 0, -1008], [1028, 0, -1008],
  [1034, -4, -1021], [1035, 2, -982], [1025, 0, -994], [1030, 1, -997],
  [1041, 6, -995], [1057, -16, -1011], [1056, -20, -1031], [1059, -20, -1036],
  [1065, -20, -1037], [1046, -25, -1044], [1035, -25, -1038], [1032, -25, -1043],
  [1024, -24, -1055], [1026, -25, -1061], [1038, -25, -1067], [1042, -23, -1069],
  [1044, -26, -1058], [1053, -23, -1054]
];

let currentWave = 0;
let waveInProgress = false;
let gameStarted = false;
let currentWaveMobs = [];
let countdownId = null;

const zoneMinX = -835, zoneMaxX = 1235;
const zoneMinY = -60, zoneMaxY = 200;
const zoneMinZ = -1214, zoneMaxZ = -814;

function isInZone(location) {
  const { x, y, z } = location;
  return x >= zoneMinX && x <= zoneMaxX && y >= zoneMinY && y <= zoneMaxY && z >= zoneMinZ && z <= zoneMaxZ;
}

system.runInterval(() => {
  if (--playerScanCooldown <= 0) {
    cachedPlayersInZone = [];
    for (const player of cachedPlayers) {
      if (isInZone(player.location)) {
        cachedPlayersInZone.push(player);
      }
    }
    playerScanCooldown = PLAYER_SCAN_INTERVAL;
  }
}, 20); // checks every 1 second

async function startWave(player) {
  if (!gameStarted) return;

  if (currentWave >= 40) {
    waveInProgress = false;
    gameStarted = false;
    currentWaveMobs = [];

    for (const p of cachedPlayersInZone) {
        p.sendMessage("§aAll 40 Waves Cleared!");
        p.onScreenDisplay.setActionBar("§aAll 40 Waves Cleared!");
        p.playSound("random.levelup");
      }
    
    const dimension = world.getDimension("overworld");
    await runCommandsSafely([
      "clone 1022 0 -987 1022 0 -987 1014 2 -991",
      "clone 1022 0 -987 1022 0 -987 1081 -19 -1035",
      "tp @e[type=item,x=1035,y=0,z=-1014,r=200] 1012 2 -989.1",
      "tp @e[type=xp_orb,x=1035,y=0,z=-1014,r=200] @r[x=1035,y=0,z=-1014,r=200]",
      "kill @e[type=arrow,x=1035,y=0,z=-1014,r=200]"
    ]);
    return;
  }

  currentWave++;
  waveInProgress = true;
  currentWaveMobs = [];

  const dimension = world.getDimension("overworld");
  
  // === INSERT CLONE COMMANDS FOR WAVE START HERE ===
  if (currentWave === 10) {
    // When wave 10 starts:
    dimension.runCommandAsync("clone 1022 -3 -988 1022 -3 -988 1014 2 -988").catch(() => {});
    dimension.runCommandAsync("clone 1022 -3 -988 1022 -3 -988 1081 -19 -1038").catch(() => {});
  }
  else if (currentWave === 20) {
    // When wave 20 starts:
    dimension.runCommandAsync("clone 1022 -3 -989 1022 -3 -989 1014 2 -988").catch(() => {});
    dimension.runCommandAsync("clone 1022 -3 -989 1022 -3 -989 1081 -19 -1038").catch(() => {});
  }
  else if (currentWave === 30) {
    // When wave 30 starts:
    dimension.runCommandAsync("clone 1022 -3 -990 1022 -3 -990 1014 2 -988").catch(() => {});
    dimension.runCommandAsync("clone 1022 -3 -990 1022 -3 -990 1081 -19 -1038").catch(() => {});
  }
  else if (currentWave === 40) {
    // When wave 30 starts:
    dimension.runCommandAsync("clone 1023 -3 -990 1023 -3 -990 1014 2 -988").catch(() => {});
    dimension.runCommandAsync("clone 1023 -3 -990 1023 -3 -990 1081 -19 -1038").catch(() => {});
  }
  // === END INSERT ===

  // Clean up items, XP, arrows before wave starts
  await runCommandsSafely([
    "tp @e[type=item,x=1035,y=0,z=-1014,r=200] 1012 2 -989.1",
    "tp @e[type=xp_orb,x=1035,y=0,z=-1014,r=200] @r[x=1035,y=0,z=-1014,r=200]",
    "kill @e[type=arrow,x=1035,y=0,z=-1014,r=200]"
  ]);

  const waveData = waveMobs[currentWave];
  if (!waveData) return;

  const mobTypes = Object.entries(waveData);
  let spawnIndex = 0;

  for (const [mobId, count] of mobTypes) {
    for (let i = 0; i < count; i++) {
      const spawnPos = spawnLocations[Math.floor(Math.random() * spawnLocations.length)];
      try {
        const mob = dimension.spawnEntity(mobId, {
          x: spawnPos[0],
          y: spawnPos[1],
          z: spawnPos[2]
        });
        
        // Add small delay between spawns
        await system.runTimeout(() => {}, 2);
        
        await applyMobEffects(mob, currentWave);
        currentWaveMobs.push(mob);
      } catch (e) {
        console.warn(`Failed to spawn ${mobId}: ${e}`);
      }
    }
  }

  for (const p of cachedPlayersInZone) {
      p.sendMessage(`§cWave ${currentWave} incoming!`);
      p.onScreenDisplay.setActionBar(`§cWave ${currentWave}`);
      p.playSound("mob.wither.spawn");
      p.addEffect("blindness", 20, { amplifier: 0, showParticles: false });
    }
  }

async function applyMobEffects(mob, wave) {
  try {
    // Add a small delay to ensure mob is fully spawned
    await system.runTimeout(() => {}, 5);
    
    switch(wave) {
      case 21: // Speed 1 and Regeneration 1
        await Promise.all([
          mob.addEffect("speed", 999999, { amplifier: 0, showParticles: false }),
          mob.addEffect("regeneration", 999999, { amplifier: 0, showParticles: false })
        ]);
        break;
        
      case 22: // Speed 2 and Regeneration 2
        await Promise.all([
          mob.addEffect("speed", 999999, { amplifier: 1, showParticles: false }),
          mob.addEffect("regeneration", 999999, { amplifier: 1, showParticles: false }),
          mob.addEffect("strength", 999999, { amplifier: 0, showParticles: false })
        ]);
        break;
        
      case 23: // Special baby zombies/husks and effects
        if (mob.typeId === "minecraft:zombie") {
          try {
            mob.setComponent("minecraft:is_baby", true);
          } catch (e) {
            try {
              mob.triggerEvent("minecraft:as_baby");
            } catch (e2) {
              console.warn("Failed to make zombie/husk baby:", e2);
            }
          }
        } else {
          await Promise.all([
            mob.addEffect("health_boost", 999999, { amplifier: 3, showParticles: false }),
            mob.addEffect("speed", 999999, { amplifier: 1, showParticles: false }),
            mob.addEffect("regeneration", 20, { amplifier: 255, showParticles: false }),
            mob.addEffect("strength", 999999, { amplifier: 1, showParticles: false })
          ]);
        }
        break;
        
      case 24: // Speed 1, health boost 3, regen 255 for 2 sec
        if (mob.typeId === "minecraft:creeper") {
          mob.triggerEvent("minecraft:become_charged");
        }
        await Promise.all([
          mob.addEffect("speed", 999999, { amplifier: 2, showParticles: false }),
          mob.addEffect("health_boost", 999999, { amplifier: 5, showParticles: false }),
          mob.addEffect("regeneration", 40, { amplifier: 255, showParticles: false }),
          mob.addEffect("strength", 999999, { amplifier: 1, showParticles: false })
        ]);
        break;
        
      case 25: // Health boost 5, speed 2, regen 255 for 2 sec
        if (mob.typeId === "minecraft:creeper") {
          mob.triggerEvent("minecraft:become_charged");
        }
        await Promise.all([
          mob.addEffect("health_boost", 999999, { amplifier: 7, showParticles: false }),
          mob.addEffect("speed", 999999, { amplifier: 2, showParticles: false }),
          mob.addEffect("regeneration", 40, { amplifier: 255, showParticles: false }),
          mob.addEffect("strength", 999999, { amplifier: 1, showParticles: false })
        ]);
        break;
        
      case 26: // Speed 2, health boost 7, regen 255 for 2 sec
        if (mob.typeId === "minecraft:creeper") {
          mob.triggerEvent("minecraft:become_charged");
        }
        await Promise.all([
          mob.addEffect("speed", 999999, { amplifier: 2, showParticles: false }),
          mob.addEffect("health_boost", 999999, { amplifier: 8, showParticles: false }),
          mob.addEffect("regeneration", 40, { amplifier: 255, showParticles: false }),
          mob.addEffect("strength", 999999, { amplifier: 1, showParticles: false })
        ]);
        break;
        
      case 27: // Speed 2, health boost 7, regen 255 for 2 sec
        if (mob.typeId === "minecraft:creeper") {
          mob.triggerEvent("minecraft:become_charged");
        }
        await Promise.all([
          mob.addEffect("speed", 999999, { amplifier: 2, showParticles: false }),
          mob.addEffect("health_boost", 999999, { amplifier: 10, showParticles: false }),
          mob.addEffect("regeneration", 40, { amplifier: 255, showParticles: false }),
          mob.addEffect("strength", 999999, { amplifier: 2, showParticles: false })
        ]);
        break;
        
      case 28:
  if (mob.typeId === "minecraft:zombie") {
    try {
      mob.setComponent("minecraft:is_baby", true);
    } catch (e) {
      try {
        mob.triggerEvent("minecraft:as_baby");
      } catch (e2) {
        console.warn("Failed to make zombie baby in wave 28:", e2);
      }
    }
  }

  await Promise.all([
    mob.addEffect("health_boost", 999999, { amplifier: 11, showParticles: false }),
    mob.addEffect("speed", 999999, { amplifier: 2, showParticles: false }),
    mob.addEffect("regeneration", 40, { amplifier: 255, showParticles: false }),
    mob.addEffect("strength", 999999, { amplifier: 2, showParticles: false })
  ]);
  break;
        
      case 29: // Speed 2, health boost 12, regen 255 for 4 sec
        await Promise.all([
          mob.addEffect("speed", 999999, { amplifier: 3, showParticles: false }),
          mob.addEffect("health_boost", 999999, { amplifier: 13, showParticles: false }),
          mob.addEffect("regeneration", 60, { amplifier: 255, showParticles: false }),
          mob.addEffect("strength", 999999, { amplifier: 2, showParticles: false })
        ]);
        break;
        
      case 30: // Wardens and Withers don't need effects
        if (mob.typeId === "minecraft:wither_skeleton" || mob.typeId === "minecraft:breeze") {
          await Promise.all([
            mob.addEffect("speed", 999999, { amplifier: 2, showParticles: false }),
            mob.addEffect("strength", 999999, { amplifier: 1, showParticles: false })
          ]);
        }
        break;
        
        case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
case 37:
case 38:
case 39:
case 40:
  if (mob.typeId === "minecraft:warden" || mob.typeId === "minecraft:wither") {
    break; // Skip effects for these
  }

  // Make creepers charged
  if (mob.typeId === "minecraft:creeper") {
    try {
      mob.triggerEvent("minecraft:become_charged");
    } catch (e) {
      console.warn("Failed to charge creeper:", e);
    }
  }

  // Make zombies baby in wave 31 only
  if (wave === 31 && mob.typeId === "minecraft:zombie") {
    try {
      mob.setComponent("minecraft:is_baby", true);
    } catch (e) {
      try {
        mob.triggerEvent("minecraft:as_baby");
      } catch (e2) {
        console.warn("Failed to make zombie baby in wave 31:", e2);
      }
    }
  }

  await Promise.all([
    mob.addEffect("speed", 999999, { amplifier: 3, showParticles: false }),
    mob.addEffect("health_boost", 999999, { amplifier: 13, showParticles: false }),
    mob.addEffect("regeneration", 60, { amplifier: 255, showParticles: false }),
    mob.addEffect("strength", 999999, { amplifier: 2, showParticles: false })
  ]);
  break;
        
    }
  } catch (e) {
    console.warn("Failed to apply effects:", e);
  }
}

async function runCommandsSafely(commands) {
  for (const cmd of commands) {
    try {
      await world.getDimension("overworld").runCommandAsync(cmd);
      await system.run(() => {}); // Small delay between commands
    } catch (e) {
      console.warn(`Command failed: ${cmd} - ${e}`);
    }
  }
}

async function clearHostileMobsInArena() {
  const dimension = world.getDimension("overworld");
  for (const mob of dimension.getEntities({ type: "minecraft:mob", families: ["monster"] })) {
    if (isInZone(mob.location)) {
      try {
        mob.remove();
      } catch (e) {
        console.warn("Failed to kill mob:", e);
      }
    }
  }
}

function countdownToNextWave(player) {
  let countdown = 3;
  countdownId = system.runInterval(() => {
    if (!gameStarted) {
      system.clearRun(countdownId);
      countdownId = null;
      return;
    }

    if (countdown <= 0) {
      system.clearRun(countdownId);
      countdownId = null;
      startWave(player);
      return;
    }

    for (const p of cachedPlayersInZone) {
      p.onScreenDisplay.setActionBar(`§eNext Wave Starts In §c${countdown}`);
      p.playSound("random.click");
    }

    countdown--;
  }, 20);
}

system.runInterval(() => {
  const dimension = world.getDimension("overworld");
  if (!gameStarted && cachedPlayersInZone.length === 0) return;

  // === [1] Wave Completion Check ===
  if (gameStarted && waveInProgress) {
    currentWaveMobs = currentWaveMobs.filter(entity => entity.isValid());

    if (currentWaveMobs.length === 0) {
      waveInProgress = false;

      for (const p of cachedPlayersInZone) {
        p.sendMessage(`§aWave ${currentWave} Cleared!`);
        p.onScreenDisplay.setActionBar(`§aWave ${currentWave} Cleared!`);
        p.playSound("random.levelup");
      }

      if ([10, 20, 30, 40].includes(currentWave)) {
        dimension.runCommandAsync("clone 1022 0 -987 1022 0 -987 1014 2 -988").catch(() => {});
        dimension.runCommandAsync("clone 1022 0 -987 1022 0 -987 1081 -19 -1038").catch(() => {});
      }

      if (currentWave === 10) giveWaveReward(10);
      if (currentWave === 20) giveWaveReward(20);
      if (currentWave === 30) giveWaveReward(30);
      if (currentWave === 40) giveWaveReward(40);

      const anyPlayer = cachedPlayers[0];
      if (anyPlayer) countdownToNextWave(anyPlayer);
    }
  }

  // === [2] Player Tags and Game Control ===
  for (const player of cachedPlayers) {
    const tags = player.getTags();

    for (const tag of tags) {
      const match = tag.match(/^jumpToWave(\d{1,2})$/);
      if (match) {
        const waveNumber = parseInt(match[1]);
        if (waveNumber >= 1 && waveNumber <= 40) {
          player.removeTag(tag);

          cachedPlayersInZone = [];
          for (const player of cachedPlayers) {
            if (isInZone(player.location)) {
              cachedPlayersInZone.push(player);
            }
          }

          waveInProgress = false;
          gameStarted = false;
          if (countdownId !== null) {
            system.clearRun(countdownId);
            countdownId = null;
          }

          for (const p of cachedPlayersInZone) {
            p.sendMessage(`§8[§c§lAdmin§8]§r §aJumped to Wave §l${waveNumber}`);
            p.onScreenDisplay.setActionBar(`§aNow Starting Wave §l${waveNumber}`);
            p.playSound("random.orb");
          }

          for (const entity of dimension.getEntities({ families: ["monster"] })) {
            if (isInZone(entity.location)) {
              entity.remove();
            }
          }

          system.runTimeout(() => {
            for (const entity of dimension.getEntities({ type: "minecraft:item" })) {
              if (isInZone(entity.location)) {
                entity.remove();
              }
            }

            currentWave = waveNumber - 1;
            waveInProgress = false;
            gameStarted = true;
            clearHostileMobsInArena();
            startWave(player);
          }, 10);
          break;
        }
      }
    }

    if (gameStarted && currentWave > 0 && currentWave < 41 && isInZone(player.location)) {
      if (countdownId === null) {
        player.onScreenDisplay.setActionBar(`§cWave ${currentWave}`);
      }
    }

    if (player.hasTag("mobGameStart")) {
      player.removeTag("mobGameStart");

      dimension.runCommandAsync("clone 1022 -3 -987 1022 3 -987 1014 2 -991");
      dimension.runCommandAsync("clone 1022 -3 -987 1022 3 -987 1081 -19 -1035");

      currentWave = 0;
      waveInProgress = false;
      gameStarted = true;
      clearHostileMobsInArena();
      startWave(player);
    }

    if (player.hasTag("mobGameStop")) {
      player.removeTag("mobGameStop");

      currentWave = 0;
      waveInProgress = false;
      gameStarted = false;

      if (countdownId !== null) {
        system.clearRun(countdownId);
        countdownId = null;
      }

      for (const mob of dimension.getEntities({ families: ["monster"] })) {
        if (isInZone(mob.location)) {
          mob.remove();
        }
      }

      system.runTimeout(() => {
        for (const item of dimension.getEntities({ type: "minecraft:item" })) {
          if (isInZone(item.location)) {
            item.remove();
          }
        }
      }, 3);

      system.runTimeout(() => {
        runCommandsSafely([
          "clone 1022 0 -987 1022 0 -987 1014 2 -991",
          "clone 1022 0 -987 1022 0 -987 1081 -19 -1035",
          "tp @e[type=item,x=1035,y=0,z=-1014,r=200] 1012 2 -989.1",
          "tp @e[type=xp_orb,x=1035,y=0,z=-1014,r=200] @r[x=1035,y=0,z=-1014,r=200]",
          "kill @e[type=arrow,x=1035,y=0,z=-1014,r=200]"
        ]);
      }, 4);

      for (const p of cachedPlayersInZone) {
        p.sendMessage("§c§l>> §r§cPVE stopped");
        p.onScreenDisplay.setActionBar("§r§cPVE stopped");
        p.playSound("random.explode");
      }
    }
  }
}, 20);

function giveWaveReward(wave) {
  let reward = 0;
  if (wave === 10) reward = 50000;
  else if (wave === 20) reward = 100000;
  else if (wave === 30) reward = 200000;  // Updated to 150,000 for wave 30
  else if (wave === 40) reward = 300000;  // Updated to 150,000 for wave 40

  if (reward === 0) return;

  for (const player of cachedPlayers) {
    try {
      if (!isInZone(player.location)) continue;

      let moneyObjective = world.scoreboard.getObjective("Money");
      if (!moneyObjective) {
        moneyObjective = world.scoreboard.addObjective("Money", "Money");
      }

      const currentScore = moneyObjective.getScore(player) ?? 0;
      moneyObjective.setScore(player, currentScore + reward);

      player.sendMessage(`§aYou earned §a§l$${reward.toLocaleString()} §r§afor clearing §l§aWave ${wave}!`);
    } catch (e) {
      console.warn(`[Wave Reward Error @ Wave ${wave}]:`, e);
    }
  }
}