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

const armorSets = {
  frankenstein: "frnk",
  lagoon: "goon",
  mummy: "mumm",
  reaper: "reap",
  //skeleton: "skel",
  //spider: "spi",
  vampire: "vmp",
  werewolf: "were",
  witch: "wtch",
  zombie: "zmb",
};

const playerHitCountMap = new Map();
const vampireHitCountMap = new Map();
const zombieHitCountMap = new Map();

function getEquippedArmor(entity) {
  const equippable = entity.getComponent("minecraft:equippable");
  if (!equippable) return {};

  return {
    helmet: equippable.getEquipment(EquipmentSlot.Head)?.typeId || null,
    chestplate: equippable.getEquipment(EquipmentSlot.Chest)?.typeId || null,
    leggings: equippable.getEquipment(EquipmentSlot.Legs)?.typeId || null,
    boots: equippable.getEquipment(EquipmentSlot.Feet)?.typeId || null,
  };
}

function getArmorPieceType(itemId, setPrefix) {
  const patterns = {
    helmet: new RegExp(`^arcedge_horr:${setPrefix}(_1|_helmet)?$`, "i"),
    chestplate: new RegExp(`^arcedge_horr:${setPrefix}(_2|_chestplate)?$`, "i"),
    leggings: new RegExp(`^arcedge_horr:${setPrefix}(_3|_leggings)?$`, "i"),
    boots: new RegExp(`^arcedge_horr:${setPrefix}(_4|_boots)?$`, "i"),
  };

  for (const [type, pattern] of Object.entries(patterns)) {
    if (pattern.test(itemId)) {
      return type;
    }
  }

  return null;
}

function isWearingRelevantArmor(entity) {
  const equippedArmor = getEquippedArmor(entity);
  for (const itemId of Object.values(equippedArmor)) {
    for (const setPrefix of Object.values(armorSets)) {
      if (getArmorPieceType(itemId, setPrefix)) {
        return true;
      }
    }
  }
  return false;
}

function getArmorSetForEntity(entity) {
  const equippedArmor = getEquippedArmor(entity);
  const setCounts = {};

  for (const [slot, itemId] of Object.entries(equippedArmor)) {
    for (const [setName, setPrefix] of Object.entries(armorSets)) {
      if (getArmorPieceType(itemId, setPrefix)) {
        setCounts[setName] = (setCounts[setName] || 0) + 1;
      }
    }
  }

  return setCounts;
}

function hasEffect(entity, effectType, amplifier) {
  const effects = entity.getEffects();
  for (const effect of effects) {
    if (
      effect.typeId === effectType &&
      (amplifier == null || amplifier === -1 || effect.amplifier >= amplifier)
    ) {
      return true;
    }
  }
  return false;
}

function hasFamily(entity, family) {
  const attackerFamilyComponent = entity.getComponent("type_family");
  if (
    attackerFamilyComponent &&
    attackerFamilyComponent.getTypeFamilies().includes(family)
  ) {
    return true;
  }
  return false;
}

const armorConfigTellraw = {
  frankenstein: {
    tag: "ae_armor_tutorial_frankenstein",
    tellrawText: "arcedge_horr.text.tutorial.frankenstein",
  },
  lagoon: {
    tag: "ae_armor_tutorial_lagoon",
    tellrawText: "arcedge_horr.text.tutorial.lagoon",
  },
  mummy: {
    tag: "ae_armor_tutorial_mummy",
    tellrawText: "arcedge_horr.text.tutorial.mummy",
  },
  reaper: {
    tag: "ae_armor_tutorial_reaper",
    tellrawText: "arcedge_horr.text.tutorial.reaper",
  },
  vampire: {
    tag: "ae_armor_tutorial_vampire",
    tellrawText: "arcedge_horr.text.tutorial.vampire",
  },
  werewolf: {
    tag: "ae_armor_tutorial_werewolf",
    tellrawText: "arcedge_horr.text.tutorial.werewolf",
  },
  witch: {
    tag: "ae_armor_tutorial_witch",
    tellrawText: "arcedge_horr.text.tutorial.witch",
  },
  zombie: {
    tag: "ae_armor_tutorial_zombie",
    tellrawText: "arcedge_horr.text.tutorial.zombie",
  },
};

