import { world, system } from "@minecraft/server";
import * as ui from "@minecraft/server-ui";

console.warn("[BASES_MENU] Script carregado");






////////////////////////////TELEPORTE BASE



// ================================
// CONFIG
// ================================
const COOLDOWN_MS = 1000;
const cooldown = new WeakMap();
const GLOBAL_KEY = "bases_globais";

// ================================
// CORES ALEATÓRIAS
// ================================
const CORES_BASE = ["§b", "§d", "§e", "§6", "§9", "§2", "§f"];
const corAleatoria = () => CORES_BASE[Math.floor(Math.random() * CORES_BASE.length)];

// ================================
// UTIL: GET / SET BASES
// ================================
function getBases() {
    try {
        const raw = world.getDynamicProperty(GLOBAL_KEY);
        if (raw) return JSON.parse(raw);
    } catch {}
    return [];
}

function salvarBases(lista) {
    world.setDynamicProperty(GLOBAL_KEY, JSON.stringify(lista));
}

// ================================
// MENU PRINCIPAL
// ================================
async function abrirMenuPrincipal(player) {
    const form = new ui.ActionFormData()
        .title({ rawtext: [{ translate: "menu_bases" }] })
        .body({ rawtext: [{ translate: "menu.bases.escolha" }] })
        .button({ rawtext: [{ translate: "menu.bases.registrar" }] }, "textures/ui/icon_bell.png")
        .button({ rawtext: [{ translate: "menu.bases.listar" }] }, "textures/ui/icon_bookshelf.png")
        .button({ rawtext: [{ translate: "menu.bases.remover" }] }, "textures/ui/ErrorGlyph.png");

    const res = await form.show(player);
    if (res.canceled) return;

    if (res.selection === 0) await registrarBase(player);
    if (res.selection === 1) await abrirListaBases(player);
    if (res.selection === 2) await abrirRemoverBases(player);
}

// ================================
// REGISTRAR BASE
// ================================
async function registrarBase(player) {
    const form = new ui.ModalFormData()
        .title({ rawtext: [{ translate: "menu.bases.registrar.titulo" }] })
        .textField(
            { rawtext: [{ translate: "menu.bases.registrar.nome" }] },
            { rawtext: [{ translate: "menu.bases.registrar.nome_exemplo" }] }
        )
        .toggle(
            { rawtext: [{ translate: "menu.bases.registrar.publica_toggle" }] },
            { defaultValue: false }
        );

    const result = await form.show(player);
    if (result.canceled) return;

    const nome = result.formValues[0]?.trim();
    const publico = result.formValues[1];

    if (!nome) {
        player.sendMessage({ rawtext: [{ translate: "menu.bases.registrar.erro_nome" }] });
        return;
    }

    const bases = getBases();
    
	const x = Math.floor(player.location.x) + 0.5;
    const y = Math.floor(player.location.y);
    const z = Math.floor(player.location.z) + 0.5;
    const dim = player.dimension.id;
    
    // 🔒 Verifica se já existe base nesse ponto
    const jaExiste = bases.some(b =>
        b.x === x &&
        b.y === y &&
        b.z === z &&
        b.dim === dim
    );

if (jaExiste) {
    player.sendMessage({
        rawtext: [{ translate: "menu.bases.registrar.erro_local_ocupado" }]
    });
    return;
}
	
	
	
	
	
	bases.push({
        nome,
        x,
        y,
        z,
        dim,
        dono: player.name,
        publico
    });

    salvarBases(bases);

    player.sendMessage({
        rawtext: [{
            translate: "menu.bases.registrar.sucesso",
            with: [nome, publico ? "§aPública" : "§cPrivada"]
        }]
    });
}

// ================================
// LISTA DE BASES
// ================================
async function abrirListaBases(player) {
    const bases = getBases();
    if (bases.length === 0) {
        player.sendMessage({ rawtext: [{ translate: "menu.bases.lista.vazia" }] });
        return;
    }

    const form = new ui.ActionFormData()
        .title({ rawtext: [{ translate: "menu.bases.lista.titulo" }] })
        .body({ rawtext: [{ translate: "menu.bases.lista.escolha" }] });

    bases.forEach(base => {
        const cor = corAleatoria();
        const status = base.publico ? "§a[Pública]" : "§c[Privada]";
        form.button(
            { rawtext: [{ text: `${cor}${base.nome}\n§r(${base.dono}) ${status}` }] },
            "textures/ui/undoArrow.png"
        );
    });

    const res = await form.show(player);
    if (res.canceled) return;

    const base = bases[res.selection];
    if (!base) return;

    if (!base.publico && base.dono !== player.name) {
        player.sendMessage({ rawtext: [{ translate: "menu.bases.lista.erro_privada" }] });
        return;
    }

    player.teleport(
        { x: base.x, y: base.y, z: base.z },
        { dimension: world.getDimension(base.dim) }
    );
}

// ================================
// REMOVER BASE
// ================================
async function abrirRemoverBases(player) {
    const bases = getBases().filter(b => b.dono === player.name);
    if (bases.length === 0) {
        player.sendMessage({ rawtext: [{ translate: "menu.bases.remover.vazio" }] });
        return;
    }

    const form = new ui.ActionFormData()
        .title({ rawtext: [{ translate: "menu.bases.remover.titulo" }] })
        .body({ rawtext: [{ translate: "menu.bases.remover.escolha" }] });

    bases.forEach(base => {
        form.button(
            { rawtext: [{ text: `§4${base.nome}\n§r(${base.dono})` }] },
            "textures/ui/undoArrow.png"
        );
    });

    const res = await form.show(player);
    if (res.canceled) return;

    confirmarRemocao(player, bases[res.selection]);
}

async function confirmarRemocao(player, base) {
    const form = new ui.MessageFormData()
        .title({ rawtext: [{ translate: "menu.bases.remover.confirmar_titulo" }] })
        .body({ rawtext: [{ translate: "menu.bases.remover.confirmar_texto", with: [base.nome] }] })
        .button1({ rawtext: [{ translate: "menu.bases.remover.botao_remover" }] })
        .button2({ rawtext: [{ translate: "menu.bases.remover.botao_cancelar" }] });

    const res = await form.show(player);
    if (res.canceled || res.selection === 1) return;

    const bases = getBases().filter(b =>
        !(b.nome === base.nome && b.x === base.x && b.y === base.y && b.z === base.z && b.dono === player.name)
    );

    salvarBases(bases);
    player.sendMessage({ rawtext: [{ translate: "menu.bases.remover.sucesso", with: [base.nome] }] });
    player.playSound("random.break");
}

// ================================
// ABRIR MENU PELO BLOCO
// ================================
world.beforeEvents.playerInteractWithBlock.subscribe(ev => {
    const player = ev.player;
    const block = ev.block;
    if (!player || !block) return;
    if (block.typeId !== "well:pedra_teleporte_animada") return;

    const agora = Date.now();
    const ultimo = cooldown.get(player) ?? 0;
    if (agora - ultimo < COOLDOWN_MS) return;
    cooldown.set(player, agora);

    ev.cancel = true;
    system.run(() => abrirMenuPrincipal(player));
});
