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

const area = {
  x1: 2025, x2: 2081,
  y1: -17, y2: 0,
  z1: -1827, z2: -1771
};

const originalBlocks = new Set([
  "minecraft:blue_concrete", "minecraft:cyan_concrete", "minecraft:light_blue_concrete",
  "minecraft:blue_wool", "minecraft:cyan_wool", "minecraft:light_blue_wool",
  "minecraft:gray_concrete"
]);

const cycleColors = [
  "minecraft:lime_concrete",
  "minecraft:yellow_concrete",
  "minecraft:orange_concrete",
  "minecraft:red_concrete"
];

const activeBlocks = new Map(); // key: "x,y,z" => { stage, ticks, fast }

function inArea(x, y, z) {
  return x >= area.x1 && x <= area.x2 &&
         y >= area.y1 && y <= area.y2 &&
         z >= area.z1 && z <= area.z2;
}

function addBlockToCycle(x, y, z, stage = 0, fast = false) {
  const key = `${x},${y},${z}`;
  const existing = activeBlocks.get(key);
  if (existing) {
    existing.fast = true;
  } else {
    activeBlocks.set(key, { stage, ticks: 0, fast });
  }
}

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


system.runInterval(() => {
  const playersInArea = cachedPlayers.filter(p => {
  const x = Math.floor(p.location.x);
  const y = Math.floor(p.location.y - 1);
  const z = Math.floor(p.location.z);
  return inArea(x, y, z);
});

if (playersInArea.length < 2 && activeBlocks.size === 0) return;

  for (const player of playersInArea) {
    const px = player.location.x;
    const py = player.location.y;
    const pz = player.location.z;

    const x = Math.floor(px);
    const y = Math.floor(py - 1);
    const z = Math.floor(pz);

    if (!inArea(x, y, z)) continue;

    const block = dim.getBlock({ x, y, z });
    if (!block) continue;

    const id = block.typeId;

    if (originalBlocks.has(id)) {
      block.setType("minecraft:lime_concrete");
      addBlockToCycle(x, y, z, 0, true);
      continue;
    }

    if (cycleColors.includes(id)) {
      addBlockToCycle(x, y, z, cycleColors.indexOf(id), true);
    }

    if (id === "minecraft:air") {
      for (let dx of [-0.3, 0, 0.3]) {
        for (let dz of [-0.3, 0, 0.3]) {
          const bx = Math.floor(px + dx);
          const by = Math.floor(py - 0.5);
          const bz = Math.floor(pz + dz);

          if (!inArea(bx, by, bz)) continue;

          const nearBlock = dim.getBlock({ x: bx, y: by, z: bz });
          if (!nearBlock) continue;

          const nid = nearBlock.typeId;

          if (originalBlocks.has(nid)) {
            nearBlock.setType("minecraft:lime_concrete");
            addBlockToCycle(bx, by, bz, 0, true);
          } else if (cycleColors.includes(nid)) {
            addBlockToCycle(bx, by, bz, cycleColors.indexOf(nid), true);
          }
        }
      }
    }
  }

  // ✅ Cycle update logic
  for (const [key, state] of activeBlocks) {
    const [x, y, z] = key.split(',').map(Number);
    const block = dim.getBlock({ x, y, z });
    if (!block) {
      activeBlocks.delete(key);
      continue;
    }

    const currentId = block.typeId;
    const expectedId = cycleColors[state.stage];

    const match = (expectedId === currentId) ||
                  (state.stage === 0 && currentId === "minecraft:lime_concrete");

    if (!match || !cycleColors.includes(currentId)) {
      activeBlocks.delete(key);
      continue;
    }

    state.ticks++;
    const interval = state.fast ? 5 : 20;

    if (state.ticks >= interval) {
      state.ticks = 0;
      state.stage++;
      state.fast = false;

      if (state.stage < cycleColors.length) {
        block.setType(cycleColors[state.stage]);
      } else {
        block.setType("minecraft:air");
        activeBlocks.delete(key);
      }
    }
  }
}, 1); // Runs every tick (unchanged)