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

export function initSkillSwitcher() {
  system.runInterval(() => {
    for (const player of world.getPlayers()) {
      try {
        const equippable = player.getComponent("minecraft:equippable");
        const entityData = player.getComponent("minecraft:entity_data");

        if (!equippable || !entityData) continue;

        const mainHandItem = equippable.getEquipment(EquipmentSlot.Mainhand);
        if (!mainHandItem) continue;

        const itemId = mainHandItem.typeId;
        if (!itemId.startsWith("well:cajado_mago")) continue;

        const isSneaking = player.isSneaking;
        const isUsingItem = entityData.data?.IsUsingItem ?? false;
        const attackTime = entityData.data?.AttackTime ?? 0;

        if (attackTime <= 0) continue;

        // AGACHADO
        if (isSneaking) {
          if (isUsingItem) {
            // Agachado + usando = troca de skin
            trocarSkin(player, itemId);
          } else {
            // Só agachado = troca de skill
            trocarSkill(player);
          }
        }
      } catch (e) {
        console.warn(`Erro no skillSwitcher: ${e}`);
      }
    }
  }, 5);
}

function trocarSkill(player) {
  player.runCommandAsync(`scoreboard players add @s skill_ataque 1`);
  player.runCommandAsync(`execute as @s[scores={skill_ataque=2..}] run scoreboard players set @s skill_ataque 0`);
  player.runCommandAsync(`titleraw @s actionbar {"rawtext":[{"text":"§dSkill Trocada!"}]}`);
}

function trocarSkin(player, itemIdAtual) {
  const ordemCajados = [
    "well:cajado_mago",
    "well:cajado_mago2",
    "well:cajado_mago3",
    "well:cajado_mago4",
    "well:cajado_mago5",
  ];

  const indexAtual = ordemCajados.indexOf(itemIdAtual);
  if (indexAtual === -1) return;

  const proximoCajado = ordemCajados[(indexAtual + 1) % ordemCajados.length];
  //player.runCommandAsync(`replaceitem entity @s slot.weapon.mainhand ${proximoCajado}`);
  player.runCommandAsync(`titleraw @s actionbar {"rawtext":[{"text":"§bSkin Trocada!"}]}`);
}
