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

/**
 * Ancient armor: reflect push on attacker when wearer is hurt.
 * - Player attacker: knockback
 * - Non-player attacker: impulse to attacker + splash impulse to nearby entities
 */
export const ancient_armor = {
  id: "ancient",
  intervaloTicks: 10,
  piezas: [
    "dungeon:ancient_helmet",
    "dungeon:ancient_chestplate",
    "dungeon:ancient_leggings",
    "dungeon:ancient_boots"
  ],

  verificar(equip) {
    return this.piezas.every((id, i) => {
      const slot = [EquipmentSlot.Head, EquipmentSlot.Chest, EquipmentSlot.Legs, EquipmentSlot.Feet][i];
      const item = equip.getEquipment(slot);
      return item && item.typeId === id;
    });
  },

  accion(_player, _health) { /* no-op */ }
};

(function initAncientReflectPush() {
  const PLAYER_ID = "minecraft:player";
  const attackerPush = { strength: 3.2, vertical: 0.8 }; // for non-player impulse
  const playerKB = { strength: 1.8, vertical: 1.35 }; // for player knockback
  const splash = { radius: 6, strength: 1.6, vertical: 0.4 };

  world.afterEvents.entityHurt.subscribe((ev) => {
    const victim = ev.hurtEntity;
    if (!victim || victim.typeId !== PLAYER_ID) return;

    const equip = victim.getComponent("equippable");
    if (!equip || !ancient_armor.verificar(equip)) return;

    const attacker = ev.damageSource?.damagingEntity;
    if (!attacker || attacker === victim) return;

    const dx = attacker.location.x - victim.location.x;
    const dz = attacker.location.z - victim.location.z;
    const mag = Math.hypot(dx, dz) || 1;
    const dirX = dx / mag;
    const dirZ = dz / mag;

    try {
      if (attacker.typeId === PLAYER_ID) {
        // Player attacker: knockback
        attacker.applyKnockback(dirX, dirZ, playerKB.strength, playerKB.vertical);
      } else {
        // Non-player attacker: impulse
        victim.dimension.spawnParticle("minecraft:knockback_roar_particle", attacker.location);
        attacker.applyImpulse({ x: dirX * attackerPush.strength, y: attackerPush.vertical, z: dirZ * attackerPush.strength });

        // Splash: push other nearby entities around the attacker (excluding attacker & victim)
        const nearby = attacker.dimension.getEntities({
          location: attacker.location,
          maxDistance: splash.radius
        });

        for (const e of nearby) {
          if (e.id === attacker.id || e.id === victim.id) continue;
          // Skip items/xp or other non-pushables
          const t = e.typeId;
          if (t === "minecraft:item" || t === "minecraft:xp_orb" || t === "minecraft:leash_knot") continue;

          // Push them in the same general direction away from the victim
          e.applyImpulse({ x: dirX * splash.strength, y: splash.vertical, z: dirZ * splash.strength });
        }
      }
      try {
        victim.dimension.spawnParticle("minecraft:knockback_roar_particle", attacker.location);
      } catch { }

    } catch {
    }
  });
})();
