import { world, system } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";
import { openClanSelection } from "./clan_selection.js"; 

world.beforeEvents.itemUse.subscribe((data) => {
    const itemId = data.itemStack?.typeId;

    if (itemId === "nz:menu_custom" || itemId === "nz:display_config" || itemId === "nz:display_custom") {
        system.run(() => {
            openClanSelection(data.source);
        });
    }
});

const PELES_CLAN = {
    Uzumaki: { Male: [1, 2, 3], Female: [17, 18, 19] },
    Aburame: { Male: [4, 5, 6], Female: [20, 21, 22] },
    Uchiha: { Male: [4, 5, 6], Female: [20, 21, 22] },
    Chinoike: { Male: [4, 5, 6], Female: [20, 21, 22] },
    Akimichi: { Male: [7, 8, 9], Female: [23, 24, 25] },
    HyugaNormal: { Male: [10, 11, 12], Female: [26, 27, 28] },
    HyugaSelado: { Male: [13, 14, 15], Female: [29, 30, 31] },
    Senju: { Male: [7, 8, 9], Female: [23, 24, 25] }
};

const CABELOS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const PELES_PADRAO = Array.from({ length: 12 }, (_, i) => i + 1);
const playerStates = new Map();

function getClanKey(player) {
    const keys = Object.keys(PELES_CLAN);
    for (const k of keys) {
        if (player.hasTag(k) || player.hasTag(k.toLowerCase())) return k;
    }
    return null;
}

function getGenero(player) {
    if (player.hasTag("female")) return "Female";
    return "Male";
}

function aplicarVisual(player, peleId, cabeloId) {
    player.runCommandAsync(`event entity @s test:custom${peleId}`);
    player.runCommandAsync(`event entity @s test:cabelo${cabeloId}`);
    player.runCommandAsync(`titleraw @s actionbar {"rawtext":[{"text":"§aPele | Cabelo"}]}`);
}

export function abrirMenuCustom(player) {
    const clanKey = getClanKey(player);
    const genero = getGenero(player);

    let listaPeles = PELES_PADRAO;
    if (clanKey && PELES_CLAN[clanKey] && PELES_CLAN[clanKey][genero]) {
        listaPeles = PELES_CLAN[clanKey][genero];
    }
    
    if (!playerStates.has(player.id)) playerStates.set(player.id, { peleIdx: 0, cabeloIdx: 0 });
    const state = playerStates.get(player.id);
    if (state.peleIdx >= listaPeles.length) state.peleIdx = 0;

    const peleAtual = listaPeles[state.peleIdx];
    const cabeloAtual = CABELOS[state.cabeloIdx];

    const form = new ActionFormData()
        .title(":zenkai_character_creator:§fCustomização")
        .body(`§fPele\n\n§fCabelo`) 
        .button("§p§r§e§v§s§k§i§n") 
        .button("§n§e§x§t§s§k§i§n") 
        .button("§p§r§e§v§h§a§i§r") 
        .button("§n§e§x§t§h§a§i§r") 
        .button("§d§o§n§e§aConfirmar"); 

    form.show(player).then((res) => {
        if (res.canceled) {
            // Reabre o menu se o jogador fechar
            abrirMenuCustom(player);
            return;
        }

        switch (res.selection) {
            case 0: 
                state.cabeloIdx = (state.cabeloIdx - 1 + CABELOS.length) % CABELOS.length;
                aplicarVisual(player, listaPeles[state.peleIdx], CABELOS[state.cabeloIdx]);
                abrirMenuCustom(player);
                break;
            case 1: 
                state.cabeloIdx = (state.cabeloIdx + 1) % CABELOS.length;
                aplicarVisual(player, listaPeles[state.peleIdx], CABELOS[state.cabeloIdx]);
                abrirMenuCustom(player);
                break;
            case 2: 
                state.peleIdx = (state.peleIdx - 1 + listaPeles.length) % listaPeles.length;
                aplicarVisual(player, listaPeles[state.peleIdx], CABELOS[state.cabeloIdx]);
                abrirMenuCustom(player);
                break;
            case 3: 
                state.peleIdx = (state.peleIdx + 1) % listaPeles.length;
                aplicarVisual(player, listaPeles[state.peleIdx], CABELOS[state.cabeloIdx]);
                abrirMenuCustom(player);
                break;
            case 4: 
                player.addTag("menu_status_entregue");
                player.addTag("ItensIniciaisEntregues");
                
                player.runCommandAsync(`replaceitem entity @s slot.hotbar 8 nz:display_config1 1 0 {"minecraft:item_lock":{"mode":"lock_in_slot"}}`);
                player.sendMessage("§aPersonagem criado com sucesso!");
                player.runCommandAsync(`titleraw @s title {"rawtext":[{"text":"§aBem-Vindo Shinobi!"}]}`);
                player.runCommandAsync("clear @s nz:menu_custom");
                
                playerStates.delete(player.id);
                break;
        }
    });
}