// vento_combos.js – MACHADO DOS VENTOS (dano via eventos + knockback consistente + combo 4 original)
import { world, system, EquipmentSlot } from "@minecraft/server";

const lastValidHit = new Map();
const combo4Cooldown = new Map();
const comboTimeouts = new Map();
const danoRemoveTimeouts = new Map();

const MIN_TICKS_BETWEEN_HITS = 10;
const COMBO4_COOLDOWN_TICKS = 15;

export function enableVentoCombos() {
    function machadoVentos(player) {
        const equip = player.getComponent("minecraft:equippable");
        if (!equip) return false;
        const item = equip.getEquipment(EquipmentSlot.Mainhand);
        return item?.typeId === "well:espada_humano4";
    }

    function getScore(player, obj) {
        try {
            return world.scoreboard.getObjective(obj)?.getScore(player) ?? 0;
        } catch {
            return 0;
        }
    }

    function limparCamera(player, combo = 0) {
        try { player.runCommand("camera @s clear"); } catch {}
        try { player.runCommand("scoreboard players set @s combo 0"); } catch {}

        // Remove knockback após 2s apenas se não for combo 4
        if (combo !== 4) {
            system.runTimeout(() => {
                try { player.runCommand("event entity @s remove_knockback"); } catch {}
            }, 40);
        }
    }

    function ativarDanoArea(player, eventoDano) {
        try { player.runCommand("event entity @s remove_danos"); } catch {}

        if (danoRemoveTimeouts.has(player.id)) {
            danoRemoveTimeouts.get(player.id)();
            danoRemoveTimeouts.delete(player.id);
        }

        try { player.runCommand(`event entity @s ${eventoDano}`); } catch {}

        const timeout = system.runTimeout(() => {
            try { player.runCommand("event entity @s remove_danos"); } catch {}
            danoRemoveTimeouts.delete(player.id);
        }, 20);

        danoRemoveTimeouts.set(player.id, () => system.clearRun(timeout));
    }

    function processarHit(player) {
        const agora = system.currentTick;
        const cooldownEnd = combo4Cooldown.get(player.id);
        if (cooldownEnd && agora < cooldownEnd) return;

        const ultimoHit = lastValidHit.get(player.id) || 0;
        if (agora - ultimoHit < MIN_TICKS_BETWEEN_HITS) return;

        lastValidHit.set(player.id, agora);

        const furia = getScore(player, "furia");
        if (furia <= 0) return;

        if (comboTimeouts.has(player.id)) {
            comboTimeouts.get(player.id)();
            comboTimeouts.delete(player.id);
        }

        // Knockback em todo hit válido (incluindo o que inicia o combo 4)
        try { player.runCommand("event entity @s add_knockback"); } catch {}

        player.runCommand("scoreboard players add @s combo 1");
        player.runCommand("scoreboard players set @s stamina_player 0");
        player.runCommand("scoreboard players set @s animacao_esquiva 0");
        player.runCommand("scoreboard players remove @s[scores={combo=3..}] furia 1");
        player.runCommand("scoreboard players set @s[scores={combo=5..}] combo 0");
        player.runCommand("execute as @s[scores={combos_animacoes=1,combo=4..5,furia=1..}] at @s run scoreboard players remove @s furia 2");

        const cmds = [
            "effect @s[scores={combos_animacoes=1,combo=1,furia=1..}] weakness 2 30 true",
            "effect @s[scores={combos_animacoes=1,combo=1,furia=1..}] resistance 7 50 true",
            "effect @s[scores={combos_animacoes=1,combo=1,furia=1..}] slowness 2 1 true",
            "execute as @s[scores={combos_animacoes=1,combo=4..5,furia=1..}] at @s run particle well:furacao_grande",
            "playanimation @s[scores={combos_animacoes=1,combo=1,furia=1..}] animation.js_armor3.espada1",
            "playanimation @s[scores={combos_animacoes=1,combo=2,furia=1..}] animation.js_armor3.espada2",
            "playanimation @s[scores={combos_animacoes=1,combo=3,furia=1..}] animation.js_armor3.espada3",
            "playanimation @s[scores={combos_animacoes=1,combo=4,furia=1..}] animation.machadao.humano.combo3",
            "playanimation @s[scores={combos_animacoes=1,combo=4,furia=1..}] animation.machadao.humano.surgir_terra",
            "titleraw @s[scores={classe_humana=1,combo=4..5,furia=1..100}] actionbar {\"rawtext\":[{\"translate\":\"furia.2\"}]}",
            "titleraw @s[scores={classe_humana=1,combo=4..5,furia=..0}] actionbar {\"rawtext\":[{\"translate\":\"dialogue.furia.vazia\"}]}",
            "execute as @s[scores={classe_humana=1,combo=4..5,furia=100}] run title @s title furia_bar10",
            "execute as @s[scores={classe_humana=1,combo=4..5,furia=90..99}] run title @s title furia_bar9",
            "execute as @s[scores={classe_humana=1,combo=4..5,furia=80..89}] run title @s title furia_bar8",
            "execute as @s[scores={classe_humana=1,combo=4..5,furia=70..79}] run title @s title furia_bar7",
            "execute as @s[scores={classe_humana=1,combo=4..5,furia=60..69}] run title @s title furia_bar6",
            "execute as @s[scores={classe_humana=1,combo=4..5,furia=50..59}] run title @s title furia_bar5",
            "execute as @s[scores={classe_humana=1,combo=4..5,furia=40..49}] run title @s title furia_bar4",
            "execute as @s[scores={classe_humana=1,combo=4..5,furia=30..39}] run title @s title furia_bar3",
            "execute as @s[scores={classe_humana=1,combo=4..5,furia=20..29}] run title @s title furia_bar2",
            "execute as @s[scores={classe_humana=1,combo=4..5,furia=10..19}] run title @s title furia_bar1",
            "execute as @s[scores={classe_humana=1,combo=4..5,furia=0..9}] run title @s title furia_bar0",
            "camerashake add @s[scores={combos_animacoes=1,combo=4,furia=1..}] 0.5 0.9 positional",
            "execute as @s[scores={combos_animacoes=1,combo=4..5,furia=1..}] at @s run hud @s hide status_effects",
            "execute as @s[scores={combos_animacoes=1,combo=4..5,furia=1..}] at @s run camera @s set well:camera_rpg",
            "camerashake add @s[scores={furia=1..}] 0.2 0.3 positional",
            "execute as @s[scores={genero=2,combos_animacoes=1,combo=1..3,furia=1..}] at @s run playsound player.female.attack @a ~ ~ ~ 1",
            "execute as @s[scores={genero=2,combo=4,furia=1..}] at @s run playsound player.female.attack.especial @a ~ ~ ~ 1",
            "execute as @s[scores={genero=1,combos_animacoes=1,combo=1..3,furia=1..}] at @s run playsound player.male.attack @a ~ ~ ~ 1",
            "execute as @s[scores={genero=1,combo=4,furia=1..}] at @s run playsound player.male.attack.especial @a ~ ~ ~ 1",
            "execute as @s[scores={combos_animacoes=1,combo=1..,furia=1..}] at @s run playsound cajado.golpe @a ~ ~ ~ 1",
            "execute as @s[scores={combos_animacoes=1,combo=4..5,furia=1..}] at @s run playsound shuriken.ninja @a ~ ~ ~ 1",
            "playsound random.totem @s[scores={combos_animacoes=1,combo=4,furia=1..}] ~ ~ ~ 0.1 2"
        ];
        cmds.forEach(c => { try { player.runCommand(c); } catch {} });

        const combo = getScore(player, "combo");

        if (combo === 1 || combo === 2) {
            ativarDanoArea(player, "add_dano2");
        } else if (combo === 3) {
            ativarDanoArea(player, "add_dano2");
        } else if (combo === 4) {
            // COMBO 4 ORIGINAL: 4 PROJÉTEIS DE FURACÃO
            const frente = player.getViewDirection();
            const tras = { x: -frente.x, y: frente.y, z: -frente.z };
            const esquerda = { x: -frente.z, y: frente.y, z: frente.x };
            const direita = { x: frente.z, y: frente.y, z: -frente.x };
            const direcoes = [frente, tras, esquerda, direita];

            direcoes.forEach(dir => {
                try {
                    const furacao = player.dimension.spawnEntity("well:projectil_furacao_entidade", player.getHeadLocation());
                    if (!furacao) return;
                    const projectile = furacao.getComponent("minecraft:projectile");
                    if (projectile) {
                        projectile.owner = player;
                        projectile.shoot(dir);
                    }
                } catch {}
            });

            // Remove knockback logo após o combo 4
            try { player.runCommand("event entity @s remove_knockback"); } catch {}

            combo4Cooldown.set(player.id, system.currentTick + COMBO4_COOLDOWN_TICKS);
            limparCamera(player, 4); // passa 4 pra não remover knockback cedo (mas já removemos acima)
        }

        // Reset rápido (1.5s)
        const reset = system.runTimeout(() => {
            limparCamera(player);
            try { player.runCommand("event entity @s remove_danos"); } catch {}
        }, 30);

        comboTimeouts.set(player.id, () => system.clearRun(reset));
    }

    world.afterEvents.entityHitEntity.subscribe(ev => {
        const player = ev.damagingEntity;
        if (!player || player.typeId !== "minecraft:player") return;
        if (!ev.hitEntity) return;
        if (!machadoVentos(player)) return;
        processarHit(player);
    });

    world.afterEvents.entityHitBlock.subscribe(ev => {
        const player = ev.damagingEntity;
        if (!player || player.typeId !== "minecraft:player") return;
        if (!machadoVentos(player)) return;
        processarHit(player);
    });

    world.afterEvents.playerLeave.subscribe(e => {
        lastValidHit.delete(e.playerId);
        combo4Cooldown.delete(e.playerId);
        if (comboTimeouts.has(e.playerId)) {
            comboTimeouts.get(e.playerId)();
            comboTimeouts.delete(e.playerId);
        }
        if (danoRemoveTimeouts.has(e.playerId)) {
            danoRemoveTimeouts.get(e.playerId)();
            danoRemoveTimeouts.delete(e.playerId);
        }
    });
}