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

const arm_id = "nb:berserk_armor";
const mod_id = "nb:berserk_mode";
const prop_bsk = "nb:berserk_armor";
const prop_femto = "nb:femto";

const tempo_recuperacao = 7400; 
const duracao_maxima = 3200;    
const custo_por_uso = 300;      
const limite_minimo = 200;      

system.runInterval(() => {
    for (const player of world.getAllPlayers()) {
        if (!player.isValid()) continue;

        const inv = player.getComponent("inventory").container;
        const equ = player.getComponent("equippable");
        
        const isApostle = player.hasTag("apostle") || player.hasTag("femto");
        const isBerserk = player.hasTag("Berserk");

        if (!isBerserk) {
            if (!player.hasTag("descansando_bsk")) {
                player.addTag("descansando_bsk");
                player.setDynamicProperty("last_bsk_tick", system.currentTick);
            }

            const lastTick = player.getDynamicProperty("last_bsk_tick") ?? system.currentTick;
            if (system.currentTick - lastTick >= tempo_recuperacao) {
                let usos = 0;
                try {
                    const obj = world.scoreboard.getObjective("berserk_usada");
                    usos = obj ? obj.getScore(player) : 0;
                    
                    if (usos > 0) {
                        obj.addScore(player, -1);
                        player.sendMessage("§aYour body has recovered slightly from the armor's strain.");
                    }
                } catch(e) {}
                player.setDynamicProperty("last_bsk_tick", system.currentTick);
            }
        } else {
            if (player.hasTag("descansando_bsk")) player.removeTag("descansando_bsk");
        }

        if (isApostle && player.getProperty(prop_bsk) === 1) {
            player.setProperty(prop_bsk, 0);
            player.sendMessage("§4Apostles cannot succumb to the Beast of Darkness.");
        }

        if (isBerserk && player.getProperty(prop_femto) === 1) {
            player.setProperty(prop_femto, 0);
            player.sendMessage("§4The Beast within rejects the God Hand");
        }

        const isFemtoProp = player.getProperty(prop_femto) === 1;
        if (isFemtoProp && !isBerserk) { 
            if (!player.hasTag("femto")) {
                player.addTag("femto");
                adicionarstatus(player, "stat_end", 4);
                adicionarstatus(player, "stat_str", 4);
                adicionarstatus(player, "stat_vit", 10);
            }
            
            if (!hasItem(player, "nb:femto_skill1")) {
                const s1 = new ItemStack("nb:femto_skill1", 1);
                s1.lockMode = ItemLockMode.inventory;
                s1.keepOnDeath = true;
                inv.addItem(s1);
            }
            if (!hasItem(player, "nb:femto_skill4")) {
                const s4 = new ItemStack("nb:femto_skill4", 1);
                s4.lockMode = ItemLockMode.inventory; 
                s4.keepOnDeath = true;
                inv.addItem(s4);
            }
        } else if (!isFemtoProp && player.hasTag("femto")) {
            adicionarstatus(player, "stat_end", -4);
            adicionarstatus(player, "stat_str", -4);
            adicionarstatus(player, "stat_vit", -10);
            player.removeTag("femto");
        }

        const head = equ.getEquipment(EquipmentSlot.Head);
        const has_arm = head?.typeId === arm_id;
        let has_mod = false;
        let mod_slot = -1;

        for (let i = 0; i < inv.size; i++) {
            const item = inv.getItem(i);
            if (item?.typeId === mod_id) {
                if (isApostle) {
                    inv.setItem(i, undefined); 
                } else {
                    has_mod = true;
                    mod_slot = i;
                }
                break;
            }
        }

        if (!isApostle) {
            if ((has_arm || isBerserk) && !has_mod) {
                const it = new ItemStack(mod_id, 1);
                it.lockMode = ItemLockMode.inventory;
                it.keepOnDeath = true;
                inv.addItem(it);
            } else if (!(has_arm || isBerserk) && has_mod) {
                inv.setItem(mod_slot, undefined);
            }

            if (player.getProperty(prop_bsk) === 1 && !player.hasTag("stats_applied")) {
                bsk_on(player);
            }
        }

        if (isBerserk) {
            if (system.currentTick % 5 === 0) {
                player.runCommandAsync("particle minecraft:basic_red_dust_particle ~ ~1 ~0.2");
            }

            if (system.currentTick % 20 === 0) {
                let usos = 0;
                try {
                    const obj = world.scoreboard.getObjective("berserk_usada");
                    usos = obj ? obj.getScore(player) : 0;
                } catch(e) {}

                if (usos > 5) {
                    const dano = Math.floor(usos / 3);
                    player.applyDamage(dano, { cause: "magic" });
                    if (system.currentTick % 40 === 0) {
                        player.onScreenDisplay.setActionBar("§4The Armor is crushing your bones...");
                    }
                }
            }
        }
    }
}, 20);

