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

system.runInterval(() => {
  for (const player of world.getPlayers()) {
    if (player.hasTag('we:windwalker')) {
      if (!player.isFlying && player.isSprinting && player.isFalling && player.dimension.getBlock(player.location).isAir && player.dimension.getBlock(player.location).below().isAir && player.dimension.getBlock(player.location).below(2).isAir) {
        const velocity = player.getViewDirection();

        player.applyKnockback(velocity.x, velocity.z, 0.8, -0.01);
        player.playAnimation('animation.windwalker.glide', {blendOutTime: 0.75});
      }
    }
  }
}, 1);

system.runInterval(() => {
  for (const player of world.getPlayers()) {
    if (player.hasTag('we:windwalker')) {
      if (!player.isFlying && player.isSprinting && player.isFalling && player.dimension.getBlock(player.location).isAir && player.dimension.getBlock(player.location).below().isAir && player.dimension.getBlock(player.location).below(2).isAir) {
        const equipment = player.getComponent('equippable');
        const selectedItem = equipment.getEquipment('Chest');

        if (!selectedItem) {
          return;
        }

        if (!player.matches({
            gameMode: 'creative'
          })) {

          const itemEnchantmentComp = selectedItem.getComponent("minecraft:enchantable");
          const unbreakingLevel = itemEnchantmentComp?.getEnchantment("unbreaking")?.level ?? 0;

          const breakChance = 100 / (unbreakingLevel + 1);

          const randomizeChance = Math.random() * 100;

          if (breakChance < randomizeChance) return;

          const itemUsedDurabilityComp = selectedItem.getComponent("durability");

          if (!itemUsedDurabilityComp) return;

          let durabilityModifier = 1;

          itemUsedDurabilityComp.damage += durabilityModifier;

          const maxDurability = itemUsedDurabilityComp.maxDurability
          const currentDamage = itemUsedDurabilityComp.damage
          if (currentDamage >= maxDurability) {

            player.playSound('random.break', {
              pitch: 1,
              location: player.location,
              volume: 1
            })
            equipment.setEquipment("Chest", new ItemStack('minecraft:air', 1));
          } else if (currentDamage < maxDurability) {

            equipment.setEquipment("Chest", selectedItem);
          }
        }
      }
    }
  }
}, 20);