#include "core/tree_view.h"
#include "core/tokens.h"
#include <imgui.h>
#include <cstdio>

namespace fn_ui {

namespace {

bool g_last_clicked = false;

ImGuiTreeNodeFlags base_flags() {
    return ImGuiTreeNodeFlags_SpanFullWidth
         | ImGuiTreeNodeFlags_OpenOnArrow
         | ImGuiTreeNodeFlags_OpenOnDoubleClick;
}

void push_node_colors(bool selected) {
    using namespace fn_tokens::colors;
    // Fondo y hover — el Selected usa Header color por convencion de ImGui
    ImGui::PushStyleColor(ImGuiCol_Header,        selected ? surface_hover : ImVec4(0, 0, 0, 0));
    ImGui::PushStyleColor(ImGuiCol_HeaderHovered, surface_hover);
    ImGui::PushStyleColor(ImGuiCol_HeaderActive,  surface);
    ImGui::PushStyleColor(ImGuiCol_Text,          selected ? fn_tokens::colors::primary : fn_tokens::colors::text);
}

void pop_node_colors() {
    ImGui::PopStyleColor(4);
}

} // namespace

void tree_leaf(const char* id, const char* label, bool selected) {
    push_node_colors(selected);
    char full[256];
    std::snprintf(full, sizeof(full), "%s##%s", label, id);
    ImGuiTreeNodeFlags flags = base_flags()
        | ImGuiTreeNodeFlags_Leaf
        | ImGuiTreeNodeFlags_NoTreePushOnOpen
        | ImGuiTreeNodeFlags_Bullet;
    if (selected) flags |= ImGuiTreeNodeFlags_Selected;

    ImGui::TreeNodeEx(full, flags);
    g_last_clicked = ImGui::IsItemClicked();
    pop_node_colors();
}

bool tree_branch_begin(const char* id, const char* label, bool selected) {
    push_node_colors(selected);
    char full[256];
    std::snprintf(full, sizeof(full), "%s##%s", label, id);
    ImGuiTreeNodeFlags flags = base_flags();
    if (selected) flags |= ImGuiTreeNodeFlags_Selected;

    const bool open = ImGui::TreeNodeEx(full, flags);
    g_last_clicked = ImGui::IsItemClicked();
    pop_node_colors();
    return open;
}

void tree_branch_end() {
    ImGui::TreePop();
}

void tree_root(const char* id, const char* label, bool selected) {
    // Igual que leaf pero sin bullet ni indent
    push_node_colors(selected);
    char full[256];
    std::snprintf(full, sizeof(full), "%s##%s", label, id);
    ImGuiTreeNodeFlags flags = base_flags()
        | ImGuiTreeNodeFlags_Leaf
        | ImGuiTreeNodeFlags_NoTreePushOnOpen;
    if (selected) flags |= ImGuiTreeNodeFlags_Selected;

    ImGui::TreeNodeEx(full, flags);
    g_last_clicked = ImGui::IsItemClicked();
    pop_node_colors();
}

bool tree_node_clicked() {
    const bool r = g_last_clicked;
    g_last_clicked = false;
    return r;
}

} // namespace fn_ui
