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

const insmiblocks = [
  "minecraft:allium",
  "minecraft:acacia_sapling",
  "minecraft:azalea",
  "minecraft:beetroot",
  "minecraft:birch_sapling",
  "minecraft:blue_orchid",
  "minecraft:brain_coral",
  "minecraft:brain_coral_fan",
  "minecraft:brown_mushroom",
  "minecraft:bubble_coral",
  "minecraft:bubble_coral_fan",
  "minecraft:cave_vines_body_with_berries",
  "minecraft:cave_vines_head_with_berries",
  "minecraft:carrots",
  "minecraft:cherry_sapling",
  "minecraft:cornflower",
  "minecraft:crimson_fungus",
  "minecraft:crimson_roots",
  "minecraft:darkoak_sapling",
  "minecraft:dead_brain_coral",
  "minecraft:dead_brain_coral_fan",
  "minecraft:dead_bubble_coral",
  "minecraft:dead_bubble_coral_fan",
  "minecraft:dead_fire_coral",
  "minecraft:dead_fire_coral_fan",
  "minecraft:dead_horn_coral",
  "minecraft:dead_horn_coral_fan",
  "minecraft:dead_tube_coral",
  "minecraft:dead_tube_coral_fan",
  "minecraft:deadbush",
  "minecraft:decorated_pot",
  "minecraft:end_rod",
  "minecraft:fern",
  "minecraft:fire_coral",
  "minecraft:fire_coral_fan",
  "minecraft:flower_pot",
  "minecraft:flowering_azalea",
  "minecraft:frog_spawn",
  "minecraft:hanging_roots",
  "minecraft:honey_block",
  "minecraft:horn_coral",
  "minecraft:horn_coral_fan",
  "minecraft:jungle_sapling",
  "minecraft:large_fern",
  "minecraft:lilac",
  "minecraft:lily_of_the_valley",
  "minecraft:melon_stem",
  "minecraft:nether_wart",
  "minecraft:oak_sapling",
  "minecraft:orange_tulip",
  "minecraft:oxeye_daisy",
  "minecraft:peony",
  "minecraft:pink_petals",
  "minecraft:pink_tulip",
  "minecraft:pitcher_plant",
  "minecraft:poppy",
  "minecraft:potatoes",
  "minecraft:powered_comparator",
  "minecraft:powered_repeater",
  "minecraft:reeds",
  "minecraft:red_mushroom",
  "minecraft:red_tulip",
  "minecraft:redstone_torch",
  "minecraft:redstone_wire",
  "minecraft:rose_bush",
  "minecraft:scaffolding",
  "minecraft:seagrass",
  "minecraft:short_grass",
  "minecraft:slime",
  "minecraft:small_dripleaf",
  "minecraft:soul_torch",
  "minecraft:spruce_sapling",
  "minecraft:spore_blossom",
  "minecraft:sunflower",
  "minecraft:sweet_berry_bush",
  "minecraft:tall_grass",
  "minecraft:tnt",
  "minecraft:torch",
  "minecraft:torchflower",
  "minecraft:trip_wire",
  "minecraft:tripwire_hook",
  "minecraft:tube_coral",
  "minecraft:tube_coral_fan",
  "minecraft:twisting_vines",
  "minecraft:unpowered_comparator",
  "minecraft:unpowered_repeater",
  "minecraft:warped_fungus",
  "minecraft:warped_roots",
  "minecraft:waterlily",
  "minecraft:weeping_vines",
  "minecraft:wheat",
  "minecraft:white_tulip",
  "minecraft:wither_rose",
  "minecraft:yellow_flower",
];

export function damageitem(unbreakingLevel) {
  return 1 / (1 + (unbreakingLevel == undefined ? 0 : unbreakingLevel)) >= Math.random();
}

export function instantmine(blockIdentifier) {
  return insmiblocks.includes(blockIdentifier);
}

export function redura(entity, itemStack, damageAmount) {
  const durability = itemStack.getComponent("minecraft:durability");
  const inventory = entity.getComponent("minecraft:inventory").container;

  if (durability.damage + damageAmount >= durability.maxDurability) {
    inventory.setItem(entity.selectedSlotIndex, undefined);
    entity.playSound("random.break");
    return;
  }

  durability.damage += damageAmount;
  inventory.setItem(entity.selectedSlotIndex, itemStack);
}

