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

/* =====================================================
   FUNÇÃO SEGURA PRA PEGAR SCORE
===================================================== */
function getScoreSafe(player, objectiveName) {
  try {
    const obj = world.scoreboard.getObjective(objectiveName);
    if (!obj) return 0;
    const score = obj.getScore(player);
    return score ?? 0;
  } catch {
    return 0;
  }
}

/* =====================================================
   CONTROLE ANTI-LAG (cooldowns)
===================================================== */
// guarda quando cada efeito foi aplicado
const effectCooldown = new Map();
// reaplica a cada 5s
const REAPPLY_DELAY = 100;
// duração do efeito 7s
const EFFECT_DURATION = 140;

/* =====================================================
   CONFIG
===================================================== */
const ARMOR_PENALTIES = {
  diamond: {
    score: "armadura_dima",
    mobObjective: "skeleton",
    bar: "barra.trinta",
    items: [
      "minecraft:diamond_helmet",
      "minecraft:diamond_chestplate",
      "minecraft:diamond_leggings",
      "minecraft:diamond_boots"
    ]
  },
  gold: {
    score: "armadura_ouro",
    mobObjective: "bruxa",
    bar: "barra.dez",
    items: [
      "minecraft:golden_helmet",
      "minecraft:golden_chestplate",
      "minecraft:golden_leggings",
      "minecraft:golden_boots"
    ]
  },
  iron: {
    score: "armadura_ferro",
    mobObjective: "zumbi",
    bar: "barra.vinte",
    items: [
      "minecraft:iron_helmet",
      "minecraft:iron_chestplate",
      "minecraft:iron_leggings",
      "minecraft:iron_boots"
    ]
  },
  chainmail: {
    score: "armadura_malha",
    mobObjective: "aranha",
    bar: "barra.dez",
    items: [
      "minecraft:chainmail_helmet",
      "minecraft:chainmail_chestplate",
      "minecraft:chainmail_leggings",
      "minecraft:chainmail_boots"
    ]
  },
  netherite: {
    score: "armadura_neterita",
    mobObjective: "enderman",
    bar: "barra.trinta",
    items: [
      "minecraft:netherite_helmet",
      "minecraft:netherite_chestplate",
      "minecraft:netherite_leggings",
      "minecraft:netherite_boots"
    ]
  },
  divina: {
    score: "armadura_divina",
    mobObjective: "skeleton",
    bar: "barra.cinquenta",
    items: ["well:armadura_divina"]
  }
};

const TOOL_PENALTIES = {
  stone: { score: "itens_pedra", key: "niveis.ferramentas.pedra.actionbar" },
  gold: { score: "itens_ouro", key: "niveis.ferramentas.ouro.actionbar" },
  iron: { score: "itens_ferro", key: "niveis.ferramentas.ferro.actionbar" },
  diamond: { score: "itens_diamante", key: "niveis.ferramentas.diamante.actionbar" },
  netherite: { score: "itens_neterita", key: "niveis.ferramentas.netherite.actionbar" }
};

/* =====================================================
   CHECAR ARMADURA
===================================================== */
function hasAnyArmorPiece(player, itemIds) {
  try {
    const equip = player.getComponent("minecraft:equippable");
    if (!equip) return false;
    const armorSlots = [
      EquipmentSlot.Head,
      EquipmentSlot.Chest,
      EquipmentSlot.Legs,
      EquipmentSlot.Feet
    ];
    for (const slot of armorSlots) {
      const item = equip.getEquipment(slot);
      if (item && itemIds.includes(item.typeId)) return true;
    }
  } catch {}
  return false;
}

/* =====================================================
   PENALIDADES (ANTI SPAM)
===================================================== */
function applyArmorPenalty(player, mob, bar) {
  const id = player.id + "_armor";
  const now = system.currentTick;
  const last = effectCooldown.get(id) ?? 0;
  if (now - last < REAPPLY_DELAY) return;
  effectCooldown.set(id, now);
  player.addEffect("slowness", EFFECT_DURATION, { amplifier: 7, showParticles: false });
  player.onScreenDisplay.setActionBar({
    rawtext: [
      { translate: "insuficiente_level.text.armadura" },
      { text: "\n" },
      { translate: `entity.${mob}.death` },
      { text: " " },
      { score: { name: "@s", objective: mob } },
      { translate: bar }
    ]
  });
}

function applyToolPenalty(player, key) {
  const id = player.id + "_tool";
  const now = system.currentTick;
  const last = effectCooldown.get(id) ?? 0;
  if (now - last < REAPPLY_DELAY) return;
  effectCooldown.set(id, now);
  player.addEffect("weakness", EFFECT_DURATION, { amplifier: 40, showParticles: false });
  player.addEffect("mining_fatigue", EFFECT_DURATION, { amplifier: 40, showParticles: false });
  player.onScreenDisplay.setActionBar({
    rawtext: [
      { translate: "insuficiente_level.text.ferramenta" },
      { text: "\n" },
      { translate: key }
    ]
  });
}