function playerArmorTutorial() {
  system.runInterval(() => {
    for (const player of world.getPlayers()) {
      if (!isWearingRelevantArmor(player)) continue;

      const armorSetCounts = getArmorSetForEntity(player);
      for (const [armorSet, piecesEquipped] of Object.entries(armorSetCounts)) {
        if (piecesEquipped > 0) {
          const config = armorConfigTellraw[armorSet];

          if (config && !player.hasTag(config.tag)) {
            player.runCommandAsync(
              `tellraw @s {"rawtext":[{"translate":"${config.tellrawText}"}]}`
            );
            player.runCommandAsync(
              `playsound sound.arcedge_horr.horr_tutorial @s ~ ~ ~ 0.3 1.0 0.3`
            );
            player.addTag(config.tag);
          }
        }
      }
    }
  }, 25); // Runs every 20 ticks (1 second)
}

playerArmorTutorial();

function applyBaseEffects(entity, armorSet, piecesEquipped, attacker) {
  switch (armorSet) {
    case "frankenstein":
      const lightningChance = 0.06 * piecesEquipped;
      if (
        Math.random() < lightningChance &&
        attacker &&
        attacker.id !== entity.id
      ) {
        entity.dimension.spawnEntity(
          "minecraft:lightning_bolt",
          attacker.location
        );
      }
      break;

    case "lagoon":
      const duration = 20 * 10;
      if (entity.isInWater) {
        if (!hasEffect(entity, "strength", null)) {
          entity.addEffect("strength", duration, { amplifier: 2 });
        }
        if (!hasEffect(entity, "water_breathing", null)) {
          entity.addEffect("water_breathing", duration, { amplifier: 1 });
        }
        if (!hasEffect(entity, "conduit_power", null)) {
          entity.addEffect("conduit_power", duration, { amplifier: 1 });
        }
      } else {
        if (!hasEffect(entity, "strength", null)) {
          entity.addEffect("strength", duration, { amplifier: 0 });
        }
        if (!hasEffect(entity, "water_breathing", null)) {
          entity.addEffect("water_breathing", duration, { amplifier: 1 });
        }
        if (!hasEffect(entity, "conduit_power", null)) {
          entity.addEffect("conduit_power", duration, { amplifier: 1 });
        }
      }
      break;

    case "mummy":
      const baseChance = 1 / 20;
      const increasedChance = baseChance * (1 + 0.1 * (piecesEquipped - 2));
      if (Math.random() < increasedChance) {
        const healDuration = 5;
        if (!hasEffect(entity, "instant_health", null)) {
          entity.addEffect("instant_health", healDuration, { amplifier: 2 });
        }
      }
      break;

    case "reaper":
      const thornsDamage = 4 * piecesEquipped;
      const effectChance = 0.1 * piecesEquipped;
      if (attacker && Math.random() < effectChance) {
        attacker.applyDamage(thornsDamage);
        const effectType = Math.random() < 0.5 ? "wither" : "darkness";
        if (!hasEffect(attacker, effectType, null)) {
          attacker.addEffect(effectType, 20 * 5, { amplifier: piecesEquipped });
        }
      }
      break;

    /* case "skeleton":
      const maxDistance = 1.75 * piecesEquipped;

      const nearbyUndead = entity.dimension.getEntities({
        families: ["monster"],
        maxDistance: maxDistance,
      });

      const nearbyPlayers = entity.dimension.getPlayers({
        maxDistance: maxDistance,
      });

      for (const target of nearbyUndead) {
        if (target.id !== entity.id) {
          target.applyDamage(piecesEquipped * 2);
        }
      }

      if (isPvPEnabled()) {
        for (const targetPlayer of nearbyPlayers) {
          if (
            targetPlayer.id !== entity.id &&
            targetPlayer.typeId === "minecraft:player"
          ) {
            targetPlayer.applyDamage(piecesEquipped);
          }
        }
      }

      const arrowResistanceAmplifier = piecesEquipped - 1;
      const arrowResistanceDuration = 20 * piecesEquipped;

      if (!hasEffect(entity, "resistance", null)) {
        entity.addEffect("resistance", arrowResistanceDuration, {
          amplifier: Math.ceil(arrowResistanceAmplifier * 0.5),
        });
      }
      break; */

    /* case "spider":
      const eggSpawnChance = 0.1 * piecesEquipped;

      const existingEggs = entity.dimension.getEntities({
        type: "arcedge_horr:b_spi_egg_f",
        maxDistance: piecesEquipped + 0.75,
        location: entity.location,
      }).length;

      if (Math.random() < eggSpawnChance && existingEggs < 3 && attacker) {
        entity.dimension.spawnEntity(
          "arcedge_horr:b_spi_egg_f",
          entity.location
        );
      }
      break; */

    case "vampire":
      const effectChance2 = 0.15 + 0.1 * (piecesEquipped - 1);
      const playerId = entity.id;
      const currentHitCount = vampireHitCountMap.get(playerId) || 0;
      const newHitCount = currentHitCount + 1;

      if (Math.random() < effectChance2 && attacker) {
        if (!hasEffect(attacker, "slowness", null)) {
          attacker.addEffect("slowness", 2 * piecesEquipped * 20, {
            amplifier: piecesEquipped,
          });
        }
        if (!hasEffect(attacker, "weakness", null)) {
          attacker.addEffect("weakness", 2 * piecesEquipped * 20, {
            amplifier: 1,
          });
        }
      }

      if (newHitCount % 2 === 0) {
        attacker.applyDamage(4);
        entity.addEffect("instant_health", 5, { amplifier: 0 });
        vampireHitCountMap.delete(playerId);
      } else {
        vampireHitCountMap.set(playerId, newHitCount);
      }
      break;

    case "werewolf":
      const baseRoarDamage = 1 * piecesEquipped;
      const baseRoarRadius = 4 + 1 * piecesEquipped;
      const baseRoarChance = Math.min(0.05 * piecesEquipped, 0.15);

      if (Math.random() < baseRoarChance) {
        const affectedEntities = entity.dimension.getEntities({
          location: entity.location,
          families: ["monster"],
          maxDistance: baseRoarRadius,
        });

        for (const target of affectedEntities) {
          if (target.id !== entity.id) {
            if (!hasEffect(target, "slowness", null)) {
              target.addEffect("slowness", 20 * 5, { amplifier: 2 });
              target.applyDamage(baseRoarDamage);
            }
            vanillaKnockback(
              entity.dimension.id,
              entity.location.x,
              entity.location.y,
              entity.location.z,
              2,
              1,
              0.5,
              "entities"
            );
          }
        }
      }
      break;

    case "witch":
      const poisonChance = 0.2;
      const poisonLevel = piecesEquipped;
      const poisonDuration = 10 * 20 + piecesEquipped;
      if (Math.random() < poisonChance) {
        if (!hasEffect(attacker, "fatal_poison", null)) {
          attacker.addEffect("fatal_poison", poisonDuration, {
            amplifier: poisonLevel,
          });
        }
      }
      break;

    case "zombie":
      const entityId = entity.id;
      const currentHitCounter = zombieHitCountMap.get(entityId) || 0;
      const updatedHitCounter = currentHitCounter + 1;

      if (updatedHitCounter % 3 === 0) {
        system.run(() => {
          const healthComponent = entity.getComponent("minecraft:health");
          if (!healthComponent) return;

          const isBelowHalfHealth =
            healthComponent.currentValue <= healthComponent.effectiveMax * 0.5;
          const piecesBonus = piecesEquipped - 1;

          if (isBelowHalfHealth && Math.random() < 0.1) {
            const regenerationDuration = 20 * 1 + piecesEquipped;
            if (!hasEffect(entity, "regeneration", null)) {
              entity.addEffect("regeneration", regenerationDuration, {
                amplifier: piecesBonus,
              });
            }
          }

          if (Math.random() < 0.1 * piecesEquipped) {
            const maxDistance = 1.75 * piecesEquipped;
            const targets = entity.dimension.getEntities({
              families: ["monster"],
              location: entity.location,
              maxDistance,
            });

            if (isPvPEnabled()) {
              const players = entity.dimension.getPlayers({
                maxDistance,
                location: entity.location,
              });
              targets.push(...players);
            }

            for (const target of targets) {
              if (target.id !== entity.id) {
                target.applyDamage(1.5 * piecesEquipped);
              }
            }
          }
        });
        zombieHitCountMap.delete(entityId);
      } else {
        zombieHitCountMap.set(entityId, updatedHitCounter);
      }
      break;
  }
}

