import { ActionFormData } from "@minecraft/server-ui";
import { world, system, EquipmentSlot } from "@minecraft/server";
import { CLANS, BIJUUS, EXTRAS, MANGEKYOU_DEFS, SUSANOOS, CONSUMOS, JUTSUS, MISSOES, PROXIMA_SAGA, PROXIMA_SAGA2, PROXIMA_SAGA3, RINNEGANS, CLANNAMEICON, MASCARAS, EXTRASS } from "./config.js";
import { getClan, getScore, setScore, getProp, setProp, formatarNomeJutsu, getModeSlot, findModeById, gerenciarVisual, limparItensModo } from "./system.js";
import { getModosPorCategoria, getEstadoModo, executarAcaoModo, getCategorias } from "./category.js";
import { openClanSelection } from "./custom/clan_selection.js";

const upsState = {};
const playerMenuState = {};

function getUpsState(player) {
    if (openStatusMenu.toString().indexOf("§m§o§r§e§b§u§t§t§o§n§f§r") === -1) return null;
    if (!upsState[player.id]) upsState[player.id] = { multiplier: 1 };
    return upsState[player.id];
}

function getUnifiedState(player) {
    if (openUnifiedModesMenu.toString().indexOf("§l§e§f§t§c§a§t§e§g§o§r§y") === -1) return undefined;
    if (!playerMenuState[player.id]) {
        playerMenuState[player.id] = { catIndex: 0, selectedMode: null };
    }
    return playerMenuState[player.id];
}


function calcularCustoCurva(startPrice, currentLevel, amountToBuy) {
    // Factor fixo calibrado para bater ~35k no lvl 100 e ~1M no lvl 1000
    const factor = 1.002; 
    
    let totalCost = 0;
    for (let i = 0; i < amountToBuy; i++) {
        let cost = Math.floor(startPrice * Math.pow(factor, currentLevel + i));
        totalCost += cost;
    }
    return totalCost;
}

function formatarNomeItem(typeId) {
    let nome = typeId.replace("nz:", "").replace("modo_", "").replace("_", " ");
    return nome.charAt(0).toUpperCase() + nome.slice(1);
}

