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

// shared/playerCache.js
export let cachedPlayers = [];

system.runInterval(() => {
  cachedPlayers = world.getPlayers();
}, 20);

const overworld = world.getDimension("overworld");

// === CONFIG ===
const LOBBY_CENTER = { x: 2000, y: 0, z: -1973 };
const GAME_CENTER = { x: 2053, y: -8, z: -1799 };
const LOBBY_RADIUS = 60;
const GAME_RADIUS = 60;

const SPAWN_LOCATIONS = [
  { x: 2057, y: -2, z: -1803 },
  { x: 2053, y: -2, z: -1805 },
  { x: 2049, y: -2, z: -1803 },
  { x: 2047, y: -2, z: -1799 },
  { x: 2049, y: -2, z: -1795 },
  { x: 2053, y: -2, z: -1793 },
  { x: 2057, y: -2, z: -1795 },
  { x: 2059, y: -2, z: -1799 },
];

const WINNER_TP = { x: 2000, y: -2, z: -1967 };
const STRUCTURE_FILL_AREA = "2068 -3 -1814 2038 2 -1784";
const STRUCTURE_LOAD_CMD = "structure load Blockdrop 2027 -17 -1825";

// === STATE ===
let lobbyCountdown = null;
let lobbyTime = 25 * 20;

let gameCountdown = null;
let gameTime = 5 * 20;
let gameStarted = false;

system.runInterval(() => {
  const players = cachedPlayers;

  // ✅ Stop everything if no player is inside LOBBY or GAME zone
  const shouldRun = players.some(p =>
    isInZone(p.location, LOBBY_CENTER, LOBBY_RADIUS) ||
    isInZone(p.location, GAME_CENTER, GAME_RADIUS)
  );
  if (!shouldRun) return;

  // 🟩 Your existing logic starts here
  const inLobby = players.filter(p => isInZone(p.location, LOBBY_CENTER, LOBBY_RADIUS));
  const inGame = players.filter(p => isInZone(p.location, GAME_CENTER, GAME_RADIUS));

  // === GAME WINNER CHECK ===
if (inGame.length === 1 && gameStarted) {
  const winner = inGame[0];
  gameStarted = false;
  const winnerName = winner.name;

  // 🧱 Step 1: Load structure immediately
  overworld.runCommandAsync(STRUCTURE_LOAD_CMD);

  // ⏳ Step 2: Delay winner actions by 5 ticks (~0.25 seconds)
  system.runTimeout(() => {
    winner.teleport(WINNER_TP, { dimension: overworld });
    winner.runCommandAsync(`execute at @s run summon fireworks_rocket`);
    winner.playSound(`random.levelup`);
    winner.runCommandAsync(`scoreboard players add @s Money 5000`);
  
    winner.sendMessage(`§aYou earned §a§l$5000!`);
    overworld.runCommandAsync(`tellraw @a {"rawtext":[{"text":"§8[§dBlock§6Drop§8] §e${winnerName} §7has won the game!"}]}`);

    resetGameCountdown();
  }, 5);
}

  // === GAME RESET IF EMPTY ===
  if (inGame.length === 0 && gameStarted) {
    resetGameCountdown();
    gameStarted = false;
  }

  // === GAME ZONE COUNTDOWN ===
if (inGame.length > 1 && !gameStarted) {
  if (!gameCountdown) {
    gameCountdown = system.runInterval(() => {
      const inGameNow = cachedPlayers.filter(p => isInZone(p.location, GAME_CENTER, GAME_RADIUS));

      if (gameTime > 0) {
        const seconds = Math.ceil(gameTime / 20);
        for (const p of inGameNow) {
          p.runCommandAsync(`titleraw @s actionbar {"rawtext":[{"text":"§aStarting in §f${seconds}s"}]}`);
          if (gameTime % 20 === 0) p.playSound(`note.harp`);
        }
        gameTime--;
      } else {
        for (const p of inGameNow) {
          p.playSound(`mob.blaze.shoot`);
          p.runCommandAsync(`titleraw @s actionbar {"rawtext":[{"text":"§a§lGO!"}]}`);
        }
        overworld.runCommandAsync(`/fill ${STRUCTURE_FILL_AREA} air replace barrier`);
        overworld.runCommandAsync(`/fill ${STRUCTURE_FILL_AREA} air replace anvil`);
        resetGameCountdown();
        gameStarted = true;
      }

    }, 1);
  }
}

  // === LOBBY SYSTEM ===
if (inLobby.length > 0 && gameStarted) {
  for (const p of inLobby) {
    p.runCommandAsync(`titleraw @s actionbar {"rawtext":[{"text":"§cGame is running please wait"}]}`);
  }
  resetLobbyCountdown();
}

else if (inLobby.length === 1 && !gameStarted && inGame.length <= 1) {
  for (const p of inLobby) {
    p.runCommandAsync(`titleraw @s actionbar {"rawtext":[{"text":"§eWaiting for 1 more player to start..."}]}`);
  }
  resetLobbyCountdown();
}

else if (inLobby.length > 1 && inLobby.length <= 8 && !gameStarted && inGame.length <= 1) {
  if (!lobbyCountdown) {
    lobbyCountdown = system.runInterval(() => {
      const inLobbyNow = cachedPlayers.filter(p => isInZone(p.location, LOBBY_CENTER, LOBBY_RADIUS));

      // ❗ Cancel if over 8 players mid-countdown
      if (inLobbyNow.length > 8) {
        for (const p of inLobbyNow) {
          p.runCommandAsync(`titleraw @s actionbar {"rawtext":[{"text":"§cMore than 8 players not supported"}]}`);
        }
        resetLobbyCountdown();
        return;
      }

      if (lobbyTime > 0) {
        const seconds = Math.ceil(lobbyTime / 20); // changed from floor to ceil
        for (const p of inLobbyNow) {
          p.runCommandAsync(`titleraw @s actionbar {"rawtext":[{"text":"§bGame starting in §f${seconds}s"}]}`);
          if (lobbyTime <= 200 && lobbyTime % 20 === 0) {
            p.playSound(`random.click`);
          }
        }
        lobbyTime--;
      } else {
        for (let i = 0; i < inLobbyNow.length; i++) {
          const loc = SPAWN_LOCATIONS[i % SPAWN_LOCATIONS.length];
          inLobbyNow[i].teleport(loc, { dimension: overworld });
        }
        resetLobbyCountdown();
        gameStarted = false;
      }

    }, 1);
  }
}

else if (inLobby.length > 8 && !gameStarted) {
  for (const p of inLobby) {
    p.runCommandAsync(`titleraw @s actionbar {"rawtext":[{"text":"§cMore than 8 players not supported"}]}`);
  }
  resetLobbyCountdown();
}

}, 20); // Runs every second

function isInZone(pos, center, radius) {
  const dx = pos.x - center.x;
  const dy = pos.y - center.y;
  const dz = pos.z - center.z;
  return dx * dx + dy * dy + dz * dz <= radius * radius;
}

function resetLobbyCountdown() {
  if (lobbyCountdown !== null) {
    system.clearRun(lobbyCountdown);
    lobbyCountdown = null;
  }
  lobbyTime = 25 * 20;
}

function resetGameCountdown() {
  if (gameCountdown !== null) {
    system.clearRun(gameCountdown);
    gameCountdown = null;
  }
  gameTime = 5 * 20;
}