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

const animatedWeaopons = ["hb_hr:scythe", "hb_hr:charged_scythe", "hb_hr:chainsaw"];

export function weaponsAnims() {
  // Subscribe to the player spawn event
  world.afterEvents.playerSpawn.subscribe((spawn) => {
    const { player: player } = spawn;
    // On player spawn, remove weapon animation tag if it exists
    if (player.hasTag("hb_hr:weapon_anim")) {
      player.removeTag("hb_hr:weapon_anim");
    }
  });

  // Subscribe to entity hit events to trigger weapon animations
  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;
    // Only continue if the held item is one of the animated weapons
    if (!animatedWeaopons.includes(heldTypeId)) return;
    // Prevent triggering animation if it's already playing
    if (hitter.hasTag("hb_hr:weapon_anim")) return;

    hitter.addTag("hb_hr:weapon_anim");

    // Select the animation type based on the weapon
    let animType;
    switch (heldTypeId) {
      case "hb_hr:charged_scythe":
      case "hb_hr:scythe":
        animType = "animation.hb_hr.scythe.fp_tp_attack";
        break;
      case "hb_hr:chainsaw":
        animType = "animation.hb_hr.chainsaw.fp_tp_attack";
        break;
      default:
        animType = "animation.hb_hr.scythe.fp_tp_attack";
        break;
    }

    // Play the selected animation
    hitter.playAnimation(animType);

    // Remove the animation tag after 9.2 ticks
    system.runTimeout(() => {
      hitter.removeTag("hb_hr:weapon_anim");
    }, 9.2);
  });
}

// Helper function to convert item ID prefix from "hb_hr:" to "hb_hr."
function removeChargedPrefix(id) {
  return id.replace("hb_hr:", "hb_hr.");
}