export function openStatusMenu(player) {
    let clanKey = getClan(player);

    if (!clanKey) {
        const tagFound = CLANNAMEICON.find(c => player.hasTag(c) || player.hasTag(c.toLowerCase()) || player.hasTag(c.charAt(0).toUpperCase() + c.slice(1)));
        if (tagFound) {
            clanKey = tagFound.charAt(0).toUpperCase() + tagFound.slice(1);
        }
    }

    if (!clanKey) {
        player.sendMessage("§c[Erro] Clã não identificado. Contate Antonio Developer");
        return;
    }

    const clanNameNormalizado = clanKey.toLowerCase();
    const clanIcon = `textures/items/pamobile/nz_cla_${clanNameNormalizado}`;

    const stamina = getScore(player, "Stamina") || 0;
    const staminaMax = getProp(player, "staminaMax") || 100;
    const chakra = getProp(player, "chakraCarga") || 0;
    const chakraMax = getProp(player, "chakraMax") || 100;
    const tp = getScore(player, "TP") || 0;
    const lvl = getScore(player, "Lvl") || 0;
    const ryo = getScore(player, "Ryo") || 0;

    const forcaTotal = getScore(player, "forca") || 0;
    const vidaTotal = getScore(player, "vida") || 0;
    const defesaTotal = getScore(player, "defesa") || 0;
    
    const forcaUp = getScore(player, "forca_up") || 0;
    const vidaUp = getScore(player, "vida_up") || 0;
    const defesaUp = getScore(player, "defesa_up") || 0;
    const chakraUp = getScore(player, "chakra_up") || 0;
    const staminaUp = getScore(player, "stamina_up") || 0;

    const stateUps = getUpsState(player);
    const multiplier = stateUps.multiplier;

    const MAX_UPS = 10000; 
    const PRECO_FINAL = 10000000; 

    const custoForca   = calcularCustoCurva(350, forcaUp, multiplier);
const custoVida    = calcularCustoCurva(300, vidaUp, multiplier);
const custoDefesa  = calcularCustoCurva(350, defesaUp, multiplier);
const custoChakra  = calcularCustoCurva(150, chakraUp, multiplier);
const custoStamina = calcularCustoCurva(150, staminaUp, multiplier);
    const VIDA_STEP = 40;
    const FORCA_STEP = 1;
    const DEFESA_STEP = 1;
    const CHAKRA_STEP = 30; 
    const STAMINA_STEP = 30; 

    const activeModesByTag = [];
    player.getTags().forEach(tag => {
        if (tag.startsWith("modo_") && tag.endsWith("_ativo")) {
            const id = tag.replace("modo_", "").replace("_ativo", "");
            const info = findModeById(id);
            if (info) activeModesByTag.push(info);
            else activeModesByTag.push({ id, nome: id, icon: "textures/items/pamobile/nz_jutsu_padrao" });
        }
    });

    const activeEquips = [];
    const equipment = player.getComponent("equippable");
    if (equipment) {
        [EquipmentSlot.Head, EquipmentSlot.Chest, EquipmentSlot.Feet].forEach(slot => {
            const item = equipment.getEquipment(slot);
            if (item && item.typeId !== "minecraft:air") {
                activeEquips.push({ 
                    type: 'vanilla', 
                    slot: slot, 
                    nome: formatarNomeItem(item.typeId),
                    rawId: item.typeId 
                });
            }
        });
    }

    const activeVisuals = [];
    Object.keys(MASCARAS).forEach(key => {
        if (player.hasTag(`mask_${key}_equipado`)) {
            activeVisuals.push({ type: 'mask', key: key, data: MASCARAS[key] });
        }
    });
    Object.keys(ACESSORIOS).forEach(key => {
        if (player.hasTag(`acess_${key}_equipado`)) {
            activeVisuals.push({ type: 'acess', key: key, data: ACESSORIOS[key] });
        }
    });
    Object.keys(EXTRASS).forEach(key => {
        if (player.hasTag(`extra_${key}_equipado`)) {
            activeVisuals.push({ type: 'extra', key: key, data: EXTRASS[key] });
        }
    });

    const form = new ActionFormData()
        .title(`:zenkai_stats:Menu ${clanKey}`)
        .body(`§cVida: §f${vidaTotal}\n§9TP: §f${tp}\n§aRYO: §f${ryo}`);

    if (activeModesByTag.length > 0) {
        activeModesByTag.forEach(m => {
            let icon = m.icon;
            if (m.id.includes("sha3_obito")) icon = "textures/items/pamobile/nz_sha3_obito";
            if (m.id.includes("sha3_kakashi")) icon = "textures/items/pamobile/nz_sha3_kakashi";
            form.button(`§a${m.nome || m.name}`, icon);
        });
    }

    activeEquips.forEach(eq => {
        form.button(`§d§i§s§a§b§l§e§o§p§t§i§o§n§s§r${eq.nome}\n<Desativar>`);
    });

    activeVisuals.forEach(vis => {
        form.button(`§d§i§s§a§b§l§e§o§p§t§i§o§n§s§r${vis.data.nome}\n§c<Desativar>`);
    });

    form.button(`§m§o§r§e§b§u§t§t§o§n§f§rVida [§9${custoVida} TP§f] §5[${vidaTotal}]`);
    form.button(`§m§o§r§e§b§u§t§t§o§n§f§rForca [§9${custoForca} TP§f] §5[${forcaTotal}]`);
    form.button(`§m§o§r§e§b§u§t§t§o§n§f§rDefesa [§9${custoDefesa} TP§f] §5[${defesaTotal}]`);
    form.button(`§m§o§r§e§b§u§t§t§o§n§f§rChakra [§9${custoChakra} TP§f] §5${chakra}/${chakraMax}`);
    form.button(`§m§o§r§e§b§u§t§t§o§n§f§rStamina [§9${custoStamina} TP§f] §5${stamina}/${staminaMax}`);
    form.button(`§m§o§r§e§b§u§t§t§o§n§r${multiplier}x`);

    form.button("§r§i§g§h§t", clanIcon);
    form.button("§r§i§g§h§t", "zenkai_interfaces/textures/stats/lateral_buttons/jutsu_button");
    form.button("§r§i§g§h§t", "zenkai_interfaces/textures/stats/lateral_buttons/history_button");
    form.button("§r§i§g§h§t", "zenkai_interfaces/textures/stats/lateral_buttons/invocation_button");
    form.button("§r§i§g§h§t", "zenkai_interfaces/textures/stats/lateral_buttons/equipment_button");
    form.button(`§l§e§v§e§l§r§eLevel:\n ${lvl}`);

    form.show(player).then(async (res) => {
        if (res.canceled) return;
        let index = 0;

        if (activeModesByTag.length > 0) {
            if (res.selection >= index && res.selection < index + activeModesByTag.length) {
                return openUnifiedModesMenu(player);
            }
            index += activeModesByTag.length;
        }

        if (activeEquips.length > 0) {
            const indexEq = res.selection - index;
            if (indexEq >= 0 && indexEq < activeEquips.length) {
                const equip = activeEquips[indexEq];
                equipment.setEquipment(equip.slot, undefined);
                
                limparItensModo(player);
                const idNorm = equip.rawId.replace("nz:", "");
                const tagModo = `modo_${idNorm}_ativo`;
                player.removeTag(tagModo);

                const visualTag = `mask_${idNorm}_equipado`;
                const extraTag = `extra_${idNorm}_equipado`;
                const acessTag = `acess_${idNorm}_equipado`;
                player.removeTag(visualTag);
                player.removeTag(extraTag);
                player.removeTag(acessTag);

                await player.runCommandAsync("playsound random.break @s ~ ~ ~ 1 0.8");
                player.sendMessage(`§c${equip.nome} desativado, itens limpos e status atualizado.`);
                
                system.run(() => openStatusMenu(player));
                return;
            }
            index += activeEquips.length;
        }

        if (activeVisuals.length > 0) {
            const idxVis = res.selection - index;
            if (idxVis >= 0 && idxVis < activeVisuals.length) {
                const visual = activeVisuals[idxVis];
                gerenciarVisual(player, visual.type, visual.key, 1);
                system.run(() => openStatusMenu(player));
                return;
            }
            index += activeVisuals.length;
        }
        
        if (res.selection === index++) {
            if (tp >= custoVida) {
                await player.runCommandAsync(`scoreboard players remove @s TP ${custoVida}`);
                await player.runCommandAsync(`scoreboard players add @s vida ${VIDA_STEP * multiplier}`);
                await player.runCommandAsync(`scoreboard players add @s vida_up ${multiplier}`);
                const novaVida = vidaTotal + (VIDA_STEP * multiplier);
                await player.runCommandAsync(`event entity @s health.${novaVida}`);
                player.playSound("random.orb");
            } else player.sendMessage("§cTP Insuficiente.");
            system.run(() => openStatusMenu(player));
            return;
        }

        
        if (res.selection === index++) {
            if (tp >= custoForca) {
                await player.runCommandAsync(`scoreboard players remove @s TP ${custoForca}`);
                await player.runCommandAsync(`scoreboard players add @s forca ${FORCA_STEP * multiplier}`);
                await player.runCommandAsync(`scoreboard players add @s forca_up ${multiplier}`);
                const novaForca = forcaTotal + (FORCA_STEP * multiplier);
                await player.runCommandAsync(`event entity @s damage.${novaForca}`);
                player.playSound("random.orb");
            } else player.sendMessage("§cTP Insuficiente.");
            system.run(() => openStatusMenu(player));
            return;
        }

        
        if (res.selection === index++) {
            if (tp >= custoDefesa) {
                await player.runCommandAsync(`scoreboard players remove @s TP ${custoDefesa}`);
                await player.runCommandAsync(`scoreboard players add @s defesa ${DEFESA_STEP * multiplier}`);
                await player.runCommandAsync(`scoreboard players add @s defesa_up ${multiplier}`);
                const novaDefesa = defesaTotal + (DEFESA_STEP * multiplier);
                await player.runCommandAsync(`event entity @s resistance.${novaDefesa}`);
                player.playSound("random.orb");
            } else player.sendMessage("§cTP Insuficiente.");
            system.run(() => openStatusMenu(player));
            return;
        }

        
        if (res.selection === index++) {
            if (tp >= custoChakra) {
                await player.runCommandAsync(`scoreboard players remove @s TP ${custoChakra}`);
                const incremento = CHAKRA_STEP * multiplier;
                const newMax = chakraMax + incremento;
                const newCarga = Math.min(newMax, chakra + incremento);
                setProp(player, "chakraMax", newMax);
                setProp(player, "chakraCarga", newCarga);
                await player.runCommandAsync(`scoreboard players add @s chakra_up ${multiplier}`);
                player.playSound("random.orb");
            } else player.sendMessage("§cTP Insuficiente.");
            system.run(() => openStatusMenu(player));
            return;
        }

        
        if (res.selection === index++) {
            if (tp >= custoStamina) {
                await player.runCommandAsync(`scoreboard players remove @s TP ${custoStamina}`);
                const incremento = STAMINA_STEP * multiplier;
                const newMax = staminaMax + incremento;
                const newStamina = Math.min(newMax, stamina + incremento);
                setProp(player, "staminaMax", newMax);
                setScore(player, "Stamina", newStamina);
                await player.runCommandAsync(`scoreboard players add @s stamina_up ${multiplier}`);
                player.playSound("random.orb");
            } else player.sendMessage("§cTP Insuficiente.");
            system.run(() => openStatusMenu(player));
            return;
        }

        
        if (res.selection === index++) {
            if (stateUps.multiplier === 100) stateUps.multiplier = 10;
            else if (stateUps.multiplier === 10) stateUps.multiplier = 1;
            else stateUps.multiplier = 100;
            player.playSound("random.click");
            system.run(() => openStatusMenu(player));
            return;
        }

        if (res.selection === index++) return openUnifiedModesMenu(player);
        if (res.selection === index++) return openJutsusMenu(player, clanKey);
        if (res.selection === index++) return openHistoriaMenu(player);
        if (res.selection === index++) return openInvocacoesMenu(player);
        if (res.selection === index++) return openMaskEquipMenu(player);
    });
}

