#include "dashboard_grid.h"
#include <imgui.h>
#include <vector>

// Internal state stack to support nested grids.
namespace {

struct GridState {
    int   columns;
    float spacing;
    float col_width;
    int   counter;  // number of dashboard_grid_next() calls so far
};

static std::vector<GridState> g_grid_stack;

} // namespace

void dashboard_grid_begin(int columns, float spacing) {
    if (columns < 1) columns = 1;

    float available = ImGui::GetContentRegionAvail().x;
    float col_width = (available - spacing * static_cast<float>(columns - 1))
                      / static_cast<float>(columns);
    if (col_width < 1.0f) col_width = 1.0f;

    g_grid_stack.push_back({columns, spacing, col_width, 0});

    ImGui::BeginGroup();
    ImGui::PushItemWidth(col_width);
}

void dashboard_grid_next() {
    if (g_grid_stack.empty()) return;

    GridState& s = g_grid_stack.back();

    ImGui::PopItemWidth();
    ImGui::EndGroup();

    s.counter++;

    if (s.counter % s.columns != 0) {
        // Same row: advance horizontally.
        ImGui::SameLine(0.0f, s.spacing);
    }
    // If counter % columns == 0 the next BeginGroup starts a new row automatically.

    ImGui::BeginGroup();
    ImGui::PushItemWidth(s.col_width);
}

void dashboard_grid_end() {
    if (g_grid_stack.empty()) return;

    ImGui::PopItemWidth();
    ImGui::EndGroup();

    g_grid_stack.pop_back();
}
