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


export async function onItemUse(event) {
	let player = event.source;
	let itemId = event.itemStack.typeId;
	let cd = player.getItemCooldown("tcs_cwp:tornado_wand");
	if (cd > 0) return;
    let projectileId = "tcs_cwp:tornado_wand_projectile";

    player.startItemCooldown("tcs_cwp_tornado_wand_animation_shoot", 15);
    player.runCommandAsync(`playanimation @s animation.tcs_cwp.amethyst_staff.shoot.tp`);
    
    utils.playSound(player, `@a[x=${player.location.x}, y=${player.location.y}, z=${player.location.z}, r=15]`, 'tcs_cwp:tornado_wand_use');
	let shootAngle = [ 0 ];
    let velocity = 1.6;

    const direction = Vector3.copy(player.getViewDirection());
	const spawnDirection = Vector3.unit(direction);
	const projectileVelocity = direction.multiply(velocity);

	let playerLocation = Vector3.copy(player.location);
	let projectileSpawn = playerLocation.add(Vector3.Up.multiply(1.5)).add(spawnDirection);
    
    const projectile =  player.dimension.spawnEntity(projectileId, projectileSpawn.toLocation());
	let projectileComponent = projectile.getComponent("minecraft:projectile");
	projectileComponent.owner = player;
	projectile.applyImpulse(projectileVelocity.toLocation());
	//game.debug(`view direction: ${Vector3.copy(player.getViewDirection()).toCommand()}` );
	//game.debug(`projectile direction: ${spawnDirection.toCommand()}` );
	//game.debug(`projectile impulse: ${projectileVelocity.toCommand()}` );
	player.startItemCooldown("tcs_cwp:tornado_wand", 60);
	    damageItem(player, EquipmentSlot.Mainhand, 1);
}

//Tornado system (liftup)
export async function onTick() {
    try {
        const currentTick = system.currentTick;
        const DAMAGE_INTERVAL = 20;
        
        const tornados = await utils.getEntities("tcs_cwp:tornado");
        
        for (const tornado of tornados) {
            if (!tornado || !tornado.isValid()) continue;
            
            // Check timer for this specific tornado
            let lastDamageTick = tornado.getDynamicProperty("tcs_cwp:tornado_last_damage_tick");
            if (lastDamageTick === undefined) lastDamageTick = 0;
            const shouldApplyDamage = (currentTick - lastDamageTick >= DAMAGE_INTERVAL);
            
            if (shouldApplyDamage) {
                tornado.setDynamicProperty("tcs_cwp:tornado_last_damage_tick", currentTick);
            }
            
            const nearbyEntities = await utils.getEntitiesInRange(undefined, tornado.dimension, tornado.location, 0, 3);
            
            for (const entity of nearbyEntities) {
                if (!entity || !entity.isValid()) continue;
                if (entity.id === tornado.id || entity.typeId === "tcs_cwp:tornado") continue;
                
                const distance = Vector3.distance(tornado.location, entity.location);
                
                if (distance <= 4) {
                    const forceStrength = Math.max(0.075, 0.25 - (distance / 10.0));
                    
                    // if (entity.typeId === "minecraft:player") {
                    //     const knockbackStrength = forceStrength * 0.8;
                    //     const horizontalForce = 20;
                    //     const randomX = (Math.random() - 0.5) * horizontalForce;
                    //     const randomZ = (Math.random() - 0.5) * horizontalForce;
                        
                    //     utils.applyKnockback(entity, randomX, randomZ, knockbackStrength, forceStrength);
                    // } else {
                    const upwardImpulse = { x: 0, y: forceStrength * 2, z: 0 };
                    entity.applyImpulse(upwardImpulse);
                    
                    const horizontalForce = 0.1;
                    const randomX = (Math.random() - 0.5) * horizontalForce;
                    const randomZ = (Math.random() - 0.5) * horizontalForce;
                    entity.applyImpulse({ x: randomX, y: 0, z: randomZ });
                    // }
                    
                    // Apply damage every 20 ticks (1 second) - 2 damage (1 heart)
                    if (shouldApplyDamage) {
                        utils.applyDamage(entity, 2);
                    }
                }
            }
        }
    } catch (error) {
    }
}

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

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

	// Punch animations
	attacker.startItemCooldown("tcs_cwp_vampire_fang_punch", 8);
	attacker.playAnimation("animation.tcs_cwp.staff.tp_hit");
}