import { world, ItemStack } from "@minecraft/server";
import { randomKnockback } from "./knockbacks";

// List of base weapons that can be charged through kills
const chargeableWeapons = ["hb_hr:scythe"];
const KillThreshold = 10;
const HitToRevertThreshold = 20;

export function chargedWeapons() {
  // Handle killing entities to CHARGE weapons
  world.afterEvents.entityDie.subscribe((event) => {
    if (!event || event.deadEntity.typeId === "minecraft:player") return;

    const damager = event.damageSource?.damagingEntity;
    if (!damager || damager.typeId !== "minecraft:player") return;

    const equippable = damager.getComponent("equippable");
    const heldItem = equippable?.getEquipment("Mainhand");
    if (!heldItem) return;

    const heldTypeId = heldItem.typeId;

    if (!chargeableWeapons.includes(heldTypeId)) return;

    const scoreKey = `${heldTypeId}_score`;
    let score = heldItem.getDynamicProperty(scoreKey) ?? 0;

    score++;
    heldItem.setDynamicProperty(scoreKey, score);

    if (score >= KillThreshold) {
      const chargedTypeId = addChargedToPrefix(heldTypeId);
      const chargedItem = new ItemStack(chargedTypeId);

      transferDurability(heldItem, chargedItem);
      chargedItem.setDynamicProperty(`${chargedTypeId}_hit_score`, 0);

      equippable.getEquipmentSlot("Mainhand").setItem(chargedItem);
    } else {
      equippable.getEquipmentSlot("Mainhand").setItem(heldItem);
    }
  });

  // Handle entity hits to REVERT charged weapons
  world.afterEvents.entityHitEntity.subscribe((event) => {
    const hitter = event.damagingEntity;
    if (!hitter || hitter.typeId !== "minecraft:player") return;

    const equippable = hitter.getComponent("equippable");
    const heldItem = equippable?.getEquipment("Mainhand");
    if (!heldItem) return;

    const heldTypeId = heldItem.typeId;
    if (!isChargedWeapon(heldTypeId)) return;

    const scoreKey = `${heldTypeId}_hit_score`;
    let hitScore = heldItem.getDynamicProperty(scoreKey) ?? 0;

    hitScore++;
    heldItem.setDynamicProperty(scoreKey, hitScore);

    if (hitScore >= HitToRevertThreshold) {
      const normalTypeId = removeChargedPrefix(heldTypeId);
      const normalItem = new ItemStack(normalTypeId);

      transferDurability(heldItem, normalItem);
      normalItem.setDynamicProperty(`${normalTypeId}_score`, 0); // reset charge score

      equippable.getEquipmentSlot("Mainhand").setItem(normalItem);
    } else {
      equippable.getEquipmentSlot("Mainhand").setItem(heldItem);
    }
  });
}

// Converts "hb_hr:scythe" to "hb_hr:charged_scythe"
function addChargedToPrefix(id) {
  return id.replace(/^hb_hr:/, "hb_hr:charged_");
}

// Converts "hb_hr:charged_scythe" to "hb_hr:scythe"
function removeChargedPrefix(id) {
  return id.replace(/^hb_hr:charged_/, "hb_hr:");
}

// Checks if the weapon is a charged variant
function isChargedWeapon(id) {
  return /^hb_hr:charged_/.test(id);
}

// Transfers durability from one item to another
function transferDurability(fromItem, toItem) {
  const fromDurability = fromItem.getComponent("durability");
  const toDurability = toItem.getComponent("durability");
  if (fromDurability && toDurability) {
    toDurability.damage = fromDurability.damage;
  }
}