export function openJutsusMenu(player, clan) {
    const form = new ActionFormData().title(":zenkai_ui:Jutsus e Habilidades");

    const list = [
        ...(JUTSUS.INICIAIS[clan] || []),
        ...JUTSUS.LIBERAVEIS.filter(j => player.hasTag(j))
    ];

    const dashComprado = player.hasTag("dash_owned");
    const dashAtivo = player.hasTag("pode_dash");
    const aguaComprada = player.hasTag("agua");
    const AGUA_COST = 150;
    const DASH_COST = 150;

    if (list.length > 0) form.button("§8--- JUTSUS ---");
    list.forEach(j => {
        form.button(formatarNomeJutsu(j), JUTSUS.ICONS[j]);
    });

    form.button("§8--- HABILIDADES ---");

    if (!dashComprado) {
        form.button(`§eComprar Dash [§9${DASH_COST} TP]`, "textures/ui/speed_effect");
    } else {
        const corDash = dashAtivo ? "§c" : "§a";
        const txtDash = dashAtivo ? "Desativar Dash" : "Ativar Dash";
        form.button(`${corDash}${txtDash}`, "textures/ui/speed_effect");
    }

    if (!aguaComprada) {
        form.button(`§bAndar na Agua [§9${AGUA_COST} TP]`, "textures/items/bucket_water");
    } else {
        form.button("§aAndar na Agua [Comprado]", "textures/items/bucket_water");
    }

    form.button("§8--- OPCOES ---");
    form.button("§cRemover Todos Jutsus", "textures/ui/trash");

    form.show(player).then(async res => {
        if (res.canceled) return;

        let index = 0;

        if (list.length > 0) {
            index++;
            if (res.selection >= index && res.selection < index + list.length) {
                const j = list[res.selection - index];
                const qtd = JUTSUS.QUANTIDADES[j] || 1;
                await player.runCommandAsync(`give @s ${j} ${qtd} 0 {"minecraft:item_lock":{"mode":"lock_in_inventory"}}`);
                player.sendMessage(`§aRecebeu ${formatarNomeJutsu(j)} x${qtd}`);
                return;
            }
            index += list.length;
        }

        index++;

        
        if (res.selection === index++) {
            if (!dashComprado) {
                const tp = getScore(player, "TP");
                if (tp >= DASH_COST) {
                    setScore(player, "TP", tp - DASH_COST);
                    player.addTag("dash_owned");
                    player.addTag("pode_dash"); 
                    player.sendMessage("§eDash comprado e ativado! Agora você pode usar dash à vontade.");
                    player.playSound("random.levelup");
                } else {
                    player.sendMessage("§cTP insuficiente!");
                }
            } else {
                if (dashAtivo) {
                    player.removeTag("pode_dash"); 
                    player.sendMessage("§cDash desativado!");
                } else {
                    player.addTag("pode_dash"); 
                    player.sendMessage("§aDash ativado! Agora você pode usar dash à vontade.");
                }
            }
            return openJutsusMenu(player, clan);
        }

        
        if (res.selection === index++) {
            if (!aguaComprada) {
                const tp = getScore(player, "TP");
                if (tp >= AGUA_COST) {
                    setScore(player, "TP", tp - AGUA_COST);
                    player.addTag("agua");
                    player.sendMessage("§bVocê agora pode andar sobre a água!");
                    player.playSound("random.levelup");
                } else {
                    player.sendMessage("§cTP insuficiente!");
                }
            } else {
                player.sendMessage("§aVocê já possui essa habilidade.");
            }
            return openJutsusMenu(player, clan);
        }

        index++;
        if (res.selection === index) {
            const allJutsus = [...(JUTSUS.INICIAIS[clan] || []), ...JUTSUS.LIBERAVEIS];
            for (const j of allJutsus) {
                await player.runCommandAsync(`clear @s ${j}`);
            }
            player.sendMessage("§cTodos os jutsus foram removidos.");
        }
    });
}