function vanillaKnockback(
  dimensionId,
  originX = 0,
  originY = 0,
  originZ = 0,
  knockbackRadius = 1,
  horizontalPower = 1,
  verticalPower = 1,
  targets = "both"
) {
  if (
    !dimensionId ||
    knockbackRadius <= 0 ||
    (horizontalPower <= 0 && verticalPower <= 0)
  ) {
    return;
  }

  const dimension = world.getDimension(dimensionId);
  if (!dimension) {
    return;
  }

  let entities = [];
  if (targets === "both" || targets === "entities" || targets === "monsters") {
    const monsters = dimension.getEntities({
      location: { x: originX, y: originY, z: originZ },
      families: ["monster"],
      maxDistance: knockbackRadius,
    });
    entities.push(...monsters);
  }

  if (targets === "both" || targets === "players") {
    const players = dimension.getPlayers({
      location: { x: originX, y: originY, z: originZ },
      maxDistance: knockbackRadius,
    });
    entities.push(...players);
  }

  if (entities.length === 0) {
    return;
  }

  entities.forEach((entity) => {
    if (!entity || !entity.location) {
      return;
    }

    const deltaX = entity.location.x - originX;
    const deltaZ = entity.location.z - originZ;
    const distance = Math.hypot(deltaX, deltaZ);

    if (distance === 0) {
      return;
    }

    const normalizedX = ((deltaX / distance) * horizontalPower) / 4;
    const normalizedZ = ((deltaZ / distance) * horizontalPower) / 4;

    if (entity.typeId === "minecraft:player") {
      entity.applyKnockback(
        normalizedX,
        normalizedZ,
        horizontalPower,
        verticalPower
      );
    } else {
      entity.applyImpulse({ x: normalizedX, y: verticalPower, z: normalizedZ });
    }
  });
}

