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

// Mapea cada ítem a su función de luz correspondiente
const lightLevels = {
  15: ["minecraft:beacon", "minecraft:campfire", "dungeon:fire_stick", "minecraft:froglight", "minecraft:glowstone", "minecraft:lantern", "minecraft:lava_bucket", "minecraft:lit_pumpkin", "minecraft:sea_lantern", "minecraft:shroomlight"],
  12: ["minecraft:candle", "minecraft:torch","minecraft:copper_torch", "minecraft:soul_campfire", "minecraft:nether_star", "minecraft:soul_lantern"],
  10: ["minecraft:crying_obsidian", "minecraft:glow_lichen", "minecraft:soul_torch"],
  9:  ["minecraft:catalyst", "minecraft:enchanting_table", "minecraft:ender_chest", "minecraft:totem_of_undying"],
  7:  ["minecraft:blaze_powder", "minecraft:blaze_rod", "minecraft:experience_bottle","minecraft:redstone_torch", "minecraft:glow_berries", "minecraft:glow_ink_sac", "minecraft:glowstone_dust", "minecraft:magma"],
};

// Construir mapa de ítems a comandos sólo una vez
const itemCommandMap = new Map();
for (const [level, items] of Object.entries(lightLevels)) {
  const cmd = `execute as @s positioned ~ ~1 ~ run function light${level}`;
  for (const item of items) {
    itemCommandMap.set(item, cmd);
  }
}

const INTERVAL_TICKS = 2;

system.runInterval(() => {
  for (const player of world.getPlayers()) {
    // Obtener el ítem en mano principal solo una vez
    const equipComp = player.getComponent(EntityEquippableComponent.componentId);
    const mainHand = equipComp?.getEquipment(EquipmentSlot.Mainhand);
    const itemId = mainHand?.typeId;

    // Salida rápida si no sostiene nada relevante
    if (!itemId || !itemCommandMap.has(itemId)) {
      if (player.hasTag("mainhand") && !player.hasTag("offhand")) {
        player.removeTag("mainhand");
        player.runCommand("function no_light");
      }
      continue;
    }

    // Si sostiene un ítem de luz, aplica función sólo si no tiene luz secundaria
    if (!player.hasTag("offhand")) {
      if (!player.hasTag("mainhand")) player.addTag("mainhand");
      player.runCommand(itemCommandMap.get(itemId));
    }
  }
}, INTERVAL_TICKS);
