#include "gfx/dag_palette.h"
#include "gfx/dag_catalog.h"
#include "imgui.h"

namespace fn::gfx {

static ImVec4 kind_tint(DagKind kind) {
    switch (kind) {
        case DagKind::Gen:    return ImVec4(0.25f, 0.55f, 0.90f, 1.0f);
        case DagKind::Op:     return ImVec4(0.65f, 0.40f, 0.90f, 1.0f);
        case DagKind::Blend:  return ImVec4(0.90f, 0.65f, 0.15f, 1.0f);
        case DagKind::Output: return ImVec4(0.85f, 0.25f, 0.25f, 1.0f);
    }
    return ImVec4(1, 1, 1, 1);
}

static void draw_group(const char* header, DagKind kind) {
    if (!ImGui::CollapsingHeader(header, ImGuiTreeNodeFlags_DefaultOpen)) return;

    ImVec4 col = kind_tint(kind);
    ImGui::PushStyleColor(ImGuiCol_Button,        ImVec4(col.x * 0.35f, col.y * 0.35f, col.z * 0.35f, 0.9f));
    ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(col.x * 0.55f, col.y * 0.55f, col.z * 0.55f, 1.0f));
    ImGui::PushStyleColor(ImGuiCol_ButtonActive,  ImVec4(col.x * 0.75f, col.y * 0.75f, col.z * 0.75f, 1.0f));

    for (const auto& def : dag_catalog()) {
        if (def.kind != kind) continue;
        ImGui::PushID(def.name.c_str());
        ImGui::Button(def.label.c_str(), ImVec2(-1, 0));
        if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_SourceAllowNullID)) {
            ImGui::SetDragDropPayload("DAG_NODE_TYPE", def.name.c_str(), def.name.size());
            ImGui::Text("+ %s", def.label.c_str());
            if (!def.desc.empty()) {
                ImGui::TextDisabled("%s", def.desc.c_str());
            }
            ImGui::EndDragDropSource();
        }
        if (ImGui::IsItemHovered() && !def.desc.empty()) {
            ImGui::SetTooltip("%s", def.desc.c_str());
        }
        ImGui::PopID();
    }

    ImGui::PopStyleColor(3);
}

void dag_palette() {
    ImGui::TextDisabled("Drag into the DAG Pipeline canvas.");
    ImGui::Spacing();
    draw_group("Generators", DagKind::Gen);
    draw_group("Operators",  DagKind::Op);
    draw_group("Blends",     DagKind::Blend);
}

} // namespace fn::gfx