world.afterEvents.entityDie.subscribe((event) => {
    const vitima = event.deadEntity;
    if (vitima?.typeId === "minecraft:player" && vitima.hasTag("Berserk")) {
        desativar_berserk(vitima);
    }
});

function hasItem(player, typeId) {
    const inv = player.getComponent("inventory").container;
    for (let i = 0; i < inv.size; i++) {
        if (inv.getItem(i)?.typeId === typeId) return true;
    }
    return false;
}

function adicionarstatus(player, obj, val) {
    try {
        const objective = world.scoreboard.getObjective(obj) || world.scoreboard.addObjective(obj, obj);
        if (objective) objective.addScore(player, val);
    } catch (e) {}
}

function bsk_on(player) {
    const equ = player.getComponent("equippable");
    equ.setEquipment(EquipmentSlot.Head, undefined);

    player.runCommandAsync("clear @s nb:berserk_mode");
    player.runCommandAsync("effect @s speed 99999 5 true");
    player.runCommandAsync("effect @s regeneration 9999 1 true");
    player.runCommandAsync("music play music.game.dragon_slayer 0.2 0.5 loop");
    
    player.addTag("Berserk");
    player.addTag("stats_applied");
    adicionarstatus(player, "berserk_usada", 1);
    
    let total_usos = 0;
    try {
        const obj = world.scoreboard.getObjective("berserk_usada");
        total_usos = obj ? obj.getScore(player) : 1;
    } catch(e) {}

    let tempo_final = duracao_maxima - (total_usos * custo_por_uso);
    if (tempo_final < limite_minimo) tempo_final = limite_minimo;

    player.sendMessage(`§8The Beast of Darkness awakens...`);
    player.sendMessage(`§4Frail Body: §7${Math.floor(tempo_final / 20)}s remaining §8(Total uses: ${total_usos})`);
    
    adicionarstatus(player, "stat_dex", 4);
    adicionarstatus(player, "stat_vit", 3);
    adicionarstatus(player, "stat_end", 3);
    adicionarstatus(player, "stat_str", 3);

    system.runTimeout(() => {
        if (player.isValid() && player.hasTag("Berserk")) {
            desativar_berserk(player);
        }
    }, tempo_final);
}

function desativar_berserk(player) {
    if (!player.isValid()) return;

    player.runCommandAsync("effect @s clear");
    player.runCommandAsync("music stop 2.0");

    let uso_count = 0;
    try {
        const obj = world.scoreboard.getObjective("berserk_usada");
        uso_count = obj ? obj.getScore(player) : 0;
    } catch (e) {}

    const tempo_ruim = 15 + Math.floor(uso_count * 3);

    player.runCommandAsync(`effect @s mining_fatigue ${tempo_ruim} 3 true`);
    player.runCommandAsync(`effect @s slowness ${tempo_ruim} 1 true`);
    player.runCommandAsync(`effect @s weakness ${tempo_ruim} 5 true`);
    
    if (uso_count >= 4) {
        player.runCommandAsync(`effect @s blindness ${Math.min(tempo_ruim, 40)} 0 true`);
        player.runCommandAsync(`effect @s nausea ${Math.min(tempo_ruim, 20)} 0 true`);
    }

    player.runCommandAsync("event entity @s nb:berserk_armor_no");
    player.runCommandAsync("event entity @s nb:ds_spin_no");

    adicionarstatus(player, "stat_dex", -4);
    adicionarstatus(player, "stat_vit", -3);
    adicionarstatus(player, "stat_end", -3);
    adicionarstatus(player, "stat_str", -3);

    const eq_back = player.getComponent("equippable");
    const armor = new ItemStack(arm_id, 1);
    eq_back.setEquipment(EquipmentSlot.Head, armor);

    player.removeTag("Berserk");
    player.removeTag("stats_applied");
    player.setProperty(prop_bsk, 0);
    
    player.setDynamicProperty("last_bsk_tick", system.currentTick);
    
    system.runTimeout(() => {    
        if (player.isValid()) {
            player.runCommandAsync("title @s actionbar §4§oBerserk Mode Recharged!");    
            player.runCommandAsync("tag @s remove berserkm_cooldown");
        }
    }, 2500);
}