#include "viz/sparkline.h"
#include "imgui.h"

void sparkline(const char* id, const float* values, int count, ImVec4 color,
               float width, float height) {
    if (count <= 0) return;

    ImGui::PushID(id);

    ImVec2 pos = ImGui::GetCursorScreenPos();
    ImDrawList* draw_list = ImGui::GetWindowDrawList();

    // Reserve inline space
    ImGui::Dummy(ImVec2(width, height));

    // Find min/max for Y auto-scale
    float min_val = values[0];
    float max_val = values[0];
    for (int i = 1; i < count; i++) {
        if (values[i] < min_val) min_val = values[i];
        if (values[i] > max_val) max_val = values[i];
    }
    float range = max_val - min_val;
    if (range < 1e-6f) range = 1.0f; // avoid division by zero for flat lines

    // Fill area under curve (low alpha)
    if (count >= 2) {
        ImU32 fill_color = IM_COL32(
            (int)(color.x * 255),
            (int)(color.y * 255),
            (int)(color.z * 255),
            40);

        // Build fill polygon: baseline bottom-left -> points -> baseline bottom-right
        // We use AddConvexPolyFilled workaround: draw as a series of triangles from baseline
        float x0 = pos.x;
        float y_base = pos.y + height;

        for (int i = 0; i + 1 < count; i++) {
            float xa = x0 + ((float)i       / (count - 1)) * width;
            float xb = x0 + ((float)(i + 1) / (count - 1)) * width;
            float ya = pos.y + height - ((values[i]     - min_val) / range) * height;
            float yb = pos.y + height - ((values[i + 1] - min_val) / range) * height;

            draw_list->AddQuadFilled(
                ImVec2(xa, y_base),
                ImVec2(xa, ya),
                ImVec2(xb, yb),
                ImVec2(xb, y_base),
                fill_color);
        }
    }

    // Draw polyline
    ImU32 line_color = IM_COL32(
        (int)(color.x * 255),
        (int)(color.y * 255),
        (int)(color.z * 255),
        (int)(color.w * 255));

    for (int i = 0; i + 1 < count; i++) {
        float xa = pos.x + ((float)i       / (count - 1)) * width;
        float xb = pos.x + ((float)(i + 1) / (count - 1)) * width;
        float ya = pos.y + height - ((values[i]     - min_val) / range) * height;
        float yb = pos.y + height - ((values[i + 1] - min_val) / range) * height;
        draw_list->AddLine(ImVec2(xa, ya), ImVec2(xb, yb), line_color, 1.5f);
    }

    ImGui::PopID();
}

void sparkline(const char* id, const float* values, int count,
               float width, float height) {
    // Default color: soft green
    sparkline(id, values, count, ImVec4(0.35f, 0.85f, 0.45f, 1.0f), width, height);
}