/* =====================================================
   LOOP PRINCIPAL OTIMIZADO
===================================================== */
system.runInterval(() => {
  for (const player of world.getAllPlayers()) {
    /* ARMADURAS */
    for (const data of Object.values(ARMOR_PENALTIES)) {
      if (!hasAnyArmorPiece(player, data.items)) continue;
      if (getScoreSafe(player, data.score) === 0) {
        applyArmorPenalty(player, data.mobObjective, data.bar);
      }
    }

    /* MAIN HAND SAFE */
    let mainHand = null;
    try {
      const equip = player.getComponent("minecraft:equippable");
      if (equip) mainHand = equip.getEquipment(EquipmentSlot.Mainhand)?.typeId ?? null;
    } catch {}
    if (!mainHand) continue;

    /* FERRAMENTAS */
    for (const [material, data] of Object.entries(TOOL_PENALTIES)) {
      if (!mainHand.includes(material)) continue;
      if (getScoreSafe(player, data.score) === 0) {
        applyToolPenalty(player, data.key);
      }
    }

    /* ESPADA DIVINA */
    if (mainHand === "well:espada_divina" && getScoreSafe(player, "espada_divina") === 0) {
      const id = player.id + "_divine";
      const now = system.currentTick;
      const last = effectCooldown.get(id) ?? 0;
      if (now - last >= REAPPLY_DELAY) {
        effectCooldown.set(id, now);
        player.addEffect("weakness", EFFECT_DURATION, { amplifier: 40, showParticles: false });
        player.onScreenDisplay.setActionBar({
          rawtext: [
            { translate: "insuficiente_level.text.ferramenta" },
            { text: "\n" },
            { translate: "niveis.ferramentas.divina.actionbar" }
          ]
        });
      }
    }

    // =============================================
    //    ADIÇÃO: LIBERAÇÃO COM BASE NA BARRA DE XP REAL
    // =============================================

    const xpLevel = player.level;  // Nível real da barra de XP (barrinha verde)

    // Distância máxima para detecção (equivalente ao r=8 nos comandos)
    const nearby = player.dimension.getPlayers({
      location: player.location,
      maxDistance: 8
    });

    for (const p of nearby) {
      const pScore = (obj) => getScoreSafe(p, obj);
      const pXpLevel = p.level;

      // Liberação de ferramentas pela barra de XP
      const toolUnlocks = [
        { minXp: 5,  score: "itens_pedra",    msg: "equipamento.level.adquirido.pedra"    },
        { minXp: 10, score: "itens_ouro",      msg: "equipamento.level.adquirido.ouro"     },
        { minXp: 15, score: "itens_ferro",     msg: "equipamento.level.adquirido.ferro"    },
        { minXp: 20, score: "itens_diamante",  msg: "equipamento.level.adquirido.diamante" },
        { minXp: 25, score: "itens_neterita",  msg: "equipamento.level.adquirido.netherite"}
      ];

      for (const unlock of toolUnlocks) {
        if (pXpLevel >= unlock.minXp && pScore(unlock.score) === 0) {
          p.runCommand(`scoreboard players add @s ${unlock.score} 1`);
          p.onScreenDisplay.setActionBar({ translate: unlock.msg });
          p.onScreenDisplay.setTitle({ translate: "up.equipamento" });
          p.onScreenDisplay.setSubtitle({ translate: "subtitle.up.equipamento" });
          p.dimension.runCommand(`tellraw @a {"rawtext":[{"selector":"@s[r=5,c=1]"},{"translate":"missao.concluida.mensagem.publica.equipamento.${unlock.msg.split('.').pop()}"}]}`);
          p.playSound("missioncomplete");
          p.runCommand(`scoreboard players add @s ${unlock.score} 1`);  // avança para 2 = liberado
        }
      }

      // Espada Divina pela barra de XP (exemplo: nível 30)
      if (pXpLevel >= 30 && pScore("espada_divina") === 0) {
        p.runCommand("scoreboard players add @s espada_divina 1");
        p.onScreenDisplay.setActionBar({ translate: "equipamento.level.adquirido.divino" });
        p.onScreenDisplay.setTitle({ translate: "up.equipamento" });
        p.onScreenDisplay.setSubtitle({ translate: "subtitle.up.equipamento" });
        p.dimension.runCommand(`tellraw @a {"rawtext":[{"selector":"@s[r=5,c=1]"},{"translate":"missao.concluida.mensagem.publica.equipamento.divino"}]}`);
        p.playSound("missioncomplete");
        p.runCommand("scoreboard players add @s espada_divina 2");
      }
    }
  }
}, 20);

console.warn("§a[Sistema] Penalidades de equipamentos OTIMIZADAS carregadas!");