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

const CONFIG = {
    ids: {
        item: "nz:jutsu_amaterasu",
        projectile: "nz:jutsu_amaterasu_bullet",
        particle: "nz:amaterasu" 
    },
    combat: {
        cooldown: 0.1,
        throwForce: 3.0,
        hitRadius: 5.0 // Raio de detecção (aumentar pode fazer pegar mais de uma entidade como alvo)
    },
    burnEffect: {
        duration: 15,    // 15 segundos
        interval: 1.0,   // Dano a cada 1 segundo
        damage: 45       // Dano por tick
    }
};

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); 

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

        const target = entities.find(e => e.id !== owner.id);

        if (target) {
            owner.sendMessage(`§e[Amaterasu] 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);

    // Delay de 0.3 segundos (6 ticks) antes de lançar o projétil
    system.runTimeout(() => {
        const head = player.getHeadLocation();
        const view = player.getViewDirection();
        const spawnPos = { 
            x: head.x + view.x * 1.5, 
            y: head.y + view.y * 1.5, 
            z: head.z + view.z * 1.5 
        };

        try {
            const projectile = player.dimension.spawnEntity(CONFIG.ids.projectile, spawnPos);
            
            const impulse = {
                x: view.x * CONFIG.combat.throwForce,
                y: view.y * CONFIG.combat.throwForce,
                z: view.z * CONFIG.combat.throwForce
            };
            projectile.applyImpulse(impulse);
            trackProjectile(projectile, player);

        } catch (e) {
            player.sendMessage("§cErro ao lançar projétil.");
        }
    }, 10); // 6 ticks = 0.3 segundos
});