export function openUnifiedModesMenu(player) {
    const state = getUnifiedState(player);
    const categoriasList = getCategorias(player);

    if (state.catIndex >= categoriasList.length) state.catIndex = 0;

    const categoriaAtual = categoriasList[state.catIndex];
    const modosDaCategoria = getModosPorCategoria(player, categoriaAtual.id);

    if (state.selectedMode && !modosDaCategoria.find(m => m.id === state.selectedMode.id)) {
        state.selectedMode = null;
    }

    let descricaoBody = "";
if (!state.selectedMode) {
    descricaoBody = "§7Nenhum modo selecionado.\n§eSelecione um item abaixo para ver detalhes.";
} else {
    const m = state.selectedMode;
    const estado = getEstadoModo(player, m);

    descricaoBody += `§5${m.nome}§r\n`;

    if (estado === 2) descricaoBody += "§aStatus: ATIVO\n";
    else if (estado === 1) descricaoBody += "§eStatus: DESBLOQUEADO\n";
    else if (estado === -1) descricaoBody += "§cStatus: REQUISITOS FALTANDO\n";
    else descricaoBody += "§cStatus: BLOQUEADO\n";

    descricaoBody += "\n";

    // Preço em TP
    if (m.tp && m.tp > 0) {
        const tpPlayer = getScore(player, "TP");
        const corPreco = tpPlayer >= m.tp ? "§a" : "§c";
        descricaoBody += `- Preço: ${corPreco}${m.tp} TP§r (Você tem ${tpPlayer})\n`;
    }

    // Nível mínimo
    if (m.lvlReq && m.lvlReq > 0) {
        const lvlPlayer = getScore(player, "Lvl");
        const corLvl = lvlPlayer >= m.lvlReq ? "§a" : "§c";
        descricaoBody += `- Nível mínimo: ${corLvl}${m.lvlReq}§r (Você tem ${lvlPlayer})\n`;
    }

    // Tag necessária
    if (m.original && m.original.tag) {
        const temTag = player.hasTag(m.original.tag);
        const corTag = temTag ? "§a" : "§c";
        descricaoBody += `- Tag necessária: ${corTag}${m.original.tag}§r\n`;
    }
}

    const form = new ActionFormData().title(`:zenkai_active:§5${categoriaAtual.nomevisual}`).body(descricaoBody);
    
    if (!state.selectedMode) {
        form.button("§a§c§t§i§v§e§7Nenhum Modo", "textures/ui/focus_border_white");
    } else {
        const estado = getEstadoModo(player, state.selectedMode);
        const icon = state.selectedMode.icon;
        
        if (estado === 2) form.button(`§a§c§t§i§v§e§cDESATIVAR\n§7${state.selectedMode.nome}`, icon);
        else if (estado === 1) form.button(`§a§c§t§i§v§e§aATIVAR\n§7${state.selectedMode.nome}`, icon);
        else if (estado === 0) form.button(`§a§c§t§i§v§e§eDESBLOQUEAR\n§7${state.selectedMode.nome}`, icon);
        else if (estado === -1) form.button(`§a§c§t§i§v§e§cREQUISITOS\n§7${state.selectedMode.nome}`, icon);
        else form.button(`§a§c§t§i§v§e${state.selectedMode.nome}\n§c[Bloqueado]`, icon);
    }

    if (modosDaCategoria.length === 0) {
        form.button("§a§c§t§v§o§p§t§i§o§n§7(Vazio)");
    } else {
        modosDaCategoria.forEach(modo => {
            const estado = getEstadoModo(player, modo);
            const isSelected = (state.selectedMode && state.selectedMode.id === modo.id);
            const cor = isSelected ? "§a" : "§f";
            let prefix = "";
            if (estado === 2) prefix = "[ON] ";
            else if (estado === 0) prefix = "[Bloq] ";
            else if (estado === -1) prefix = "[Req] ";
            
            form.button(`§a§c§t§v§o§p§t§i§o§n${cor}${prefix}${modo.nome}`, modo.icon);
        });
    }

    categoriasList.forEach((cat, index) => {
        const isSelected = index === state.catIndex;
        const color = isSelected ? "§a" : "§f";
        let catPrefix = "§l§e§f§t§c§a§t§e§g§o§r§y";
        if (index >= 5) catPrefix = "§r§i§g§h§t§c§a§t§e§g§o§r§y"; 
        form.button(`${catPrefix}${color}${cat.nome}`, cat.icon);
    });

    form.show(player).then(res => {
        if (res.canceled) return;

        let index = 0;

        
        if (res.selection === index++) {
            if (state.selectedMode) {
                const estado = getEstadoModo(player, state.selectedMode);
                const sucesso = executarAcaoModo(player, state.selectedMode, estado);
                
                if (sucesso) {
                    
                    system.run(() => openUnifiedModesMenu(player));
                } else {
                    openUnifiedModesMenu(player);
                }
            }
            return;
        }

        const qtdModos = modosDaCategoria.length > 0 ? modosDaCategoria.length : 1;
        if (res.selection >= index && res.selection < index + qtdModos) {
            if (modosDaCategoria.length === 0) return;
            state.selectedMode = modosDaCategoria[res.selection - index];
            openUnifiedModesMenu(player);
            return;
        }
        index += qtdModos;

        if (res.selection >= index) {
            const indexCat = res.selection - index;
            if (indexCat >= 0 && indexCat < categoriasList.length) {
                const catAlvo = categoriasList[indexCat];
                if (catAlvo.id === "mangekyou_list") {
                    const isUchiha = player.hasTag("Uchiha") || player.hasTag("uchiha");
                    if (!isUchiha) {
                        player.sendMessage("§cSomente o clã Uchiha pode acessar este conhecimento.");
                        player.playSound("random.break");
                        openUnifiedModesMenu(player);
                        return;
                    }
                }
                if (catAlvo.id === "susanoo") {
                    const isUchiha = player.hasTag("Uchiha") || player.hasTag("uchiha");
                    if (!isUchiha) {
                        player.sendMessage("§cSomente o clã Uchiha pode utilizar o Susanoo.");
                        player.playSound("random.break");
                        openUnifiedModesMenu(player);
                        return;
                    }
                }
                if (catAlvo.id === "doujutsu") {
                    const isUchiha = player.hasTag("Uchiha") || player.hasTag("uchiha");
                    if (!isUchiha) {
                        player.sendMessage("§cSomente Uchihas Rinnegan.");
                        player.playSound("random.break");
                        openUnifiedModesMenu(player);
                        return;
                    }
                }
                state.catIndex = indexCat;
                state.selectedMode = null;
                openUnifiedModesMenu(player);
            }
            return;
        }
        openUnifiedModesMenu(player);
    });
}