function applySetBonus(entity, armorSet, attacker) {
  switch (armorSet) {
    case "frankenstein":
      if (Math.random() < 0.1) {
        const monsters = entity.dimension.getEntities({
          families: ["monster"],
          location: entity.location,
          maxDistance: 5,
        });

        let maxCap = 10;
        let counterCap = 0;
        for (const target of monsters) {
          if (target.id !== entity.id && counterCap <= maxCap) {
            counterCap = counterCap + 1;
            entity.dimension.spawnEntity(
              "minecraft:lightning_bolt",
              target.location
            );
            entity.applyDamage(6);
          }
        }
        counterCap = 0;
      }
      break;

    case "lagoon":
      if (entity && attacker) {
        if (entity.isInWater && attacker.isInWater) {
          const presenceChance = 0.3;

          if (Math.random() < presenceChance) {
            const maxDistance = 6;

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

            nearbyEntities.forEach((target) => {
              if (
                target.id !== entity.id &&
                !hasEffect(target, "slowness", null)
              ) {
                target.addEffect("slowness", 20 * 5, { amplifier: 3 });

                target.applyImpulse({
                  x:
                    (target.location.x - entity.location.x) * 0.2 +
                    Math.random(),
                  y: 0.1 + Math.random() / 2,
                  z:
                    (target.location.z - entity.location.z) * 0.2 +
                    Math.random(),
                });
              }
            });

            const doubledDuration = 20 * 10;
            ["strength", "water_breathing", "conduit_power"].forEach(
              (effect) => {
                const currentEffect = hasEffect(entity, effect, null);
                if (currentEffect) {
                  entity.addEffect(effect, doubledDuration, {
                    amplifier: 2,
                  });
                }
              }
            );
            attacker.applyDamage(4);
          }
        } else {
          const presenceChance = 0.3;

          if (Math.random() < presenceChance) {
            const maxDistance = 4;

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

            nearbyEntities.forEach((target) => {
              if (
                target.id !== entity.id &&
                !hasEffect(target, "slowness", null)
              ) {
                target.addEffect("slowness", 20 * 5, { amplifier: 1 });

                target.applyImpulse({
                  x:
                    ((target.location.x - entity.location.x) * 0.1) / 2 +
                    Math.random() / 2,
                  y: 0.05 + Math.random() / 3,
                  z:
                    ((target.location.z - entity.location.z) * 0.1) / 2 +
                    Math.random() / 2,
                });
              }
            });

            const doubledDuration = 20 * 5;
            ["strength", "water_breathing", "conduit_power"].forEach(
              (effect) => {
                const currentEffect = hasEffect(entity, effect, null);
                if (currentEffect) {
                  entity.addEffect(effect, doubledDuration, {
                    amplifier: 1,
                  });
                }
              }
            );
          }
          attacker.applyDamage(4);
        }
      }
      break;

    case "mummy":
      const playerId = entity.id;
      const currentHitCount = playerHitCountMap.get(playerId) || 0;
      const newHitCount = currentHitCount + 1;

      if (newHitCount % 5 === 0) {
        entity.addEffect("regeneration", 20 * 2, { amplifier: 3 });
      }

      playerHitCountMap.set(playerId, newHitCount);
      break;

    case "reaper":
      const spectralChance = 0.5;
      if (Math.random() < spectralChance) {
        entity.dimension.spawnEntity(
          "arcedge_horr:b_rea_min_friendly",
          entity.location
        );
      }

      const thornsDamage = 3;
      const effectChance = 0.5;

      if (attacker && Math.random() < effectChance) {
        attacker.applyDamage(thornsDamage);
      }
      break;
    /* case "skeleton":
      const knockChance = 0.1;
      if (Math.random() < knockChance) {
        const areaDamage = 4;
        const maxDistance = 8;

        const nearbyMonsters = entity.dimension.getEntities({
          families: ["monster"],
          location: entity.location,
          maxDistance: maxDistance,
        });

        const nearbyPlayers = entity.dimension.getPlayers({
          location: entity.location,
          maxDistance: maxDistance,
        });

        for (const monster of nearbyMonsters) {
          if (monster.id !== entity.id) {
            monster.applyDamage(8);
            monster.applyKnockback(
              Math.random() * 2 - 1,
              Math.random() * 2 - 1,
              Math.random(),
              Math.random()
            );
          }
        }

        if (isPvPEnabled()) {
          for (const nearbyPlayer of nearbyPlayers) {
            if (nearbyPlayer.id !== entity.id) {
              nearbyPlayer.applyDamage(areaDamage * 0.5);
            }
          }
        }
      }

      if (!hasEffect(entity, "night_vision", null)) {
        entity.addEffect("night_vision", 20 * 300, { amplifier: 0 });
      }
      if (!hasEffect(entity, "resistance", null)) {
        entity.addEffect("resistance", 20 * 5, { amplifier: 1 });
      }
      break;

    case "spider":
      const eggSpawnChance = 0.2;

      const existingEggs = entity.dimension.getEntities({
        type: "arcedge_horr:b_spi_egg_f",
        maxDistance: 6,
        location: entity.location,
      }).length;

      const existingSpiders = entity.dimension.getEntities({
        type: "arcedge_horr:b_spi_min_f",
        maxDistance: 6,
        location: entity.location,
      }).length;

      if (
        Math.random() < eggSpawnChance &&
        existingEggs === 0 &&
        existingSpiders < 10
      ) {
        entity.dimension.spawnEntity(
          "arcedge_horr:b_spi_egg_f",
          entity.location
        );
      }

      if (!hasEffect(entity, "speed", null)) {
        entity.addEffect("speed", 100, { amplifier: 1 });
      }

      if (!hasEffect(entity, "jump_boost", null)) {
        entity.addEffect("jump_boost", 100, { amplifier: 1 });
      }

      break; */
    case "vampire":
      const healthStealChance = 0.3;
      const batSummonChance = 0.6;
      const randomizer = Math.random();
      const randomizer2 = Math.random();

      const nearbyBats = entity.dimension.getEntities({
        type: "minecraft:bat",
        location: entity.location,
        maxDistance: 16,
      });

      for (const bat of nearbyBats) {
        system.run(() => bat.remove());
      }

      if (attacker.typeId === "minecraft:player" && isPvPEnabled()) {
        if (randomizer < healthStealChance) {
          attacker.applyDamage(6);
          entity.addEffect("instant_health", 5, { amplifier: 1 });
          attacker.addEffect("weakness", 20 * 3, { amplifier: 5 });
          attacker.addEffect("slowness", 20 * 5, { amplifier: 10 });

          if (randomizer2 < batSummonChance) {
            for (let i = 0; i < 3; i++) {
              const randomOffset = {
                x: Math.random() * 2 - 1,
                y: Math.random(),
                z: Math.random() * 2 - 1,
              };
              attacker.dimension.spawnEntity("minecraft:bat", {
                x: attacker.location.x + randomOffset.x,
                y: attacker.location.y + randomOffset.y,
                z: attacker.location.z + randomOffset.z,
              });
            }

            attacker.addEffect("blindness", 20 * 2, { amplifier: 0 });
            attacker.applyImpulse({
              x: 0,
              y: Math.random(),
              z: 0,
            });
          }
        }
      } else {
        if (randomizer < healthStealChance) {
          attacker.applyDamage(4);
          entity.addEffect("instant_health", 5, { amplifier: 1 });
          attacker.addEffect("weakness", 20 * 5, { amplifier: 1 });
          attacker.addEffect("slowness", 20 * 10, { amplifier: 10 });

          if (randomizer2 < batSummonChance) {
            for (let i = 0; i < 3; i++) {
              const randomOffset = {
                x: Math.random() * 2 - 1,
                y: Math.random(),
                z: Math.random() * 2 - 1,
              };
              attacker.dimension.spawnEntity("minecraft:bat", {
                x: attacker.location.x + randomOffset.x,
                y: attacker.location.y + randomOffset.y,
                z: attacker.location.z + randomOffset.z,
              });
              attacker.applyKnockback(
                Math.random(),
                Math.random(),
                Math.random() + Math.random(),
                Math.random() + Math.random()
              );
            }
          }
        }
      }
      break;
    case "werewolf":
      const bonusRoarDamage = 4;
      const bonusRoarRadius = 8;
      const bonusRoarChance = 0.3;

      if (Math.random() < bonusRoarChance) {
        const affectedEntities = entity.dimension.getEntities({
          location: entity.location,
          families: ["monster"],
          maxDistance: bonusRoarRadius,
        });

        for (const target of affectedEntities) {
          if (target.id !== entity.id) {
            if (!hasEffect(target, "slowness", null)) {
              target.addEffect("slowness", 20 * 10, { amplifier: 5 });
              target.applyDamage(bonusRoarDamage);
            }

            vanillaKnockback(
              entity.dimension.id,
              entity.location.x,
              entity.location.y,
              entity.location.z,
              2,
              1.2,
              0.3,
              "entities"
            );
          }
        }
      }
      break;
    case "witch":
      const enhancedPoisonLevel = 1;
      const enhancedPoisonDuration = 10 * 20;

      if (!hasEffect(attacker, "poison", null)) {
        attacker.addEffect("poison", enhancedPoisonDuration, {
          amplifier: enhancedPoisonLevel,
        });
      }

      const regenDuration = 20 * 3;
      if (!hasEffect(entity, "regeneration", null)) {
        entity.addEffect("regeneration", regenDuration, { amplifier: 1 });
      }
      break;

    case "zombie":
      system.run(() => {
        const healthComponent = entity.getComponent("minecraft:health");
        if (!healthComponent) return;

        const isBelowHalfHealth =
          healthComponent.currentValue <= healthComponent.effectiveMax * 0.5;

        if (isBelowHalfHealth) {
          const setBonusRegenDuration = 20 * 4;
          const setBonusRegenAmplifier = 2;

          if (!hasEffect(entity, "regeneration", null)) {
            entity.addEffect("regeneration", setBonusRegenDuration, {
              amplifier: setBonusRegenAmplifier,
            });
          }
        }
      });
      break;
  }
}

function handleArmorEffects(entity, attacker) {
  if (!entity || !isWearingRelevantArmor(entity)) {
    return;
  }

  const setCounts = getArmorSetForEntity(entity);

  for (const [armorSet, piecesEquippedExtract] of Object.entries(setCounts)) {
    try {
      console.warn("piecesEquippedExtract: " + piecesEquippedExtract);
      const piecesEquipped = piecesEquippedExtract ?? 0;
      if (piecesEquipped && piecesEquipped > 0) {
        applyBaseEffects(entity, armorSet, piecesEquipped, attacker);
      }
      if (piecesEquipped === 4) {
        applySetBonus(entity, armorSet, attacker);
      }
    } catch {}
  }
}

world.afterEvents.entityHurt.subscribe((event) => {
  try {
    let entity = event.hurtEntity;
    let attacker = event.damageSource.damagingEntity;
    let cause = event.damageSource.cause;
    if (cause === "magic") {
      return;
    } else {
      handleArmorEffects(entity, attacker);
    }
  } catch {
    return;
  }
});

function isPvPEnabled() {
  return world.gameRules.pvp;
}
