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

const CONFIG = {
    ids: {
        item: "nz:kirin",
        projectile: "nz:kirin_bullet",
        particle: "nz:raio" 
    },
    combat: {
        cooldown: 0.0,
        throwForce: 3.0,
        hitRadius: 15.0
    },
    burnEffect: {
        duration: 9,
        interval: 1.0,
        damage: 200
    }
};

const cooldowns = new Map();

function applyAmaterasu(target) {
    if (!target) return;
    
    target.dimension.spawnParticle(CONFIG.ids.particle, target.location);
    target.applyDamage(CONFIG.combat.burnEffect?.damage || 3);

    for (let i = 1; i <= CONFIG.burnEffect.duration; i++) {
        system.runTimeout(() => {
            if (target && target.isValid()) {
                try {
                    const loc = target.location;
                    target.dimension.spawnParticle(CONFIG.ids.particle, {x: loc.x, y: loc.y + 1, z: loc.z});
                    target.applyDamage(CONFIG.burnEffect.damage, { cause: "magic" });
                } catch (e) {}
            }
        }, i * 20 * CONFIG.burnEffect.interval);
    }
}

function trackProjectile(projectile, owner) {
    let lastLocation = projectile.location;
    const dimension = projectile.dimension;

    const intervalId = system.runInterval(() => {
        if (projectile.isValid()) {
            lastLocation = projectile.location;
            try {
                dimension.spawnParticle(CONFIG.ids.particle, lastLocation);
            } catch(e){}
            return; 
        }

        system.clearRun(intervalId); 

        // Quando o projétil deixa de existir, consideramos que atingiu o chão
        try {
            dimension.runCommand(`summon lightning_bolt ${lastLocation.x} ${lastLocation.y} ${lastLocation.z}`);
        } catch(e){}

        // Busca todos os alvos no raio
        const entities = dimension.getEntities({
            location: lastLocation,
            maxDistance: CONFIG.combat.hitRadius,
            excludeFamilies: ["inanimate", "item"], 
            excludeTypes: [CONFIG.ids.projectile]   
        });

        // Aplica efeito em todos os NPCs diferentes do dono
        if (entities.length > 0) {
            entities.forEach(target => {
                if (target.id !== owner.id) {
                    owner.sendMessage(`§e[Kirin] Alvo atingido: ${target.typeId}`);
                    applyAmaterasu(target);
                }
            });
        } else {
            dimension.spawnParticle("minecraft:large_explosion", lastLocation);
        }

    }, 1);
}

world.afterEvents.itemUse.subscribe((event) => {
    const player = event.source;
    const item = event.itemStack;

    if (!item || item.typeId !== CONFIG.ids.item) return;

    const agora = Date.now();
    const ultimoUso = cooldowns.get(player.id) || 0;
    if (agora - ultimoUso < CONFIG.combat.cooldown * 1000) {
        player.sendMessage("§cAguarde para usar novamente.");
        return;
    }
    cooldowns.set(player.id, agora);

    system.runTimeout(() => {
        const head = player.getHeadLocation();
        const view = player.getViewDirection();

        // Ponto alvo na direção do olhar (20 blocos à frente)
        const targetPos = {
            x: head.x + view.x * 20,
            y: head.y + view.y * 20,
            z: head.z + view.z * 20
        };

        // Spawn do projétil acima do ponto alvo
        const spawnPos = {
            x: targetPos.x,
            y: targetPos.y + 30,
            z: targetPos.z
        };

        try {
            const projectile = player.dimension.spawnEntity(CONFIG.ids.projectile, spawnPos);

            // Impulso apenas para baixo
            const impulse = { x: 0, y: -CONFIG.combat.throwForce, z: 0 };
            projectile.applyImpulse(impulse);

            trackProjectile(projectile, player);

        } catch (e) {
            player.sendMessage("§cErro ao lançar projétil.");
        }
    }, 20);
});