import { EquipmentSlot, system } from "@minecraft/server";
import { damageItem } from "../inventory_utils";
import * as utils from '../utils';

export async function onEntityHit(event) {
	const attacker = event.damagingEntity;
	if (!attacker || attacker.typeId !== "minecraft:player") return;
	
	const target = event.hitEntity;
	if (!target) return;

	const heldItem = attacker
		.getComponent("minecraft:equippable")
		?.getEquipment(EquipmentSlot.Mainhand);
	if (!heldItem || heldItem.typeId !== "tcs_cwp:vampire_fang") return;

	// Punch animations
	attacker.startItemCooldown("tcs_cwp_vampire_fang_punch", 8);
	attacker.playAnimation("animation.goe_rwp.vampire_fang.tp_attack");

	// Check particle cooldown (20 ticks)
	const currentTick = system.currentTick;
	const PARTICLE_COOLDOWN = 20;
	const lastParticleTick = attacker.getDynamicProperty("tcs_cwp:vampire_fang_last_particle_tick");
	const canShowParticles = (lastParticleTick === undefined || (currentTick - lastParticleTick >= PARTICLE_COOLDOWN));

	utils.playSound(target, `@a[x=${target.location.x}, y=${target.location.y}, z=${target.location.z}, r=7]`, 'tcs_cwp:vampire_fang_punch');
	
	if (canShowParticles) {
		target.runCommandAsync(`particle tcs_cwp:vampirism ~ ~ ~`);
		target.runCommandAsync(`particle tcs_cwp:vampirism1 ~ ~ ~`);
		utils.playSound(attacker, `@a[x=${attacker.location.x}, y=${attacker.location.y}, z=${attacker.location.z}, r=3]`, 'tcs_cwp:vampire_fang_heal');
		attacker.setDynamicProperty("tcs_cwp:vampire_fang_last_particle_tick", currentTick);
	}
	
	
	// Heal player for 1 HP (½ heart)
	const health = attacker.getComponent("health");
	if (health) {
		const currentHealth = health.currentValue;
		const maxHealth = health.effectiveMax;
		const newHealth = Math.min(currentHealth + 1, maxHealth);
		health.setCurrentValue(newHealth);
	}

	damageItem(attacker, EquipmentSlot.Mainhand, 1);
}

