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

const SOUND_ID = "halo_energy_sword_attack";

const BASE_HORIZONTAL_FORCE = 2.4;
const VERTICAL_FORCE = 0.1;
const SPRINT_MULTIPLIER = 2.0;

const SWORD_PARTICLES = {
  "halo:energy_sword": "halo:energy_sword_particle",
  "halo:energy_sword_red": "halo:energy_sword_red_particle",
  "halo:energy_sword_green": "halo:energy_sword_green_particle"
};

world.afterEvents.entityHurt.subscribe(ev => {
  const attacker = ev.damageSource.damagingEntity;
  const target = ev.hurtEntity;

  if (!attacker || !target) return;

  let mainhand;

  const equipment = attacker.getComponent("minecraft:equippable");
  if (equipment) {
    mainhand = equipment.getEquipment("Mainhand");
  }

  if (!mainhand) return;

  const particleId = SWORD_PARTICLES[mainhand.typeId];
  if (!particleId) return;

  attacker.dimension.playSound(SOUND_ID, attacker.location);

  attacker.dimension.spawnParticle(
    particleId,
    {
      x: attacker.location.x,
      y: attacker.location.y + 1.5,
      z: attacker.location.z
    }
  );

  const view = attacker.getViewDirection();

  let horizontalForce = BASE_HORIZONTAL_FORCE;

  if (attacker.isSprinting) {
    horizontalForce *= SPRINT_MULTIPLIER;
  }

  attacker.applyKnockback(
    view.x,
    view.z,
    horizontalForce,
    VERTICAL_FORCE
  );
});