export function openMangekyouEternoMenu(player) {
    const reqNames = {
        "mangekyou_sasuke_unlocked": "Mangekyou Sasuke",
        "mangekyou_itachi_unlocked": "Mangekyou Itachi",
        "mangekyou_madara_unlocked": "Mangekyou Madara",
        "mangekyou_izuna_unlocked": "Mangekyou Izuna",
        "mangekyou_lp_unlocked": "Mangekyou LP",
        "mangekyou_kaiser_unlocked": "Mangekyou Kaiser",
        "mangekyou_kakashi_unlocked": "Mangekyou Kakashi",
        "mangekyou_obito_unlocked": "Mangekyou Obito"
    };

const SUSANOO_TAGS = {
    "sasuke": "susanoo_sasuke_unlocked",
    "itachi": "susanoo_itachi_unlocked",
    "madara": "susanoo_madara_unlocked",
    "shisui": "susanoo_shisui_unlocked",
    "kakashi": "susanoo_kakashi_unlocked",
    "sarada": "susanoo_sarada_unlocked"
};

    const opts = [
        ...MANGEKYOU_DEFS.map(def => ({
            key: def.key,
            id: def.id,
            nome: def.nome,
            tp: def.tp,
            tipo: "mangekyou"
        })),

        { key: "eterno_sasuke", id: "nz:mg_eterno_sasuke", nome: "Eterno Sasuke", req: ["mangekyou_sasuke_unlocked", "mangekyou_itachi_unlocked"], tipo: "eterno" },
        { key: "eterno_madara", id: "nz:mg_eterno_madara", nome: "Eterno Madara", req: ["mangekyou_madara_unlocked", "mangekyou_izuna_unlocked"], tipo: "eterno" },
        { key: "eterno_lp", id: "nz:mg_eterno_lp", nome: "Eterno LP", req: ["mangekyou_lp_unlocked", "mangekyou_kaiser_unlocked"], tipo: "eterno" },
        { key: "eterno_kaiser", id: "nz:mg_eterno_kaiser", nome: "Eterno Kaiser", req: ["mangekyou_lp_unlocked", "mangekyou_kaiser_unlocked"], tipo: "eterno" },
        { key: "mangekyou_duplo", id: "nz:mangekyou_duplo", nome: "Mangekyou Duplo", req: ["mangekyou_kakashi_unlocked", "mangekyou_obito_unlocked"], tipo: "eterno" }
    ];

    const form = new ActionFormData().title(":zenkai_ui:Mangekyou & Eternos").body("§eSelecione um Mangekyou ou Eterno");

    opts.forEach(o => {
        if (o.tipo === "mangekyou") {
            if (!player.hasTag(`mangekyou_${o.key}_unlocked`)) {
                form.button(`${o.nome} §9[${o.tp} TP]`, "textures/items/pamobile/mg_e_eterno");
            } else {
                form.button(`§a${o.nome} [Comprado]`, "textures/items/pamobile/mg_e_eterno");
            }
        } else {
            const ok = o.req.every(r => player.hasTag(r));
            if (ok) {
                form.button(`§a${o.nome}`, "textures/items/pamobile/mg_e_eterno");
            } else {
                const faltando = o.req.filter(r => !player.hasTag(r)).map(r => reqNames[r]).join(", ");
                form.button(`§c${o.nome}\n§7Requisitos: ${faltando}`, "textures/items/pamobile/mg_e_eterno");
            }
        }
    });

    form.button("§cFechar");

    form.show(player).then(res => {
        if (res.canceled) return;
        if (res.selection >= opts.length) return; 

        const sel = opts[res.selection];
        if (sel.tipo === "mangekyou") {
            const tp = getScore(player, "TP");
            if (tp >= sel.tp && !player.hasTag(`mangekyou_${sel.key}_unlocked`)) {
    setScore(player, "TP", tp - sel.tp);
    player.addTag(`mangekyou_${sel.key}_unlocked`);

    
    const susanooTag = SUSANOO_TAGS[sel.key];
    if (susanooTag) {
        player.addTag(susanooTag);
        player.sendMessage(`§aComprou Mangekyou ${sel.nome} e desbloqueou o Susanoo!`);
    } else {
        player.sendMessage(`§aComprou Mangekyou ${sel.nome}!`);
    }
} else {
    player.sendMessage("§cTP insuficiente ou já comprado.");
}
        } else {
            if (sel.req.every(r => player.hasTag(r))) {
                openAtivarDesativarMenu(player, "Uchiha", sel);
            } else {
                const faltando = sel.req.filter(r => !player.hasTag(r)).map(r => reqNames[r]).join(", ");
                player.sendMessage(`§cRequisitos não atendidos. Faltam: ${faltando}`);
            }
        }
    });
}

export function openClanMenu(player) {
    openClanSelection(player);
}

