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

const playerStates = new Map();

world.afterEvents.entityHitEntity.subscribe((event) => {
    handleAttack(event.damagingEntity);
});

function handleAttack(source) {
    if (!source.hasComponent("minecraft:equippable")) return;
    
    const heldItem = source.getComponent("minecraft:equippable").getEquipment(EquipmentSlot.Mainhand);
    if (heldItem?.typeId !== "mc_ark:spear") return;

    const now = system.currentTick;
    let state = playerStates.get(source.id) || { lastAttack: 0 };
    
    if (now - state.lastAttack >= 2) {
        executeLongRangeAttack(source);
        state.lastAttack = now;
        playerStates.set(source.id, state);
    } 
} 

function executeLongRangeAttack(source) {
    const sourceLoc = source.location;
    const viewDir = source.getViewDirection();
    const normDir = {
        x: viewDir.x / Math.sqrt(viewDir.x**2 + viewDir.y**2 + viewDir.z**2),
        y: viewDir.y / Math.sqrt(viewDir.x**2 + viewDir.y**2 + viewDir.z**2),
        z: viewDir.z / Math.sqrt(viewDir.x**2 + viewDir.y**2 + viewDir.z**2)
    };

    source.dimension.getEntities({
        location: sourceLoc,
        maxDistance: 5
    }).forEach(entity => {
        if (entity.id !== source.id) {
            const entLoc = entity.location;
            const entDir = {
                x: entLoc.x - sourceLoc.x,
                y: entLoc.y - sourceLoc.y,
                z: entLoc.z - sourceLoc.z
            };
            const distance = Math.sqrt(entDir.x**2 + entDir.y**2 + entDir.z**2);
            const dotProduct = (normDir.x*entDir.x + normDir.y*entDir.y + normDir.z*entDir.z) / distance;
            
            if (dotProduct > 0.5) {
                entity.applyDamage(6, {
                    cause: EntityDamageCause.entityAttack,
                    damagingEntity: source
                });

                // Efectos visuales usando solo la API (más confiable)
                source.dimension.spawnParticle("minecraft:crit", entLoc);
                source.dimension.spawnParticle("minecraft:critical_hit_emitter", entLoc);
            }
        }
    }); 

    // Efectos adicionales del ataque
    source.playSound("item.trident.throw");
    source.dimension.spawnParticle("minecraft:crit", sourceLoc);
}