#include "viz/histogram.h"
#include "viz/plot_static.h"
#include "implot.h"

namespace {

template <typename T>
void draw_hist(const char* title, const T* values, int count, int bins, float height) {
    if (count <= 0) return;

    int b = (bins > 0) ? bins : ImPlotBin_Sturges;
    const ImVec2 plot_size(-1.0f, height > 0.0f ? height : 200.0f);

    // PlotHistogram necesita auto-fit para decidir limites segun los bins
    // calculados, asi que en histograma permitimos el primer fit pero
    // bloqueamos pan/zoom posterior via Lock.
    const ImPlotAxisFlags axis_flags =
          ImPlotAxisFlags_NoMenus | ImPlotAxisFlags_Lock
        | ImPlotAxisFlags_NoHighlight | ImPlotAxisFlags_AutoFit;

    if (ImPlot::BeginPlot(title, plot_size, plot_static::kPlotFlags)) {
        ImPlot::SetupAxes(nullptr, nullptr, axis_flags, axis_flags);
        ImPlot::PlotHistogram("##data", values, count, b);
        ImPlot::EndPlot();
    }
}

} // namespace

void histogram(const char* title, const float* values, int count, int bins, float height) {
    draw_hist<float>(title, values, count, bins, height);
}

void histogram(const char* title, const double* values, int count, int bins, float height) {
    draw_hist<double>(title, values, count, bins, height);
}
