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

const area = {
  x1: 1990, x2: 2010,
  y1: 0,    y2: 8,
  z1: -1983, z2: -1963
};

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 posKey(x, y, z) {
  return `${x}_${y}_${z}`;
}

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 });
  }
}

// === Radius Setup ===
const center = { x: 2000, y: 6, z: -1973 };
const radiusSq = 40 * 40;

function isInRadius(player) {
  const dx = player.location.x - center.x;
  const dy = player.location.y - center.y;
  const dz = player.location.z - center.z;
  return dx * dx + dy * dy + dz * dz <= radiusSq;
}

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


system.runInterval(() => {
  const nearbyPlayers = cachedPlayers.filter(isInRadius);
if (nearbyPlayers.length === 0 && activeBlocks.size === 0) return;

for (const player of nearbyPlayers) {
    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);

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

    const id = block.typeId;

    if (cycleColors.includes(id)) {
      addBlockToCycle(x, y, z, cycleColors.indexOf(id), true);
    } else if ((id.endsWith("_concrete") || id.endsWith("_wool")) && !cycleColors.includes(id)) {
      const key = posKey(x, y, z);
      if (!world.getDynamicProperty(key)) {
        world.setDynamicProperty(key, id);
      }
      block.setType("minecraft:lime_concrete");
      addBlockToCycle(x, y, z, 0, true);
    } else 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;
          const nKey = posKey(bx, by, bz);

          if ((nid.endsWith("_concrete") || nid.endsWith("_wool")) && !cycleColors.includes(nid)) {
            if (!world.getDynamicProperty(nKey)) {
              world.setDynamicProperty(nKey, 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);
          }
        }
      }
    }
  }

  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;
    }

    if (++state.ticks >= (state.fast ? 5 : 20)) {
      state.ticks = 0;
      state.fast = false;
      state.stage++;

      if (state.stage < cycleColors.length) {
        block.setType(cycleColors[state.stage]);
      } else {
        const propKey = posKey(x, y, z);
        const originalId = world.getDynamicProperty(propKey);
        if (originalId) {
          block.setType(originalId);
          world.setDynamicProperty(propKey, undefined);
        }
        activeBlocks.delete(key);
      }
    }
  }
}, 1);