#include "core/layouts_menu.h"
#include <imgui.h>
#include <cstring>

namespace fn_ui {

bool layouts_menu_items(const char* menu_label, LayoutCallbacks& cb) {
    bool acted = false;

    if (!ImGui::BeginMenu(menu_label)) return false;

    // ── Lista de layouts guardados ────────────────────────────────────────
    if (cb.list) {
        std::vector<std::string> names = cb.list();
        for (const std::string& name : names) {
            // Construir label con marker si es el activo
            std::string label;
            if (!cb.active_name.empty() && name == cb.active_name) {
                label = "* " + name;
            } else {
                label = "  " + name;
            }
            if (ImGui::MenuItem(label.c_str()) && cb.on_apply) {
                cb.on_apply(name);
                acted = true;
            }
        }
    }

    ImGui::Separator();

    // ── Save current as... ────────────────────────────────────────────────
    if (ImGui::MenuItem("Save current as...")) {
        ImGui::OpenPopup("##save_layout");
    }

    // Popup "Save as..."
    // Estado local del input: buffer estatico de 64 char.
    static char s_name_buf[64] = "";
    if (ImGui::BeginPopup("##save_layout")) {
        ImGui::Text("Layout name:");
        ImGui::SetNextItemWidth(200.0f);
        ImGui::InputText("##layout_name", s_name_buf, sizeof(s_name_buf));

        bool name_valid = s_name_buf[0] != '\0';
        if (!name_valid) ImGui::BeginDisabled();
        if (ImGui::Button("Save") && name_valid && cb.on_save) {
            cb.on_save(std::string(s_name_buf));
            s_name_buf[0] = '\0';
            acted = true;
            ImGui::CloseCurrentPopup();
        }
        if (!name_valid) ImGui::EndDisabled();

        ImGui::SameLine();
        if (ImGui::Button("Cancel")) {
            s_name_buf[0] = '\0';
            ImGui::CloseCurrentPopup();
        }
        ImGui::EndPopup();
    }

    // ── Delete submenu ────────────────────────────────────────────────────
    if (ImGui::BeginMenu("Delete")) {
        std::vector<std::string> names;
        if (cb.list) names = cb.list();

        if (names.empty()) {
            ImGui::MenuItem("(no layouts)", nullptr, false, false);
        } else {
            for (const std::string& name : names) {
                if (ImGui::MenuItem(name.c_str()) && cb.on_delete) {
                    cb.on_delete(name);
                    acted = true;
                }
            }
        }
        ImGui::EndMenu();
    }

    ImGui::Separator();

    // ── Reset to default ──────────────────────────────────────────────────
    if (ImGui::MenuItem("Reset to default") && cb.on_reset) {
        cb.on_reset();
        acted = true;
    }

    ImGui::EndMenu();
    return acted;
}

} // namespace fn_ui