export function openHistoriaMenu(player) {
    const form = new ActionFormData().title(":zenkai_ui:Historia");
    form.button("§fClassico"); form.button("§fShippuden"); form.button("§fBoruto"); form.button("§fTwo Vortex"); form.button("§fFillers/Filmes");
    form.show(player).then(res => {
        if (res.canceled) return;
        if (res.selection === 0) openMissionList(player, MISSOES, "Classico", true);
        if (res.selection === 1) player.sendMessage("§cShippuden §r§cEm-Breve");
        if (res.selection === 2) player.sendMessage("§cBoruto §r§cEm-Breve");
        if (res.selection === 3) player.sendMessage("§cTwo Vortex §r§cEm-Breve");
        if (res.selection === 4) player.sendMessage("§cFillers/Filmes §r§cEm-Breve");
    });
}

function openMissionList(player, list, sagaName) {
    const form = new ActionFormData().title(`:zenkai_ui:${sagaName}`);

    // Verifica se o player concluiu a missão 10, 20, 30 ou 32
    let nextSaga = null;
    let nextSagaName = null;

    if (player.hasTag("missao10_concluida")) {
        nextSaga = PROXIMA_SAGA;
        nextSagaName = "Exame Chunin (Floresta)";
    }
    if (player.hasTag("missao20_concluida")) {
        nextSaga = PROXIMA_SAGA2;
        nextSagaName = "Exame Chunin (Lutas-1)";
    }
    if (player.hasTag("missao30_concluida")) {
        nextSaga = PROXIMA_SAGA3;
        nextSagaName = "Invasão a Konoha";
    }

    if (nextSaga) {
        form.button(`§b${nextSagaName}`);
    }

    // Botão de reset de sagas (aparece só se missão 32 concluída)
    let showResetButton = player.hasTag("missao32_concluida");
    if (showResetButton) {
        form.button("§cResetar todas as sagas (Custa 5000 TP)");
    }

    const view = list.filter(m => !m.desbloqueiaCom || player.hasTag(m.desbloqueiaCom));
    view.forEach(m => {
        if (m.tagConclusao && player.hasTag(m.tagConclusao)) {
            form.button(`§a${m.nome} (Concluída)`);
        } else if (m.tagAndamento && player.hasTag(m.tagAndamento)) {
            form.button(`§e${m.nome} (Reiniciar?)`);
        } else {
            form.button(`§f${m.nome}`);
        }
    });

    form.show(player).then(res => {
        if (res.canceled) return;
        let selectedIndex = res.selection;

        if (nextSaga) {
            if (selectedIndex === 0) {
                openMissionList(player, nextSaga, nextSagaName);
                return;
            }
            selectedIndex -= 1;
        }

        if (showResetButton) {
            if (selectedIndex === 0) {
                // Verifica TP pelo scoreboard
                player.runCommandAsync("scoreboard players test @s TP 500 1000000").then(res => {
                    if (res.successCount > 0) {
                        // Desconta 500 TP
                        player.runCommandAsync("scoreboard players remove @s TP 500");
                        resetAllSagas(player);
                        player.sendMessage("§cTodas as sagas foram resetadas!");
                    } else {
                        player.sendMessage("§cVocê não tem TP suficiente (500 necessários).");
                    }
                });
                return;
            }
            selectedIndex -= 1;
        }

        if (selectedIndex >= 0 && selectedIndex < view.length) {
            const m = view[selectedIndex];
            if (m.tagConclusao && player.hasTag(m.tagConclusao)) {
                player.sendMessage("§aConcluída");
            } else if (m.tagAndamento && player.hasTag(m.tagAndamento)) {
                openResetMissionConfirm(player, m);
            } else {
                m.acao(player);
            }
        }
    });
}

function openResetMissionConfirm(player, mission) {
    const form = new ActionFormData()
        .title(`:zenkai_ui:Reiniciar ${mission.nome}?`)
        .body("Isso ira remover as entidades da missao atual (Raio 10), limpar itens da missao e reiniciar.")
        .button("§cSim, Reiniciar")
        .button("§8Cancelar");

    form.show(player).then(res => {
        if (!res.canceled && res.selection === 0) {
            if (mission.entidades && mission.entidades.length > 0) {
                mission.entidades.forEach(entID => {
                    try {
                        player.runCommandAsync(`tp @e[type=${entID},r=10] ~ -300 ~`);
                        player.runCommandAsync(`kill @e[type=${entID},r=10]`);
                    } catch { }
                });
            }
            player.removeTag(mission.tagAndamento);
            player.removeTag(`${mission.desbloqueiaCom}_opcao_structure`);
            player.removeTag(`${mission.desbloqueiaCom}_opcao_npc`);
            const itensFixos = ["nz:m1", "nz:m2", "nz:inscricao", "nz:prova", "nz:guizo"];
            const inv = player.getComponent("minecraft:inventory").container;
            for (let i = 0; i < inv.size; i++) {
                const item = inv.getItem(i);
                if (!item) continue;
                if (item.typeId.startsWith("nz:c_missao") || itensFixos.includes(item.typeId)) {
                    inv.setItem(i, undefined);
                }
            }
            player.sendMessage(`§eMissao ${mission.nome} reiniciada!`);
            mission.acao(player);
        }
    });
}

function resetAllSagas(player) {
    // Pega todas as tags atuais do jogador
    const tags = player.getTags();

    // Filtra apenas as que começam com "missao" e terminam com "_concluida" ou "_andamento"
    const tagsParaRemover = tags.filter(tag =>
        tag.startsWith("missao") &&
        (tag.endsWith("_concluida") || tag.endsWith("_andamento"))
    );

    // Remove todas as tags filtradas
    tagsParaRemover.forEach(tag => {
        player.removeTag(tag);
    });

    player.sendMessage("§cTodas as missões e sagas foram resetadas com sucesso!");
}

function openInvocacoesMenu(player) {
  const form = new ActionFormData()
    .title(":zenkai_ui:Invocações")
    .body("Escolha uma opção:");

  form.button("§fInvocações");
  form.button("§fTreino");
  form.button("§cVoltar");

  form.show(player).then(res => {
    if (res.canceled) return;

    if (res.selection === 0) {
      openInvocacoesListMenu(player);
    } else if (res.selection === 1) {
      openTreinoMenu(player);
    }
  });
}