world.beforeEvents.worldInitialize.subscribe((initEvent) => {
  // Register custom consumables
  initEvent.itemComponentRegistry.registerCustomComponent("dungeon:glimmerite_hammer", {
    onUse: ({ source }) => {
      source.runCommandAsync(`effect @s[r=6] absorption 20 0 false`);
      source.runCommandAsync(`effect @a[r=6] regeneration 10 0 false`);

    }
  });
  initEvent.itemComponentRegistry.registerCustomComponent("dungeon:cloud_staff", {
    onUse: ({ source }) => {
      source.runCommandAsync(`execute if entity @s[lm=5] run playsound random.bow @a[r=8] ~ ~ ~ 0.5 1.35`);
      source.runCommandAsync(`execute if entity @s[lm=5] run summon dungeon:minion_cloud`);
      source.runCommandAsync(`execute unless entity @s[lm=5] run titleraw @s actionbar {"rawtext":[{"translate":"dungeon.langcode.xp"}]}`);

    }
  });
  initEvent.itemComponentRegistry.registerCustomComponent("dungeon:gauntlet", {
    onUse: ({ source }) => {
      source.runCommandAsync(`clear @s dungeon:gauntlet 0 1`);
      source.runCommandAsync(`effect @s strength 240 2 true`);
      source.runCommandAsync(`execute at @s run playsound mob.wither.spawn @s[r=4] ~~~ 1 0.4`);
      source.runCommandAsync(`effect @s slowness 240 0 true`);
    }
  });
  initEvent.itemComponentRegistry.registerCustomComponent("dungeon:lumiboth_bag", {
    onUse: ({ source }) => {
      source.runCommandAsync(`clear @s dungeon:lumiboth_bag 0 1`);
      source.runCommandAsync(`effect @s absorption 120 6 false`);
      source.runCommandAsync(`tag @s add difficulty_phase3`);
      source.runCommandAsync(`execute at @s run playsound mob.wither.spawn @s[r=4] ~~~ 1 0.4`);
      source.runCommandAsync(`summon dungeon:lumimoth ~ ~ ~ ~ ~ minecraft:tamed_moth`);
      source.runCommandAsync(`give @s dungeon:flyswatter 1`);
      source.runCommandAsync(`give @s dungeon:titanium_ore_item 1`);
      source.runCommandAsync(`give @s dungeon:chitin 10`);
    }
  });
  initEvent.itemComponentRegistry.registerCustomComponent("dungeon:bone_bag", {
    onUse: ({ source }) => {
      source.runCommandAsync(`clear @s dungeon:bone_bag 0 1`);
      source.runCommandAsync(`effect @s absorption 120 2 false`);
      source.runCommandAsync(`tag @s add difficulty_phase1`);
      source.runCommandAsync(`execute at @s run playsound mob.wither.spawn @s[r=4] ~~~ 1 0.4`);
      source.runCommandAsync(`give @s dungeon:harrotrophy_hard`);
      source.runCommandAsync(`give @s dungeon:ancient_battleaxe`);
      source.runCommandAsync(`give @s dungeon:ancient_skull 4`);
      source.runCommandAsync(`give @s dungeon:bone 32`);
    }
  });
  initEvent.itemComponentRegistry.registerCustomComponent("dungeon:pumpking_bag", {
    onUse: ({ source }) => {
      source.runCommandAsync(`clear @s dungeon:pumpking_bag 0 1`);
      source.runCommandAsync(`effect @s absorption 120 2 false`);
      source.runCommandAsync(`tag @s add difficulty_phase1`);
      source.runCommandAsync(`give @s dungeon:pumpkintrophy_hard`);
      source.runCommandAsync(`execute at @s run playsound mob.wither.spawn @s`);
      source.runCommandAsync(`give @s dungeon:fire_stick`);
      source.runCommandAsync(`give @s dungeon:pumpkin_charge 4 0`);
      source.runCommandAsync(`give @s minecraft:zombie_horse_spawn_egg`);
    }
  });
  initEvent.itemComponentRegistry.registerCustomComponent("dungeon:magic_bag", {
    onUse: ({ source }) => {
      source.runCommandAsync(`clear @s dungeon:magic_bag 0 1`);
      source.runCommandAsync(`give @s dungeon:silvirum_pickaxe`);
      source.runCommandAsync(`tag @s add difficulty_phase2`);
      source.runCommandAsync(`give @s dungeon:soultrophy_hard`);
      source.runCommandAsync(`effect @s absorption 120 4 false`);
      source.runCommandAsync(`execute at @s run playsound mob.wither.spawn @s`);
    }
  });
  initEvent.itemComponentRegistry.registerCustomComponent("dungeon:ultimate_heart", {
    onUse: ({ source }) => {
      source.runCommandAsync(`scoreboard objectives add testh2 dummy`);
      source.runCommandAsync(`titleraw @s[scores={testh=0..5}] actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.heart2\"}]}`);
      source.runCommandAsync(`effect @s[scores={testh=6..}] regeneration 10 0 false`);
      source.runCommandAsync(`scoreboard players add @s[scores={testh=6..}] testh2 1`);
      source.runCommandAsync(`effect @s[tag=hp14] regeneration 10 1`);
      source.runCommandAsync(`execute at @s run playsound beacon.ambient @a[scores={testh=6..},r=1]`);
      source.runCommandAsync(`clear @s[scores={testh=6..}] dungeon:ultimate_heart 0 1`);
    }
  });
  initEvent.itemComponentRegistry.registerCustomComponent("dungeon:heart", {
    onUse: ({ source }) => {
      source.runCommandAsync(`scoreboard objectives add testh dummy`);
      source.runCommandAsync(`scoreboard players add @s testh 0`);
      source.runCommandAsync(`effect @s[scores={testh=0..2}] regeneration 4 0  false`);
      source.runCommandAsync(`titleraw @s[scores={testh=6..}] actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.heart\"}]}`);
      source.runCommandAsync(`scoreboard players add @s[scores={testh=0..6}] testh 1`);
      source.runCommandAsync(`effect @s[scores={testh=3..5}] regeneration 2 0`);
      source.runCommandAsync(`execute at @s[scores={testh=0..5}] run playsound mob.wither.spawn @a[r=2]`);
      source.runCommandAsync(`clear @s[scores={testh=0..6}] dungeon:heart 0 1`);

    }
  });
  initEvent.itemComponentRegistry.registerCustomComponent("dungeon:skull", {
    onUse: ({ source }) => {
      source.runCommandAsync(`function harrotext`);
      source.runCommandAsync(`summon dungeon:harrowing ~-5 ~-4 ~5`);
      source.runCommandAsync(`clear @s dungeon:skull 0 1`);
    }
  });
  initEvent.itemComponentRegistry.registerCustomComponent("dungeon:lumimoth_boss", {
    onUse: ({ source }) => {
      source.runCommandAsync(`function lumimoth_boss`);
      source.runCommandAsync(`summon dungeon:lumimoth ~ ~-3 ~ ~ ~ minecraft:entity_spawned`);
      source.runCommandAsync(`clear @s dungeon:lumimoth_boss 0 1`);
    }
  });
  initEvent.itemComponentRegistry.registerCustomComponent("dungeon:spine", {
    onUse: ({ source }) => {
      source.runCommandAsync(`function braintext`);
      source.runCommandAsync(`summon zombie_horse ~-4 ~ ~ ~ ~ minecraft:event_pumpkin Ridle`);
      source.runCommandAsync(`clear @s dungeon:pumpkin_boss 0 1`);
    }
  });
  initEvent.itemComponentRegistry.registerCustomComponent("dungeon:bone_relic", {
    onUse: ({ source }) => {
      source.runCommandAsync(`effect @s resistance 240 1 true`);
      source.runCommandAsync(`effect @s slowness 240 0 true`);
      source.runCommandAsync(`execute at @s run playsound mob.wither.spawn @a[r=4]`);
      source.runCommandAsync(`clear @s dungeon:bone_relic 0 1`);
    }
  });
  initEvent.itemComponentRegistry.registerCustomComponent("dungeon:petrifyn", {
    onUse: ({ source }) => {
      source.runCommandAsync(`tag @s[tag=!stone] add stone_player`);
      source.runCommandAsync(`effect @s regeneration 8 3 true`);
      source.runCommandAsync(`scoreboard objectives add stonetest dummy`);
      source.runCommandAsync(`scoreboard players reset @s stonetest`);
      source.runCommandAsync(`effect @e[family=monster,r=6] slowness 10 255 false`);
    }
  });
  initEvent.itemComponentRegistry.registerCustomComponent("dungeon:cobalt_hammer", {
    onUse: ({ source }) => {
      source.runCommandAsync(`tp @e[type=item,c=4,r=14] @s`);
      source.runCommandAsync(`effect @e[family=mob,r=4] weakness 10 2 false`);

    }
  });
  initEvent.itemComponentRegistry.registerCustomComponent("dungeon:punisher", {
    onUse: ({ source }) => {
      source.runCommandAsync(`execute if entity @s[lm=5] run playsound mob.wither.spawn @s ~ ~ ~ 0.5 1.35`);
      source.runCommandAsync(`execute if entity @s[lm=5] run titleraw @s actionbar {"rawtext":[{"translate":"dungeon.langcode.minion"}]}`);
      source.runCommandAsync(`execute if entity @s[lm=5] run summon dungeon:minion_skull`);
      source.runCommandAsync(`xp -5l @s[lm=5]`);
      source.runCommandAsync(`execute unless entity @s[lm=5] run titleraw @s actionbar {"rawtext":[{"translate":"dungeon.langcode.xp"}]}`);

    }
  });
  initEvent.itemComponentRegistry.registerCustomComponent("otherworldly_winter:food", {
    onConsume: ({ itemStack, source }) => {
      switch (itemStack.typeId) {
        case "dungeon:bandage":
          source.addEffect("instant_health", TicksPerSecond * 0.1, { amplifier: 0 });
          break;
        case "dungeon:hunter_potion": {
          source.runCommandAsync(`playsound random.orb @s ~ ~ ~ 1 1.5`);

          const HUNTER_DURATION = TicksPerSecond * 120;
          const startTime = system.currentTick;

          const interval = system.runInterval(() => {
            if (system.currentTick - startTime >= HUNTER_DURATION) {
              system.clearRun(interval);
              return;
            }

            const nearbyEntities = source.dimension.getEntities({
              location: source.location,
              maxDistance: 48,
              families: ["monster"],
              excludeTags: ["hunter_exempt"]
            });

            for (const mob of nearbyEntities) {
              const { x: mobX, y: mobY, z: mobZ } = mob.location;
              const { x: playerX, y: playerY, z: playerZ } = source.location;

              // Número de partículas intermedias entre el jugador y el mob
              const particleCount = 10;

              // Calculamos los puntos intermedios entre el jugador y el mob
              for (let i = 1; i <= particleCount; i++) {
                const t = i / particleCount;

                // Interpolamos las coordenadas entre el jugador y el mob
                const x = playerX + (mobX - playerX) * t;
                const y = playerY + (mobY - playerY) * t + 1.2; // Añadimos altura para las partículas
                const z = playerZ + (mobZ - playerZ) * t;

                // Generamos la partícula en la posición intermedia
                source.dimension.spawnParticle("minecraft:redstone_wire_dust_particle", { x, y, z });
              }
            }
          }, TicksPerSecond * 0.5); // cada 0.5 segundos

          break;
        }
        case "dungeon:teleport_potion": {
          const dimension = source.dimension;
          const center = source.location;
          const maxRadius = 1000;

          // Generar una posición aleatoria dentro del círculo
          function getRandomXZ(center, radius) {
            const angle = Math.random() * 2 * Math.PI;
            const r = Math.sqrt(Math.random()) * radius;
            const x = Math.floor(center.x + r * Math.cos(angle));
            const z = Math.floor(center.z + r * Math.sin(angle));
            return { x, z };
          }

          // Elegir coordenadas aleatorias XZ y Y fija dentro de rango seguro
          const { x, z } = getRandomXZ(center, maxRadius);
          const y = Math.floor(Math.random() * (70 - (-50) + 1)) + (-50); // Rango de -50 a 70

          const destination = { x: x + 0.5, y: y, z: z + 0.5 };

          // Ejecutar efectos y teletransportar
          source.runCommandAsync(`playsound mob.endermen.portal @s ~ ~ ~ 1 1.3`);
          source.teleport(destination, {
            dimension,
            rotation: source.rotation,
            keepVelocity: false,
          });

          break;
        }
        case "dungeon:levitation_potion":
          source.addEffect("levitation", TicksPerSecond * 10, { amplifier: 10 });
          break;
        case "dungeon:return_potion":
          // Obtener el punto de aparición del jugador
          const spawnPoint = source.getSpawnPoint(); // Método para obtener el punto de aparición
          if (spawnPoint) {
            const { x, y, z } = spawnPoint; // Extraer coordenadas del punto de aparición

            source.runCommandAsync(`playsound mob.shulker.teleport @s ~ ~ ~ 1 1.2`);
            // Teletransportar al jugador al punto de aparición
            source.teleport({ x, y, z }, {
              dimension: source.dimension, // Utiliza la dimensión actual del jugador
              rotation: source.rotation, // Mantener orientación
              keepVelocity: false, // Detener movimiento
            });
          } else {
            // Mensaje al jugador si no tiene un punto de aparición configurado
            source.runCommandAsync("titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.return_potion\"}]}");
          }
          break;
        case "dungeon:haste_potion2":
          source.addEffect("haste", TicksPerSecond * 90, { amplifier: 2 });
          break;
        case "dungeon:haste_potion":
          source.addEffect("haste", TicksPerSecond * 180, { amplifier: 1 });
          break;
        case "dungeon:poison_inmunity":
          source.runCommandAsync(`tag @s add poison_inmunity`);
          source.runCommandAsync(`execute at @s run playsound mob.wither.spawn @a[r=4]`);
          break;
        case "dungeon:wither_inmunity":
          source.runCommandAsync(`tag @s add wither_inmunity`);
          source.runCommandAsync(`execute at @s run playsound mob.wither.spawn @a[r=4]`);
          break;
        case "dungeon:mining_fatigue_inmunity":
          source.runCommandAsync(`tag @s add fatigueinmunity`);
          source.runCommandAsync(`execute at @s run playsound mob.wither.spawn @a[r=4]`);
          break;
        case "dungeon:weakness_inmunity":
          source.runCommandAsync(`tag @s add weakness_inmunity`);
          source.runCommandAsync(`execute at @s run playsound mob.wither.spawn @a[r=4]`);
          break;
        case "dungeon:slowness_inmunity":
          source.runCommandAsync(`tag @s add slowness_inmunity`);
          source.runCommandAsync(`execute at @s run playsound mob.wither.spawn @a[r=4]`);
          break;
        case "dungeon:melon_redpie":
          source.addEffect("mining_fatigue", 300, {
            amplifier: 0,
            showParticles: true
          });
          source.runCommandAsync(`scoreboard players reset @s tombstest`);
          source.runCommandAsync(`tag @s remove cursedcementery`);
          source.runCommandAsync(`fog @s remove cemetery`);
          source.runCommandAsync(`scoreboard objectives add redpie dummy`);
          source.runCommandAsync(`scoreboard players reset @s redpie`);
          source.runCommandAsync(`tag @s remove cemetery`);
          source.runCommandAsync(`tag @s remove punisher`);
          source.runCommandAsync(`tag @s remove punishment`);
          source.runCommandAsync(`scoreboard players add @s redpie 1200`);
          source.runCommandAsync(`execute at @s run playsound mob.wither.spawn @s`);
          source.addEffect("hunger", TicksPerSecond * 2, { amplifier: 255 });
          source.addEffect("nausea", TicksPerSecond * 10, { amplifier: 0 });
          break;
        case "otherworldly_winter:candy_cane":
          source.addEffect("speed", 30, {
            amplifier: 2,
            showParticles: true
          });
          source.runCommandAsync(`execute as @s[scores={insomnio=1..}]  run scoreboard players remove @s[scores={insomnio=1..}]  insomnio 3900 `);
          source.runCommandAsync(`execute if entity @s[scores={insomnio=1..}] run titleraw @s[scores={insomnio=1..}] actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.fear\"}]}`);
          source.addEffect("regeneration", TicksPerSecond * 50, { amplifier: 0 });
          break;
        case "otherworldly_winter:candy":
          source.runCommandAsync(`execute as @s[scores={insomnio=1..}]  run scoreboard players remove @s[scores={insomnio=1..}]  insomnio 300 `);
          source.runCommandAsync(`execute if entity @s[scores={insomnio=1..}] run titleraw @s[scores={insomnio=1..}] actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.fear\"}]}`);
          source.addEffect("regeneration", TicksPerSecond * 5, { amplifier: 0 });
          break;
        case "otherworldly_winter:candy2":
          source.runCommandAsync(`execute as @s[scores={insomnio=1..}]  run scoreboard players remove @s[scores={insomnio=1..}]  insomnio 300 `);
          source.runCommandAsync(`execute if entity @s[scores={insomnio=1..}] run titleraw @s[scores={insomnio=1..}] actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.fear\"}]}`);
          source.addEffect("speed", 30, {
            amplifier: 2,
            showParticles: true
          });
          break;
        case "otherworldly_winter:christmas_stew":
          source.runCommandAsync(`execute as @s[scores={insomnio=1..}]  run scoreboard players remove @s[scores={insomnio=1..}]  insomnio 25000 `);
          source.runCommandAsync(`execute if entity @s[scores={insomnio=1..}] run titleraw @s[scores={insomnio=1..}] actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.fear\"}]}`);
          source.addEffect("haste", TicksPerSecond * 130, { amplifier: 1 });
          source.addEffect("slowness", TicksPerSecond * 630, { amplifier: 1 });
          source.addEffect("resistance", 620, {
            amplifier: 0,
            showParticles: true
          });
          break;
        case "otherworldly_winter:eggnog":
          source.runCommandAsync(`execute as @s[scores={insomnio=1..}]  run scoreboard players remove @s[scores={insomnio=1..}]  insomnio 22000 `);
          source.runCommandAsync(`execute if entity @s[scores={insomnio=1..}] run titleraw @s[scores={insomnio=1..}] actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.fear\"}]}`);
          source.addEffect("regeneration", TicksPerSecond * 75, { amplifier: 0 });
          source.addEffect("resistance", TicksPerSecond * 130, { amplifier: 0 });
          break;
        case "dungeon:magic_seeds":
          source.runCommandAsync(`execute as @s[scores={insomnio=1..}]  run scoreboard players remove @s[scores={insomnio=1..}]  insomnio 5000 `);
          source.runCommandAsync(`execute if entity @s[scores={insomnio=1..}] run titleraw @s[scores={insomnio=1..}] actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.fear\"}]}`);
          break;
        case "otherworldly_winter:gingerbread_cookie":
          source.runCommandAsync(`execute as @s[scores={insomnio=1..}]  run scoreboard players remove @s[scores={insomnio=1..}] insomnio 1000 `);
          source.runCommandAsync(`execute if entity @s[scores={insomnio=1..}] run titleraw @s[scores={insomnio=1..}] actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.fear\"}]}`);
          source.addEffect("regeneration", TicksPerSecond * 35, { amplifier: 0 });
          source.addEffect("resistance", TicksPerSecond * 30, { amplifier: 0 });
          break;
        case "otherworldly_winter:gingerbread_cookie2":
          source.runCommandAsync(`execute as @s[scores={insomnio=1..}]  run scoreboard players remove @s[scores={insomnio=1..}] insomnio 1000 `);
          source.runCommandAsync(`execute if entity @s[scores={insomnio=1..}] run titleraw @s[scores={insomnio=1..}] actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.fear\"}]}`);
          source.addEffect("absorption", TicksPerSecond * 35, { amplifier: 0 });
          source.addEffect("resistance", TicksPerSecond * 30, { amplifier: 0 });
          break;
        case "otherworldly_winter:gingerbread_cookie3":
          source.runCommandAsync(`execute as @s[scores={insomnio=1..}]  run scoreboard players remove @s[scores={insomnio=1..}] insomnio 1000 `);
          source.runCommandAsync(`execute if entity @s[scores={insomnio=1..}] run titleraw @s[scores={insomnio=1..}] actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.fear\"}]}`);
          source.addEffect("speed", TicksPerSecond * 65, { amplifier: 0 });
          source.addEffect("resistance", TicksPerSecond * 30, { amplifier: 0 });
          break;
        case "otherworldly_winter:gingerbread_cookie4":
          source.runCommandAsync(`execute as @s[scores={insomnio=1..}]  run scoreboard players remove @s[scores={insomnio=1..}] insomnio 1000 `);
          source.runCommandAsync(`execute if entity @s[scores={insomnio=1..}] run titleraw @s[scores={insomnio=1..}] actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.fear\"}]}`);
          source.addEffect("strength", TicksPerSecond * 35, { amplifier: 0 });
          source.addEffect("resistance", TicksPerSecond * 30, { amplifier: 0 });
          break;
        case "otherworldly_winter:hot_chocolate":
          source.runCommandAsync(`execute as @s[scores={insomnio=1..}]  run scoreboard players remove @s[scores={insomnio=1..}] insomnio 10000 `);
          source.runCommandAsync(`execute if entity @s[scores={insomnio=1..}] run titleraw @s[scores={insomnio=1..}] actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.fear\"}]}`);
          source.addEffect("regeneration", TicksPerSecond * 15, { amplifier: 4 });
          source.addEffect("resistance", TicksPerSecond * 30, { amplifier: 1 });
          source.addEffect("speed", TicksPerSecond * 30, { amplifier: 1 });
          break;
        case "otherworldly_winter:ice_cream":
          source.runCommandAsync(`execute as @s[scores={insomnio=1..}]  run scoreboard players remove @s[scores={insomnio=1..}] insomnio 1000 `);
          source.runCommandAsync(`execute if entity @s[scores={insomnio=1..}] run titleraw @s[scores={insomnio=1..}] actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.fear\"}]}`);
          source.addEffect("regeneration", TicksPerSecond * 15, { amplifier: 0 });
          source.addEffect("resistance", TicksPerSecond * 60, { amplifier: 0 });
          break;
        case "otherworldly_winter:ice_cream2":
          source.runCommandAsync(`execute as @s[scores={insomnio=1..}]  run scoreboard players remove @s[scores={insomnio=1..}] insomnio 1000 `);
          source.runCommandAsync(`execute if entity @s[scores={insomnio=1..}] run titleraw @s[scores={insomnio=1..}] actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.fear\"}]}`);
          source.addEffect("resistance", TicksPerSecond * 60, { amplifier: 0 });
          source.addEffect("speed", TicksPerSecond * 30, { amplifier: 1 });
          break;
        case "otherworldly_winter:ice_cream3":
          source.runCommandAsync(`execute as @s[scores={insomnio=1..}]  run scoreboard players remove @s[scores={insomnio=1..}] insomnio 1000 `);
          source.runCommandAsync(`execute if entity @s[scores={insomnio=1..}] run titleraw @s[scores={insomnio=1..}] actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.fear\"}]}`);
          source.addEffect("resistance", TicksPerSecond * 120, { amplifier: 0 });
          source.addEffect("slowness", TicksPerSecond * 80, { amplifier: 0 });
          break;
        case "otherworldly_winter:ice_cream4":
          source.runCommandAsync(`execute as @s[scores={insomnio=1..}]  run scoreboard players remove @s[scores={insomnio=1..}] insomnio 1000 `);
          source.runCommandAsync(`execute if entity @s[scores={insomnio=1..}] run titleraw @s[scores={insomnio=1..}] actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.fear\"}]}`);
          source.addEffect("resistance", TicksPerSecond * 60, { amplifier: 0 });
          source.addEffect("speed", TicksPerSecond * 120, { amplifier: 0 });
          source.addEffect("regeneration", TicksPerSecond * 10, { amplifier: 0 });
          break;
        case "otherworldly_winter:ice_cream5":
          source.runCommandAsync(`execute as @s[scores={insomnio=1..}]  run scoreboard players remove @s[scores={insomnio=1..}] insomnio 1000 `);
          source.runCommandAsync(`execute if entity @s[scores={insomnio=1..}] run titleraw @s[scores={insomnio=1..}] actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.fear\"}]}`);
          source.addEffect("resistance", TicksPerSecond * 20, { amplifier: 1 });
          source.addEffect("regeneration", TicksPerSecond * 6, { amplifier: 0 });
          break;
        case "otherworldly_winter:ice_cream6":
          source.runCommandAsync(`execute as @s[scores={insomnio=1..}]  run scoreboard players remove @s[scores={insomnio=1..}] insomnio 1000 `);
          source.runCommandAsync(`execute if entity @s[scores={insomnio=1..}] run titleraw @s[scores={insomnio=1..}] actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.fear\"}]}`);
          source.addEffect("resistance", TicksPerSecond * 30, { amplifier: 0 });
          source.addEffect("absorption", TicksPerSecond * 60, { amplifier: 0 });
          break;
        case "otherworldly_winter:gift_common":

          const randomChoice = Math.floor(Math.random() * 8); // Genera un número aleatorio entre 0 y 7.

          switch (randomChoice) {
            case 0:
              // Opción 1: Reduce el miedo
              source.runCommandAsync(`scoreboard players remove @s[scores={insomnio=1..}] insomnio 25200`);
              source.runCommandAsync(`execute if entity @s[scores={insomnio=1..}] run titleraw @s[scores={insomnio=1..}] actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.fear\"}]}`);
              break;

            case 1:
              // Opción 2: Otorga un efecto positivo
              source.addEffect("speed", TicksPerSecond * 30, { amplifier: 1 });
              source.addEffect("jump_boost", TicksPerSecond * 30, { amplifier: 1 });
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.commongift\"}]}`);
              break;

            case 2:
              // Opción 3: Aparece un mob hostil cerca
              source.runCommandAsync(`summon otherworldly_winter:elf ~ ~1 ~ ~ ~ minecraft:entity_spawned`);
              break;
            case 3:
              // Opción 4: Invoca un evento atmosférico
              source.runCommandAsync(`weather thunder`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.commongift2\"}]}`);
              break;
            case 4:
              // Opción 5: Otorga un regalo misterioso
              source.runCommandAsync(`give @s minecraft:golden_apple 1`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.commongift3\"}]}`);
              break;
            case 5:
              // Opción 6: Otorga un ponche de huevo
              source.runCommandAsync(`give @s otherworldly_winter:eggnog`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.christmasitem\"}]}`);
              break;
            case 6:
              // Opción 7: Otorga un dulce
              source.runCommandAsync(`give @s otherworldly_winter:candy`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.christmasitem\"}]}`);
              break;
            case 7:
              // Opción 8: Otorga un dulce
              source.runCommandAsync(`give @s otherworldly_winter:candy2`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.christmasitem\"}]}`);
              break;
            default:
              // Opción por defecto, en caso de errores
              source.runCommandAsync(`titleraw @s actionbar {"rawtext":[{"text":"§7???"}]}`);
              break;
          }
          break;
        case "otherworldly_winter:gift_rare":
          const randomChoice2 = Math.floor(Math.random() * 9); // Genera un número aleatorio entre 0 y 8.

          switch (randomChoice2) {
            case 0:
              // Opción 1: Reduce el miedo
              source.runCommandAsync(`scoreboard players remove @s[scores={insomnio=1..}] insomnio 35200`);
              source.runCommandAsync(`execute if entity @s[scores={insomnio=1..}] run titleraw @s[scores={insomnio=1..}] actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.fear\"}]}`);
              break;

            case 1:
              // Opción 2: Otorga un efecto positivo
              source.addEffect("water_breathing", TicksPerSecond * 30, { amplifier: 0 });
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.commongift\"}]}`);
              break;

            case 2:
              // Opción 3: Aparece un mob hostil cerca
              source.runCommandAsync(`summon otherworldly_winter:elf ~ ~1 ~ ~ ~ minecraft:entity_spawned`);
              break;
            case 3:
              // Opción 4: Otorga Xp
              source.runCommandAsync(`xp 10l @s`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.raregift\"}]}`);
              break;
            case 4:
              // Opción 5: Otorga un regalo misterioso
              source.runCommandAsync(`give @s minecraft:golden_apple 2`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.commongift3\"}]}`);
              break;
            case 5:
              // Opción 6: Otorga un helado
              source.runCommandAsync(`give @s otherworldly_winter:ice_cream`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.christmasitem\"}]}`);
              break;
            case 6:
              // Opción 7: Otorga un dulce
              source.runCommandAsync(`give @s otherworldly_winter:gingerbread_cookie`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.christmasitem\"}]}`);
              break;
            case 7:
              // Opción 8: Otorga un dulce
              source.runCommandAsync(`give @s otherworldly_winter:gingerbread_cookie2`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.christmasitem\"}]}`);
              break;
            case 8:
              // Opción 9: Otorga un dulce
              source.runCommandAsync(`give @s otherworldly_winter:gingerbread_cookie2`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.christmasitem\"}]}`);
              break;
            default:
              // Opción por defecto, en caso de errores
              source.runCommandAsync(`titleraw @s actionbar {"rawtext":[{"text":"§7???"}]}`);
              break;
          }
          break;
        case "otherworldly_winter:gift_mythical":
          const randomChoice3 = Math.floor(Math.random() * 16); // Genera un número aleatorio entre 0 y 15.

          switch (randomChoice3) {
            case 0:
              // Opción 1: Reduce el miedo
              source.runCommandAsync(`scoreboard players remove @s[scores={insomnio=1..}] insomnio 65200`);
              source.runCommandAsync(`execute if entity @s[scores={insomnio=1..}] run titleraw @s[scores={insomnio=1..}] actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.fear\"}]}`);
              break;

            case 1:
              // Opción 2: Otorga un efecto positivo
              source.addEffect("strength", TicksPerSecond * 300, { amplifier: 0 });
              source.addEffect("resistance", TicksPerSecond * 300, { amplifier: 0 });
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.commongift\"}]}`);
              break;

            case 2:
              // Opción 3: Aparece un mob hostil cerca
              source.runCommandAsync(`summon otherworldly_winter:elf_friend ~ ~1 ~ ~ ~ minecraft:entity_spawned`);
              break;
            case 3:
              // Opción 4: Otorga Xp
              source.runCommandAsync(`xp 60l @s`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.raregift\"}]}`);
              break;
            case 4:
              // Opción 5: Otorga un regalo misterioso
              source.runCommandAsync(`give @s minecraft:golden_apple 20`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.commongift3\"}]}`);
              break;
            case 5:
              // Opción 6: Otorga un helado
              source.runCommandAsync(`give @s otherworldly_winter:ice_cream`);
              source.runCommandAsync(`give @s otherworldly_winter:ice_cream2`);
              source.runCommandAsync(`give @s otherworldly_winter:ice_cream3`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.christmasitem\"}]}`);
              break;
            case 6:
              // Opción 7: Otorga un dulce
              source.runCommandAsync(`give @s otherworldly_winter:gingerbread_cookie`);
              source.runCommandAsync(`give @s otherworldly_winter:gingerbread_cookie3`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.christmasitem\"}]}`);
              break;
            case 7:
              // Opción 8: Otorga un dulce
              source.runCommandAsync(`give @s otherworldly_winter:gingerbread_cookie2`);
              source.runCommandAsync(`give @s otherworldly_winter:gingerbread_cookie4`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.christmasitem\"}]}`);
              break;
            case 8:
              // Opción 9: Otorga un dulce
              source.runCommandAsync(`give @s otherworldly_winter:eggnog`);
              source.runCommandAsync(`give @s otherworldly_winter:eggnog`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.christmasitem\"}]}`);
              break;
            case 9:
              // Opción 10: Otorga un dulce
              source.runCommandAsync(`give @s otherworldly_winter:candy2`);
              source.runCommandAsync(`give @s otherworldly_winter:candy`);
              source.runCommandAsync(`give @s otherworldly_winter:candy2`);
              source.runCommandAsync(`give @s otherworldly_winter:candy`);
              source.runCommandAsync(`give @s otherworldly_winter:candy2`);
              source.runCommandAsync(`give @s otherworldly_winter:candy`);
              source.runCommandAsync(`give @s otherworldly_winter:candy2`);
              source.runCommandAsync(`give @s otherworldly_winter:candy`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.christmasitem\"}]}`);
              break;
            case 10:
              // Opción 11: Otorga un dulce
              source.runCommandAsync(`give @s otherworldly_winter:christmas_stew`);
              source.runCommandAsync(`give @s otherworldly_winter:christmas_stew`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.christmasitem\"}]}`);
              break;
            case 11:
              // Opción 12: Otorga un objeto especial 
              source.runCommandAsync(`give @s dungeon:moonstone`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.mythical\"}]}`);
              break;
            case 12:
              // Opción 13: Otorga un objeto especial 
              source.runCommandAsync(`give @s dungeon:bone_relic`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.mythical\"}]}`);
              break;
            case 13:
              // Opción 14: Otorga un objeto especial 
              source.runCommandAsync(`give @s dungeon:bone_relic`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.mythical\"}]}`);
              break;
            case 14:
              // Opción 15: Otorga un objeto especial 
              source.runCommandAsync(`give @s dungeon:bone_relic`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.mythical\"}]}`);
              break;
            case 15:
              // Opción 15: Otorga un objeto especial 
              source.runCommandAsync(`give @s dungeon:slowness_inmunity`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.mythical\"}]}`);
              break;
            default:
              // Opción por defecto, en caso de errores
              source.runCommandAsync(`titleraw @s actionbar {"rawtext":[{"text":"§7???"}]}`);
              break;
          }
          break;
        case "otherworldly_winter:gift_legendary":
          const randomChoice4 = Math.floor(Math.random() * 16); // Genera un número aleatorio entre 0 y 15.

          switch (randomChoice4) {
            case 0:
              // Opción 1: Reduce el miedo
              source.runCommandAsync(`scoreboard players remove @s[scores={insomnio=1..}] insomnio 85200`);
              source.runCommandAsync(`execute if entity @s[scores={insomnio=1..}] run titleraw @s[scores={insomnio=1..}] actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.fear\"}]}`);
              break;

            case 1:
              // Opción 2: Otorga un efecto positivo
              source.addEffect("strength", TicksPerSecond * 300, { amplifier: 1 });
              source.addEffect("resistance", TicksPerSecond * 300, { amplifier: 1 });
              source.addEffect("absorption", TicksPerSecond * 300, { amplifier: 1 });
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.commongift\"}]}`);
              break;

            case 2:
              // Opción 3: Aparece un mob cerca
              source.runCommandAsync(`summon otherworldly_winter:elf_friend ~ ~1 ~ ~ ~ minecraft:entity_spawned`);
              source.runCommandAsync(`summon otherworldly_winter:elf_friend ~ ~1 ~ ~ ~ minecraft:entity_spawned`);
              break;
            case 3:
              // Opción 4: Otorga Xp
              source.runCommandAsync(`xp 100l @s`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.raregift\"}]}`);
              break;
            case 4:
              // Opción 5: Otorga un regalo misterioso
              source.runCommandAsync(`give @s minecraft:golden_apple 80`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.commongift3\"}]}`);
              break;
            case 5:
              // Opción 6: Otorga un helado
              source.runCommandAsync(`give @s otherworldly_winter:ice_cream`);
              source.runCommandAsync(`give @s otherworldly_winter:ice_cream2`);
              source.runCommandAsync(`give @s otherworldly_winter:ice_cream3`);
              source.runCommandAsync(`give @s otherworldly_winter:ice_cream4`);
              source.runCommandAsync(`give @s otherworldly_winter:ice_cream5`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.christmasitem\"}]}`);
              break;
            case 6:
              // Opción 7: Otorga un dulce
              source.runCommandAsync(`give @s otherworldly_winter:gingerbread_cookie`);
              source.runCommandAsync(`give @s otherworldly_winter:gingerbread_cookie`);
              source.runCommandAsync(`give @s otherworldly_winter:gingerbread_cookie3`);
              source.runCommandAsync(`give @s otherworldly_winter:gingerbread_cookie3`);
              source.runCommandAsync(`give @s otherworldly_winter:gingerbread_cookie`);
              source.runCommandAsync(`give @s otherworldly_winter:gingerbread_cookie`);
              source.runCommandAsync(`give @s otherworldly_winter:gingerbread_cookie3`);
              source.runCommandAsync(`give @s otherworldly_winter:gingerbread_cookie3`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.christmasitem\"}]}`);
              break;
            case 7:
              // Opción 8: Otorga un dulce
              source.runCommandAsync(`give @s otherworldly_winter:gingerbread_cookie2`);
              source.runCommandAsync(`give @s otherworldly_winter:gingerbread_cookie4`);
              source.runCommandAsync(`give @s otherworldly_winter:gingerbread_cookie2`);
              source.runCommandAsync(`give @s otherworldly_winter:gingerbread_cookie4`);
              source.runCommandAsync(`give @s otherworldly_winter:gingerbread_cookie2`);
              source.runCommandAsync(`give @s otherworldly_winter:gingerbread_cookie4`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.christmasitem\"}]}`);
              break;
            case 8:
              // Opción 9: Otorga un dulce
              source.runCommandAsync(`give @s otherworldly_winter:eggnog`);
              source.runCommandAsync(`give @s otherworldly_winter:hot_chocolate`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.christmasitem\"}]}`);
              break;
            case 9:
              // Opción 10: Otorga un dulce
              source.runCommandAsync(`give @s otherworldly_winter:candy2`);
              source.runCommandAsync(`give @s otherworldly_winter:candy`);
              source.runCommandAsync(`give @s otherworldly_winter:candy2`);
              source.runCommandAsync(`give @s otherworldly_winter:candy`);
              source.runCommandAsync(`give @s otherworldly_winter:candy2`);
              source.runCommandAsync(`give @s otherworldly_winter:candy`);
              source.runCommandAsync(`give @s otherworldly_winter:candy2`);
              source.runCommandAsync(`give @s otherworldly_winter:candy`);
              source.runCommandAsync(`give @s otherworldly_winter:candy2`);
              source.runCommandAsync(`give @s otherworldly_winter:candy`);
              source.runCommandAsync(`give @s otherworldly_winter:candy2`);
              source.runCommandAsync(`give @s otherworldly_winter:candy`);
              source.runCommandAsync(`give @s otherworldly_winter:candy2`);
              source.runCommandAsync(`give @s otherworldly_winter:candy`);
              source.runCommandAsync(`give @s otherworldly_winter:candy2`);
              source.runCommandAsync(`give @s otherworldly_winter:candy`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.christmasitem\"}]}`);
              break;
            case 10:
              // Opción 11: Otorga un dulce
              source.runCommandAsync(`give @s otherworldly_winter:christmas_stew`);
              source.runCommandAsync(`give @s otherworldly_winter:christmas_stew`);
              source.runCommandAsync(`give @s otherworldly_winter:christmas_stew`);
              source.runCommandAsync(`give @s otherworldly_winter:christmas_stew`);
              source.runCommandAsync(`give @s otherworldly_winter:christmas_stew`);
              source.runCommandAsync(`give @s otherworldly_winter:christmas_stew`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.christmasitem\"}]}`);
              break;
            case 11:
              // Opción 12: Otorga un objeto especial 
              source.runCommandAsync(`give @s dungeon:moonstone`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.mythical\"}]}`);
              break;
            case 12:
              // Opción 13: Otorga un objeto especial 
              source.runCommandAsync(`give @s dungeon:bone_relic`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.mythical\"}]}`);
              break;
            case 13:
              // Opción 14: Otorga un objeto especial 
              source.runCommandAsync(`give @s dungeon:gauntlet`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.mythical\"}]}`);
              break;
            case 14:
              // Opción 15: Otorga un objeto especial 
              source.runCommandAsync(`give @s dungeon:haste_potion2`);
              source.runCommandAsync(`give @s dungeon:haste_potion2`);
              source.runCommandAsync(`give @s dungeon:haste_potion2`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.mythical\"}]}`);
              break;
            case 15:
              // Opción 15: Otorga un objeto especial 
              source.runCommandAsync(`give @s dungeon:slowness_inmunity`);
              source.runCommandAsync(`give @s dungeon:weakness_inmunity`);
              source.runCommandAsync(`execute if entity @s run titleraw @s actionbar {\"rawtext\":[{\"translate\":\"dungeon.langcode.mythical\"}]}`);
              break;
            default:
              // Opción por defecto, en caso de errores
              source.runCommandAsync(`titleraw @s actionbar {"rawtext":[{"text":"§7???"}]}`);
              break;
          }
          break;
      };
    },
  });
  // Register custom durability logic for mining blocks
  initEvent.itemComponentRegistry.registerCustomComponent("dungeon:durability", {
    onMineBlock: (e) => {
      // Verificar si el jugador está en modo creativo
      if (e.source.matches({ gameMode: GameMode.creative })) return;

      // Obtener encantamientos de la herramienta
      const itemEnchantable = e.itemStack.getComponent("enchantable");
      const unbreaking = itemEnchantable?.getEnchantment("unbreaking");
      const unbreakingLevel = unbreaking?.level || 0;
      const silkTouch = itemEnchantable?.getEnchantment("silk_touch");

      // Reducción de durabilidad si se tiene Silk Touch
      if (silkTouch) {
        redura(e.source, e.itemStack, 1);
        return;
      }

      // Reducción de durabilidad si no tiene Unbreaking y el bloque no es "instantáneo"
      if (!unbreaking && !instantmine(e.minedBlockPermutation.type.id)) {
        redura(e.source, e.itemStack, 1);
        return;
      }

      // Reducción de durabilidad si se tiene Unbreaking y el daño es exitoso
      if (unbreaking && damageitem(unbreakingLevel)) {
        redura(e.source, e.itemStack, 1);
      }
    },
  });


  // Register custom durability logic for item usage
  initEvent.itemComponentRegistry.registerCustomComponent("dungeon:durability_use", {
    onUse: (e) => {
      if (e.source.matches({ gameMode: GameMode.creative })) return;
      redura(e.source, e.itemStack, 5);
    },
  });
  initEvent.itemComponentRegistry.registerCustomComponent("dungeon:durability_use2", {
    onUse: (e) => {
      if (e.source.matches({ gameMode: GameMode.creative })) return;
      redura(e.source, e.itemStack, 100);
    },
  });
});
world.afterEvents.entityHitEntity.subscribe(
  // Register toolseffect
  ({ damagingEntity, hitEntity }) => {
    if (damagingEntity instanceof Player) {
      toolseffects(damagingEntity, hitEntity);
    }
  }
);
export function toolseffects(player, hitEntity) {
  const equip = player.getComponent(EntityEquippableComponent.componentId);
  const mainhand = equip.getEquipment(EquipmentSlot.Mainhand);
  if (mainhand == undefined)
    return;

  switch (mainhand.typeId) {
    case "dungeon:viritum_sword": player.addEffect("regeneration", TicksPerSecond * 5, { amplifier: 0 }); break;
    case "dungeon:spider_fang": hitEntity.addEffect("instant_damage", TicksPerSecond * 10, { amplifier: 0 }); break;
    case "dungeon:spectrum_spike": hitEntity.addEffect("slowness", TicksPerSecond * 10, { amplifier: 2 }); break;
    case "dungeon:lunar_sword":
      {
        const time = world.getTimeOfDay();
        const isNight = time >= 13000 && time <= 23000; // noche en Minecraft

        if (isNight) {
          player.addEffect("strength", TicksPerSecond * 1, { amplifier: 6 });
        }

        hitEntity.addEffect("weakness", TicksPerSecond * 5, { amplifier: 1 });
      }
      break; case "dungeon:flyswatter": {
        hitEntity.applyKnockback(
          -hitEntity.getViewDirection().z, // Dirección Z del retroceso
          -hitEntity.getViewDirection().x, // Dirección X del retroceso
          0.2, // Intensidad horizontal del retroceso
          0.6  // Intensidad vertical del retroceso
        );

        // Daño adicional si tiene la etiqueta "armored"
        if (hitEntity.hasTag("flymob")) {
          hitEntity.runCommandAsync("damage @s 80 magic").catch(() => { });
        }
        break;
      }
    case "dungeon:wither_spike":
      {
        player.addEffect("wither", TicksPerSecond * 1, { amplifier: 255 });
        player.addEffect("instant_damage", TicksPerSecond * 0.5, { amplifier: 0 });

        // Eliminar resistencia si la tiene
        if (hitEntity.hasTag || hitEntity.hasComponent("minecraft:resistance")) {
          hitEntity.runCommandAsync("effect @s resistance 0 0 true").catch(() => { });
        }
        if (hitEntity.hasTag("armored")) {
          hitEntity.runCommandAsync("damage @s 14 magic").catch(() => { });
        }
        // Aplicar daño mágico directo
        hitEntity.runCommandAsync("damage @s 10 magic").catch(() => { });
      }
      break;
    case "dungeon:ancient_copper_sword":
      {
        hitEntity.addEffect("poison", TicksPerSecond * 10, { amplifier: 0 });
        if (hitEntity.hasTag("armored")) {
          hitEntity.runCommandAsync("damage @s 12 magic").catch(() => { });
        }
        // Aplicar daño mágico directo
        hitEntity.runCommandAsync("damage @s 8 magic").catch(() => { });
      }
      break;
    case "dungeon:cursed_sickle":
      {
        player.addEffect("weakness", TicksPerSecond * 2, { amplifier: 255 });
        player.addEffect("slowness", TicksPerSecond * 2, { amplifier: 1 });

        // Eliminar resistencia si la tiene
        if (hitEntity.hasTag("armored")) {
          hitEntity.runCommandAsync("damage @s 40 magic").catch(() => { });
        }
        // Aplicar daño mágico directo
        hitEntity.runCommandAsync("damage @e[family=monster,r=3] 20 entity_attack").catch(() => { });
        hitEntity.runCommandAsync("damage @s 30 magic").catch(() => { });
      }
      break;

    case "dungeon:storm_sword": hitEntity.runCommandAsync("summon dungeon:beam ~ ~ ~ ~ ~ minecraft:player_beam"); break;

    // case "dungeon:viritum_sword": hitEntity.addEffect("weakness", TicksPerSecond * 10, { amplifier: 1 }); break;
    //case "dungeon:viritum_sword": hitEntity.setOnFire(2, true); break;
  };
};
