// martelao_combos.js – MARTELÃO (com eventos de dano via behavior pack + knockback consistente como na espada)
import { world, system, EquipmentSlot } from "@minecraft/server";

const lastValidHit = new Map();
const combo4Cooldown = new Map();
const comboTimeouts = new Map();
const danoRemoveTimeouts = new Map(); // Para cancelar remoção automática do dano no combo 4

const MIN_TICKS_BETWEEN_HITS = 10; // 0.5s entre hits
const COMBO4_COOLDOWN_TICKS = 100; // 5s de cooldown após combo 4

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

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

    function limparCameraEInput(player, combo = 0) {
        try { player.runCommand("camera @s clear"); } catch {}
        try { player.runCommand("scoreboard players set @s combo 0"); } catch {}
        try { player.runCommand("inputpermission set @s lateral_movement enabled"); } catch {}
        try { player.runCommand("inputpermission set @s movement enabled"); } 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);
        }
    }

    // Ativa dano em área via evento e agenda remoção após 1s (não usado no combo 4)
    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));
    }

    // PROCESSAR HIT
    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);
        }

        // Adiciona knockback a cada hit válido
        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");

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

        // EFEITOS GERAIS
        const cmdsGerais = [
            "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",
            "playanimation @s[scores={combos_animacoes=1,combo=1,furia=1..}] animation.machadao.humano.combo1",
            "playanimation @s[scores={combos_animacoes=1,combo=2,furia=1..}] animation.machadao.humano.combo2",
            "playanimation @s[scores={combos_animacoes=1,combo=3,furia=1..}] animation.machadao.humano.combo3",
            "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",
            "playsound random.totem @s[scores={combos_animacoes=1,combo=4,furia=1..}] ~ ~ ~ 0.1 2",
            // Bloqueia movimento no combo 4
            "inputpermission set @s[scores={combos_animacoes=1,combo=4..5,furia=1..}] lateral_movement disabled",
            "inputpermission set @s[scores={combos_animacoes=1,combo=4..5,furia=1..}] movement disabled"
        ];
        cmdsGerais.forEach(c => { try { player.runCommand(c); } catch {} });

        // DANOS VIA EVENTOS
        if (combo === 1 || combo === 2) {
            ativarDanoArea(player, "add_dano4");
        } else if (combo === 3) {
            ativarDanoArea(player, "add_dano4");
        } else if (combo === 4) {
            // EFEITOS INICIAIS DO COMBO 4
            try { player.runCommand("playanimation @s animation.machadao.humano.combo4"); } catch {}
            try { player.runCommand("camera @s set minecraft:third_person"); } catch {}
            try { player.runCommand("camerashake add @s 0.15 1.5 positional"); } catch {}
            try { player.runCommand("effect @s slowness 2 2 true"); } catch {}

            // EFEITOS COM DELAY DE 20 TICKS
            system.runTimeout(() => {
                const cmdsDelay = [
                    "playsound mob.boss3.attack_chao @a[r=10] ~ ~ ~",
                    "particle well:terra_escavacao ~ ~ ~",
                    "particle well:terra_escavacao ~0.2 ~ ~",
                    "particle well:terra_escavacao ~ ~ ~0.2",
                    "particle well:terra_escavacao ~ ~ ~",
                    "particle well:terra_escavacao ~0.1 ~ ~0.1",
                    "particle well:terra_escavacao ^ ^0.5 ^0.3",
                    "particle well:rachadura_solo2 ~ ~ ~",
                    "camerashake add @s 0.1 1.5 rotational",
                    "hud @s hide status_effects"
                ];
                cmdsDelay.forEach(c => { try { player.runCommand(c); } catch {} });
            }, 20);

            const slotInicial = player.selectedSlotIndex;
            let ticks = 0;

            // Ativa dano contínuo e cancela remoção automática
            try { player.runCommand("event entity @s remove_danos"); } catch {}
            try { player.runCommand("event entity @s add_dano4"); } catch {}

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

            const loop = system.runInterval(() => {
                if (!player || !player.isValid || player.selectedSlotIndex !== slotInicial) {
                    try { player.runCommand("event entity @s remove_danos"); } catch {}
                    try { player.runCommand("event entity @s remove_knockback"); } catch {}
                    limparCameraEInput(player);
                    system.clearRun(loop);
                    return;
                }

                if (++ticks >= 40) {
                    try { player.runCommand("event entity @s remove_danos"); } catch {}
                    try { player.runCommand("event entity @s remove_knockback"); } catch {}
                    limparCameraEInput(player, 4); // Passa 4 pra não remover knockback cedo
                    combo4Cooldown.set(player.id, system.currentTick + COMBO4_COOLDOWN_TICKS);
                    system.clearRun(loop);
                }
            }, 1);
        }

        // Reset por inatividade
        const reset = system.runTimeout(() => {
            limparCameraEInput(player);
            try { player.runCommand("event entity @s remove_danos"); } catch {}
        }, 60);

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

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

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

    // Limpeza ao sair
    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);
        }
    });
}