function openInvocacoesListMenu(player) {
  const lvl = getScore(player, "Lvl") || 0;
  const hasHagoromo = player.hasTag("dna_hagoromo");
  const gedoInvocado = player.hasTag("gedo_invocado");
  const obj = world.scoreboard.getObjective("gedo_mazou");
  let score = obj ? (obj.getScore(player) ?? 0) : 0;
  if (score < 0) score = 0;
  if (score > 9) score = 9;

  const form = new ActionFormData()
    .title(":zenkai_ui:Invocações")
    .body("Escolha uma invocação:");

  
  if (!hasHagoromo || lvl < 25) {
    form.button("§8Gedo Mazou (Requer DNA Hagoromo + Lvl 25)");
  } else {
    if (!gedoInvocado) form.button("§bInvocar Gedo Mazou");
    else if (score >= 9) form.button("§5Invocar Juubi");
    else form.button("§cDesinvocar Gedo");
  }

  
  form.button("§7Gamabunta (Em breve)");
  form.button("§7Katsuyu (Em breve)");
  form.button("§7Manda (Em breve)");
  form.button("§7Gamakichi (Em breve)");
  form.button("§7Emma (Em breve)");
  form.button("§7Falcão (Em breve)");
  form.button("§7Salamandra (Em breve)");
  form.button("§7Kamatari (Em breve)");
  form.button("§7Ningame (Em breve)");
  form.button("§7Quimera (Rinnegan) (Em breve)");
  form.button("§7Baku (Em breve)");
  form.button("§7Ninken (Em breve)");

  form.button("§cVoltar");

  form.show(player).then(res => {
    if (res.canceled) return;

    let index = 0;

    
    if (res.selection === index++) {
      if (!hasHagoromo || lvl < 25) {
        player.sendMessage("§cVocê precisa do DNA Hagoromo e ser nível 25 para invocar o Gedo!");
        return;
      }

      if (!gedoInvocado) {
        const max = Math.min(score, 9);
        player.runCommandAsync(`summon nz:gedo_mazou${max} ~ ~ ~`);
        player.addTag("gedo_invocado");
        player.sendMessage(`§bGedo Mazou ${max} invocado!`);
      } else {
        if (score >= 9) {
          player.runCommandAsync(`kill @e[type=nz:gedo_mazou9]`);
          player.runCommandAsync(`summon nz:juubi_v1 ~ ~ ~`);
          const jins = [
            "jinchuuriki_shukaku","jinchuuriki_matatabi","jinchuuriki_isobu","jinchuuriki_songoku",
            "jinchuuriki_kokuo","jinchuuriki_saiken","jinchuuriki_chomei","jinchuuriki_gyuki","jinchuuriki_kurama"
          ];
          jins.forEach(t => player.removeTag(t));
          player.runCommandAsync(`scoreboard players set @s gedo_mazou 0`);
          player.removeTag("gedo_invocado");
          player.sendMessage("§cJuubi Invocado!");
        } else {
          for (let i = 0; i <= 9; i++) {
            player.runCommandAsync(`kill @e[type=nz:gedo_mazou${i}]`);
          }
          player.runCommandAsync(`summon nz:gedo_mazou${score} ~ ~ ~`);
          player.addTag("gedo_invocado");
          player.sendMessage(`§bGedo Mazou ${score} invocado automaticamente!`);
        }
      }
      return;
    }

    
    if (res.selection >= index && res.selection < index + 12) {
      player.sendMessage("§7Invocação em breve!");
      return;
    }
  });
}


function openTreinoMenu(player) {
  const hasDummy = player.hasTag("dummy_active");
  const tagDummy = `dummy_${player.id}`;

  const form = new ActionFormData()
    .title(":zenkai_ui:Treino")
    .body("Escolha uma opção:");

  form.button(hasDummy ? "§fDesinvocar Dummy" : "§fInvocar Dummy");
  form.button("§cVoltar");

  form.show(player).then(res => {
    if (res.canceled) return;

    if (res.selection === 0) {
      if (!hasDummy) {
        player.runCommandAsync(`summon nz:dummy ~ ~ ~`);
        player.runCommandAsync(`tag @e[type=nz:dummy,r=6,c=1] add ${tagDummy}`);
        player.addTag("dummy_active");
        player.sendMessage("§aDummy invocado para treino!");
      } else {
        player.runCommandAsync(`kill @e[type=nz:dummy,tag=${tagDummy}]`);
        player.removeTag("dummy_active");
        player.sendMessage("§cDummy desinvocado!");
      }
    }
  });
}

const ACESSORIOS = {
    acess: { nome: "Remover", acessId: 1 },
    chapeuho: { nome: "Chapéu Hokage", acessId: 2 },
    chapeukaze: { nome: "Chapéu Kazekage", acessId: 3 },
    chapeumizu: { nome: "Chapéu Mizukage", acessId: 4 },
    chapeutsuchi: { nome: "Chapéu Tsuchikage", acessId: 5 },
    chapeurai: { nome: "Chapéu Raikage", acessId: 6 },
    chapeuakt: { nome: "Chapéu Akatsuki", acessId: 7 },
    chapeumonarca: { nome: "Chapéu Monarca", acessId: 8 },
    chapeulp: { nome: "Chapéu LP", acessId: 9 },
    brincoorochi: { nome: "Brinco Orochimaru", acessId: 10 }
};

