import { world, system, Difficulty } from "@minecraft/server";

const SCOREBOARD_OBJECTIVE = "otherworldly_difficulty";
let lastDifficulty = -1;

function getAllDimensions() {
  return [
    world.getDimension("overworld"),
    world.getDimension("nether"),
    world.getDimension("the_end")
  ];
}

function setDifficultyScore(value) {
  if (value !== lastDifficulty) {
    lastDifficulty = value;
    const players = world.getPlayers();
    if (players.length > 0) {
      players[0].runCommand(`scoreboard players set difficulty ${SCOREBOARD_OBJECTIVE} ${value}`);
    }
  }
}

function giveHardcoreItem(player) {
  if (!player.hasTag("received_hardcore_book")) {
    player.runCommand("give @s dungeon:guide_book");
    player.runCommand("give @s dungeon:vampiric_amulet");
    player.addTag("received_hardcore_book");
  }
}

function clearExpertAura() {
  const players = world.getPlayers();
  for (const player of players) {
    if (player.hasTag("player_expert")) {
      player.removeTag("player_expert");
    }
  }

  for (const dimension of getAllDimensions()) {
    const mobs = dimension.getEntities({ families: ["monster"] });
    for (const mob of mobs) {
      if (mob.hasTag("otherworldly_expert")) {
        mob.removeTag("otherworldly_expert");
      }
    }
  }
}

function applyExpertAura(expertPlayers) {
  if (!expertPlayers.length) return;

  for (const player of expertPlayers) {
    const mobs = player.dimension.getEntities({
      location: player.location,
      maxDistance: 128,
      families: ["monster"]
    });

    for (const mob of mobs) {
      if (!mob.hasTag("otherworldly_expert")) {
        mob.addTag("otherworldly_expert");
      }
    }
  }
}

function updateDifficulty() {
  const players = world.getPlayers();
  if (players.length === 0) return;

  const isHardcore = world.isHardcore;
  const expertPlayers = players.filter(p => p.hasTag("player_expert"));
  const difficulty = world.getDifficulty();

  if (isHardcore) {
    setDifficultyScore(3);
    applyExpertAura(expertPlayers);
    for (const player of players) {
      if (!player.hasTag("player_expert")) {
        player.addTag("player_expert");
      }
      giveHardcoreItem(player);
    }
    return;
  }

  switch (difficulty) {
    case Difficulty.Hard:
      if (expertPlayers.length > 0) {
        setDifficultyScore(3);
        applyExpertAura(expertPlayers);
      } else {
        clearExpertAura();
        setDifficultyScore(2);
      }
      break;

    case Difficulty.Normal:
      clearExpertAura();
      setDifficultyScore(1);
      break;

    case Difficulty.Easy:
    case Difficulty.Peaceful:
      clearExpertAura();
      setDifficultyScore(0);
      break;
  }
}

// Ejecutar cada 1 segundos (100 ticks)
system.runInterval(updateDifficulty, 19);
