#pragma once
// VideoPane — 一路视频窗: dma-buf 画布(XRGB8888) + LVGL canvas 对象
//
// 线程约定:
//   Push()      —— 采集线程调用: RGA 把相机 NV12 帧缩放/转换进画布, 只置脏标志, 不碰 LVGL
//   其它方法     —— 显示线程(LVGL 唯一调用者)
// 说明:
//   - 画布缓冲来自 dma-heap(RV1106 RGA 只认 dma-buf fd), LVGL 直接读同一块内存, 零拷贝;
//   - 单缓冲写读可能偶发撕裂(写入 ~1.5ms 与 LVGL flush 重叠), P0 接受; 后续可改双缓冲。
#include <atomic>
#include <cstdint>
#include <string>

#include "camera/frame_types.h"
#include "common/dma_buffer.h"
#include "rga/rga_utils.h"

#include "display/display_host.h"
#include "lvgl.h"

namespace hwdisplay {

class VideoPane {
public:
    struct Stats {
        uint64_t frames_in    = 0;   // 到达本窗的帧(未节流前)
        uint64_t pushed       = 0;   // 实际完成 RGA 更新的帧
        uint64_t errors       = 0;   // RGA 失败次数
        double   rga_ms_avg   = 0;   // RGA 平均耗时(ms, 指数平滑)
    };

    VideoPane() = default;
    ~VideoPane();

    // 创建 LVGL canvas 并分配画布(必须在显示线程调用)
    bool Init(lv_obj_t* parent, std::string tag, int x, int y, int w, int h, RgaFit fit);

    // 水平镜像显示(相机视角与人的直觉左右相反时使用; 需额外一块中转缓冲)
    void SetMirror(bool on);

    // 采集线程: 相机帧 → 画布(零拷贝); 失败返回 false
    bool Push(const CameraFrame& f);

    // 显示线程: 有新帧则返回 true 并清除脏标志
    bool TakeDirty() { return dirty_.exchange(false, std::memory_order_acq_rel); }

    // 相机像素坐标 → 画布本地坐标(已考虑 letterbox/crop 与镜像); 供叠加层使用
    // (需已收到至少一帧, 否则按输入尺寸原样返回)
    void MapPoint(float cx, float cy, float* out_x, float* out_y) const;

    lv_obj_t*        obj() const { return canvas_; }
    const std::string& tag() const { return tag_; }
    const Stats&     stats() const { return stats_; }
    // 画布缓冲(供快照 dump; 只在 Push 之后读安全)
    const DmaBuffer& buffer() const { return buf_; }
    bool mirror() const { return mirror_; }
    int  width() const { return (int)dst_.width; }
    int  height() const { return (int)dst_.height; }
    RgaFit fit() const { return fit_; }
    int  src_width() const { return src_w_.load(); }
    int  src_height() const { return src_h_.load(); }

private:
    std::string tag_;
    DmaBuffer   buf_;
    DmaBuffer   tmp_;          // 镜像时的中转缓冲(先 blit 到这里, 再翻转拷贝到画布)
    RgaImage    dst_;
    lv_obj_t*   canvas_ = nullptr;
    RgaFit      fit_    = RgaFit::Letterbox;
    bool        mirror_ = false;
    std::atomic<int>  src_w_{0};   // 最近一帧的相机尺寸(映射用)
    std::atomic<int>  src_h_{0};
    std::atomic<bool> dirty_{false};
    Stats       stats_{};
};

}  // namespace hwdisplay