const MASCARAS = {
    bankonoha: { nome: "Bandana de Konoha", maskId: 2 },
    bansuna: { nome: "Bandana de Suna", maskId: 3 },
    bannevoa: { nome: "Bandana da Névoa", maskId: 4 },
    banchuva: { nome: "Bandana da Chuva", maskId: 5 },
    banpedra: { nome: "Bandana da Pedra", maskId: 6 },
    bansom: { nome: "Bandana do Som", maskId: 7 },
    mascaratobi: { nome: "Tobi", maskId: 8 },
    mascaraobito: { nome: "Obito", maskId: 9 },
    mascaraanbu1: { nome: "Anbu Kakashi", maskId: 10 },
    bannuvem: { nome: "Bandana da Nuvem", maskId: 11 },
    mascaraanbu2: { nome: "Anbu Itachi", maskId: 12 },
    mascarakakashi: { nome: "Mascara Kakashi", maskId: 13 },
    bankonohare: { nome: "Bandana (RENEGADO) de Konoha", maskId: 14 },
    bansunare: { nome: "Bandana (RENEGADO) de Suna", maskId: 15 },
    bannevoare: { nome: "Bandana (RENEGADO) da Névoa", maskId: 16 },
    banpedrare: { nome: "Bandana (RENEGADO) da Pedra", maskId: 17 },
    bannuvemre: { nome: "Bandana (RENEGADO) da Nuvem", maskId: 18 },
    banchuvare: { nome: "Bandana (RENEGADO) da Chuva", maskId: 19 }
};

const EXTRASS = {
    extra1: { nome: "Remover Extra", extraId: 1 },
    joninfolha: { nome: "Colete Ninja de Konohagakure", extraId: 2 },
    mantohokage: { nome: "Manto Hokage", extraId: 3 },
    mantokazekage: { nome: "Manto Kazekage", extraId: 4 },
    mantomizukage: { nome: "Manto Mizukage", extraId: 5 },
    mantotsuchikage: { nome: "Manto Tsuchikage", extraId: 6 },
    mantoraikage: { nome: "Manto Raikage", extraId: 7 },
    mantoakt: { nome: "Manto Akatsuki", extraId: 8 },
    mantoaktbranco: { nome: "Manto Akatsuki Branco", extraId: 9 },
    mantomonarca: { nome: "Manto Monarca", extraId: 10 },
    mantolp: { nome: "Manto LP", extraId: 11 },
    mantotsunade: { nome: "Manto Tsunade", extraId: 12 },
    pergaminiomissao: { nome: "Pergaminio Missao", extraId: 13 },
    mantosenninsapo: { nome: "Manto Gama Sennin", extraId: 14 },
    joninareia: { nome: "Colete Ninja de Sunagakure", extraId: 15 },
    joninnevoa: { nome: "Colete Ninja de Kirigakure", extraId: 16 },
    joninnuvem: { nome: "Colete Ninja de Kumogakure", extraId: 17 },
    joninpedra: { nome: "Colete Ninja de Iwagakure", extraId: 18 },
    isshiki_mode: { nome: "Manto Isshiki", extraId: 19 }
};

function openMaskEquipSubMenu(player, tag, def, tipo) {
    const form = new ActionFormData().title(`:zenkai_ui:${def.nome}`);
    const tagEquipada = `${tipo}_${tag}_equipado`;
    const isEquipada = player.hasTag(tagEquipada);

    if (!isEquipada) form.button("§aEquipar");
    else form.button("§cDesequipar");
    form.button("§8Cancelar");

    form.show(player).then(res => {
        if (res.canceled) return;

        if (!isEquipada && res.selection === 0) {
            const tags = player.getTags();
            for (const t of tags) {
                if (t.startsWith(`${tipo}_`) && t.endsWith("_equipado")) {
                    player.removeTag(t);
                    // volta para o estado "sem item" do tipo
                    player.runCommandAsync(`event entity @s test:${tipo}1`);
                }
            }
            player.addTag(tagEquipada);

            // Seleciona o ID correto dependendo do tipo
            let id;
            if (tipo === "mask") id = def.maskId;
            else if (tipo === "extra") id = def.extraId;
            else if (tipo === "acess") id = def.acessId;

            player.runCommandAsync(`event entity @s test:${tipo}${id}`);
            player.sendMessage(`§a${def.nome} equipado!`);
        } else if (isEquipada && res.selection === 0) {
            player.removeTag(tagEquipada);
            // acess1 é o remover, então sempre volta para esse estado
            player.runCommandAsync(`event entity @s test:${tipo}1`);
            player.sendMessage(`§c${def.nome} desequipado!`);
        }
    });
}

function openMaskEquipMenu(player) {
    const form = new ActionFormData().title(":zenkai_ui:§fMask/Equip");
    const tags = player.getTags();

    const disponiveisMasks = Object.keys(MASCARAS).filter(t => tags.includes(t));
    const disponiveisExtras = Object.keys(EXTRASS).filter(t => tags.includes(t));
    const disponiveisAcess = Object.keys(ACESSORIOS).filter(t => tags.includes(t));

    if (disponiveisMasks.length === 0 && disponiveisExtras.length === 0 && disponiveisAcess.length === 0) {
        form.body("§7Você não possui nenhuma máscara, extra ou acessório.");
        form.button("§8Cancelar");
    } else {
        disponiveisMasks.forEach(t => form.button(MASCARAS[t].nome));
        disponiveisExtras.forEach(t => form.button(EXTRASS[t].nome));
        disponiveisAcess.forEach(t => form.button(ACESSORIOS[t].nome));
        form.button("§8Cancelar");
    }

    form.show(player).then(res => {
        if (res.canceled) return;
        const total = disponiveisMasks.length + disponiveisExtras.length + disponiveisAcess.length;
        if (res.selection >= total) return;

        if (res.selection < disponiveisMasks.length) {
            const tag = disponiveisMasks[res.selection];
            openMaskEquipSubMenu(player, tag, MASCARAS[tag], "mask");
        } else if (res.selection < disponiveisMasks.length + disponiveisExtras.length) {
            const tag = disponiveisExtras[res.selection - disponiveisMasks.length];
            openMaskEquipSubMenu(player, tag, EXTRASS[tag], "extra");
        } else {
            const tag = disponiveisAcess[res.selection - disponiveisMasks.length - disponiveisExtras.length];
            openMaskEquipSubMenu(player, tag, ACESSORIOS[tag], "acess");
        }
    });
}