import {
  system,
  GameMode,
  world,
  EntityComponentTypes,
  EquipmentSlot,
  Player,
} from "@minecraft/server";

export function ShadowSpawnSystem(dimension, chance = 0.5, interval = 60) {
  const shadowId = "tvf_randev:shadow";

  const runId = system.runInterval(() => {
    const players = dimension.getPlayers();

    for (const player of players) {
      if (
        chance > Math.random() ||
        !player.isValid ||
        player.getGameMode() != GameMode.Survival
      )
        continue;
      const pLoc = player.location;
      let viewDir = player.getViewDirection();
      viewDir.y = 0;

      //нормализую
      const length = Math.sqrt(viewDir.x ** 2 + viewDir.z ** 2);
      viewDir.x /= length;
      viewDir.z /= length;

      const offset = 2;
      const posRaw = {
        x: pLoc.x - viewDir.x * offset,
        y: pLoc.y - viewDir.y * offset, // та же что у игрока
        z: pLoc.z - viewDir.z * offset,
      };
      try {
        const block = dimension.getBlock(posRaw);
        const block_a = block.above();
        if (block.isAir && block_a.isAir) {
          dimension.spawnEntity(shadowId, posRaw);
        }
      } catch {}
    }
  }, interval);
  return runId;
}

// Shadow Armor

const armorStates = new Map(); // key: player.name, value: "none" | "partial" | "full"

system.runInterval(() => {
  const players = world.getAllPlayers();
  const onlineIds = new Set(players.map((p) => p.id));

  for (const player of players) {
    const eq = player.getComponent(EntityComponentTypes.Equippable);
    if (!eq) continue;

    const armorSlots = [
      { slot: EquipmentSlot.Head, id: "tvf_randev:shadow_helmet" },
      { slot: EquipmentSlot.Chest, id: "tvf_randev:shadow_chestplate" },
      { slot: EquipmentSlot.Legs, id: "tvf_randev:shadow_leggings" },
      { slot: EquipmentSlot.Feet, id: "tvf_randev:shadow_boots" },
    ];

    let equippedCount = 0;
    for (const { slot, id } of armorSlots) {
      const itemStack = eq.getEquipment(slot);
      if (itemStack?.typeId === id) {
        equippedCount++;
      }
    }

    const prevState = armorStates.get(player.id) || "none";
    let newState = "none";
    if (equippedCount === 4) {
      newState = "full";
    } else if (equippedCount > 0) {
      newState = "partial";
    }

    const currentEffect = player.getEffect("speed");
    const effectMissing = !currentEffect;

    if (prevState !== newState || (newState !== "none" && effectMissing)) {
      armorStates.set(player.id, newState);

      // Снятие предыдущего эффекта
      ClearEffect(player);

      // Применение нового эффекта
      if (newState === "full") {
        FullEffect(player);
      } else if (newState === "partial") {
        PeaceEffect(player);
      }
    }
  }

  // Очистка состояний вышедших игроков
  for (const id of armorStates.keys()) {
    if (!onlineIds.has(id)) {
      armorStates.delete(id);
    }
  }
}, 10);

// Эффекты
function ClearEffect(player) {
  player.removeEffect("speed");
}

function FullEffect(player) {
  player.addEffect("speed", 20000000, { amplifier: 2 });
}

function PeaceEffect(player) {
  player.onScreenDisplay.setActionBar({
    translate: "tvf_randev.shadow_armor.message",
  });
  player.addEffect("speed", 20000000, { amplifier: 1 });
}
