#pragma once

#include "source.h"

#include <QWidget>
#include <deque>
#include <memory>
#include <vector>

class QLabel;
class QPushButton;
class QTableWidget;

/**
 * Collapsible statistics bar embedded at the bottom of the central widget.
 *
 * Header row (always visible): toggle ▲/▼ button + summary text.
 * Expanded content: per-source table with rate, latency, loss;
 *                   per-source sparkline bar charts for packet rate.
 *
 * Call refresh() each timer tick.
 */
class StatsPanel : public QWidget {
    Q_OBJECT
public:
    explicit StatsPanel(QWidget* parent = nullptr);

    void refresh(const std::vector<std::shared_ptr<Source>>& sources);

    bool isExpanded() const { return expanded_; }

public slots:
    void setExpanded(bool on);
    void toggle() { setExpanded(!expanded_); }

private:
    // Per-source rolling rate data
    struct SrcStats {
        uint64_t lastPkts  = 0;
        double   lastTime  = 0.0;
        double   pktRate   = 0.0;   // packets/s EWA
        double   byteRate  = 0.0;   // bytes/s EWA
        std::deque<float> rateHist; // last 60 pkt/s samples for sparkline
    };
    std::vector<SrcStats> srcStats_;

    QWidget*      content_     = nullptr;
    QPushButton*  toggleBtn_   = nullptr;
    QLabel*       summaryLbl_  = nullptr;
    QTableWidget* table_       = nullptr;
    bool          expanded_    = false;
    int           lastSrcCount_= 0;

    void buildTable(int nSrc);
    void updateRows(const std::vector<std::shared_ptr<Source>>& sources);
};

// ── Inline sparkline painter ──────────────────────────────────────────

class SparkLine : public QWidget {
    Q_OBJECT
public:
    explicit SparkLine(QWidget* parent = nullptr);
    void setSamples(const std::deque<float>& hist, float peak);

protected:
    void paintEvent(QPaintEvent*) override;

private:
    std::vector<float> samples_;
    float peak_ = 1.0f;
};
