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

world.afterEvents.entityHitEntity.subscribe(eventData => {
  const damager = eventData.damagingEntity;
  const target = eventData.hitEntity;
  const damagerEquippable = damager.getComponent("equippable");
  if (!damagerEquippable) return;

  const itemUsed = damagerEquippable.getEquipment("Mainhand");
  if (!itemUsed) return;

  const id = itemUsed.typeId;
  if (id !== "faf:ice_dragon_sword" && id !== "faf:fire_dragon_sword") return;
  if (!target.matches({ excludeFamilies: ["golem", "elder_golem", "irongolem", "snowgolem"] })) return;

  const pitchRange = Math.random() * 0.4 + 0.8;
  target.applyDamage(1, { cause: "override", damagingEntity: damager });
  damager.playSound("mob.mod.sting", { pitch: pitchRange, location: damager.location, volume: 0.5 });

  if (id === "faf:ice_dragon_sword") {
    target.addEffect("slowness", 300, { amplifier: 1, showParticles: true });
  }

  if (id === "faf:fire_dragon_sword") {
    target.setOnFire(4, true);
  }

  const itemEnchantable = itemUsed.getComponent("enchantable");
  const unbreakingLevel = itemEnchantable?.getEnchantment("unbreaking")?.level ?? 0;
  const breakChance = 100 / (unbreakingLevel + 1);
  if (Math.random() * 100 > breakChance) return;

  const itemDurability = itemUsed.getComponent("durability");
  if (!itemDurability) return;

  let shouldDamage = true;
  if (damager.typeId === "minecraft:player" && damager.matches({ gameMode: GameMode.creative })) {
    shouldDamage = false;
  }

  if (shouldDamage) {
    const remaining = itemDurability.maxDurability - itemDurability.damage;
    if (remaining <= 1) {
      damager.playSound("random.break", { pitch: 0.9, location: damager.location, volume: 1 });
      damagerEquippable.setEquipment("Mainhand", null);
    } else {
      itemDurability.damage += 1;
      damagerEquippable.setEquipment("Mainhand", itemUsed);
    }
  }
});