// 叠加层实现 — 手部框/骨架/关节 + 状态区
#include "display/overlay.h"

#include "common/log.h"
#include "common/time_utils.h"

#include <cstdio>

// 自制中文子集字库(只含界面用字; 生成命令见 src/display/lv_font_ui_16.c 头部注释)
LV_FONT_DECLARE(lv_font_ui_16)

namespace hwdisplay {
namespace {

// MediaPipe 手部 21 点 → 5 条手指链(腕 → 指尖), 画骨架用
const int kChains[5][5] = {
    {0, 1, 2, 3, 4},        // 拇指
    {0, 5, 6, 7, 8},        // 食指
    {0, 9, 10, 11, 12},     // 中指
    {0, 13, 14, 15, 16},    // 无名指
    {0, 17, 18, 19, 20},    // 小指
};

const uint32_t kColorBox  = 0x22CC22;   // 检测框(绿)
const uint32_t kColorSkel = 0xFF9900;   // 骨架(橙)
const uint32_t kColorDot  = 0xFFFFFF;   // 关节点(白)
const uint32_t kColorFace = 0x3388FF;   // 人脸框(蓝)

inline void Hide(lv_obj_t* o, bool hide) {
    if (!o) return;   // LVGL 内存不足时对象可能为 NULL(不要喂给 LVGL API, 会触发 assert 死循环)
    if (hide) lv_obj_add_flag(o, LV_OBJ_FLAG_HIDDEN);
    else      lv_obj_remove_flag(o, LV_OBJ_FLAG_HIDDEN);
}

}  // namespace

// ---------------- HandOverlay ----------------
bool HandOverlay::Init(lv_obj_t* parent, const VideoPane* pane) {
    if (!parent) {
        HW_ERR("overlay: 父对象为空, 叠加层未创建");
        return false;
    }
    pane_ = pane;
    LogLvMem("叠加前");
    int created = 0, failed = 0;
    for (int i = 0; i < kMaxHands; ++i) {
        HandObjs& ho = h_[i];

        ho.box = lv_line_create(parent);
        if (!ho.box) {
            failed++;
        } else {
            created++;
            lv_obj_set_style_line_width(ho.box, 2, 0);
            lv_obj_set_style_line_color(ho.box, lv_color_hex(kColorBox), 0);
            lv_obj_set_style_line_rounded(ho.box, true, 0);
        }

        for (int c = 0; c < 5; ++c) {
            ho.skel[c] = lv_line_create(parent);
            if (!ho.skel[c]) { failed++; continue; }
            created++;
            lv_obj_set_style_line_width(ho.skel[c], 2, 0);
            lv_obj_set_style_line_color(ho.skel[c], lv_color_hex(kColorSkel), 0);
            lv_obj_set_style_line_rounded(ho.skel[c], true, 0);
        }
        for (int k = 0; k < 21; ++k) {
            lv_obj_t* d = lv_obj_create(parent);
            if (!d) { failed++; continue; }
            created++;
            lv_obj_remove_flag(d, LV_OBJ_FLAG_SCROLLABLE);
            lv_obj_set_size(d, 6, 6);
            lv_obj_set_style_radius(d, LV_RADIUS_CIRCLE, 0);
            lv_obj_set_style_bg_color(d, lv_color_hex(kColorDot), 0);
            lv_obj_set_style_border_width(d, 1, 0);
            lv_obj_set_style_border_color(d, lv_color_hex(0x101010), 0);
            lv_obj_set_style_pad_all(d, 0, 0);
            ho.dot[k] = d;
        }
        ho.label = lv_label_create(parent);
        if (!ho.label) { failed++; }
        else {
            created++;
            lv_obj_set_style_text_color(ho.label, lv_color_white(), 0);
            lv_obj_set_style_bg_color(ho.label, lv_color_hex(0x000000), 0);
            lv_obj_set_style_bg_opa(ho.label, LV_OPA_60, 0);
            lv_obj_set_style_pad_all(ho.label, 2, 0);
        }
        HideAll();
    }
    LogLvMem("叠加后");
    if (failed) HW_WARN("overlay: %d 个对象创建失败(成功 %d)", failed, created);
    HW_LOG("overlay: 手部叠加层就绪(最多 %d 只手)", kMaxHands);
    return true;
}

void HandOverlay::HideAll() {
    for (int i = 0; i < kMaxHands; ++i) {
        HandObjs& ho = h_[i];
        Hide(ho.box, true);
        for (int c = 0; c < 5; ++c) Hide(ho.skel[c], true);
        for (int k = 0; k < 21; ++k) Hide(ho.dot[k], true);
        Hide(ho.label, true);
    }
}

void HandOverlay::Update(const handwash::OverlayData& d) {
    if (!pane_) return;
    const int n = (int)d.hands.size();

    for (int i = 0; i < kMaxHands; ++i) {
        HandObjs& ho   = h_[i];
        const bool has = i < n;
        Hide(ho.box, !has);
        Hide(ho.label, !has);
        if (!has) {
            for (int c = 0; c < 5; ++c) Hide(ho.skel[c], true);
            for (int k = 0; k < 21; ++k) Hide(ho.dot[k], true);
            continue;
        }

        const auto& hand = d.hands[i];

        // 1) 检测框(四角 + 闭合)
        const float bx[4] = {hand.box.x1, hand.box.x2, hand.box.x2, hand.box.x1};
        const float by[4] = {hand.box.y1, hand.box.y1, hand.box.y2, hand.box.y2};
        float lx[5], ly[5];
        for (int c = 0; c < 4; ++c) pane_->MapPoint(bx[c], by[c], &lx[c], &ly[c]);
        lx[4] = lx[0];
        ly[4] = ly[0];
        for (int c = 0; c < 5; ++c) {
            ho.box_pts[c].x = lx[c];
            ho.box_pts[c].y = ly[c];
        }
        lv_line_set_points(ho.box, ho.box_pts, 5);

        // 2) 骨架 + 关节点
        const bool draw_lm = hand.has_lm && hand.lm_valid;
        for (int c = 0; c < 5; ++c) {
            Hide(ho.skel[c], !draw_lm);
            if (!draw_lm) continue;
            for (int k = 0; k < 5; ++k) {
                const int idx = kChains[c][k];
                float px = 0, py = 0;
                pane_->MapPoint(hand.lm.pts[idx][0], hand.lm.pts[idx][1], &px, &py);
                ho.skel_pts[c][k].x = px;
                ho.skel_pts[c][k].y = py;
            }
            lv_line_set_points(ho.skel[c], ho.skel_pts[c], 5);
        }
        for (int k = 0; k < 21; ++k) {
            Hide(ho.dot[k], !draw_lm);
            if (!draw_lm) continue;
            float px = 0, py = 0;
            pane_->MapPoint(hand.lm.pts[k][0], hand.lm.pts[k][1], &px, &py);
            lv_obj_set_pos(ho.dot[k], (lv_coord_t)px - 3, (lv_coord_t)py - 3);
        }

        // 3) 标签(左右手 + 分数)
        char txt[48];
        snprintf(txt, sizeof(txt), "%s%s %.2f", hand.side ? hand.side : "",
                 (hand.side && hand.side[0]) ? "" : "hand", hand.score);
        lv_label_set_text(ho.label, txt);
        lv_obj_set_pos(ho.label, (lv_coord_t)lx[0], (lv_coord_t)(ly[0] > 20 ? ly[0] - 20 : 0));
    }
}

// ---------------- FaceOverlay ----------------
bool FaceOverlay::Init(lv_obj_t* parent, const VideoPane* pane) {
    if (!parent) {
        HW_ERR("overlay: 人脸层父对象为空, 未创建");
        return false;
    }
    pane_ = pane;
    int failed = 0;
    for (int i = 0; i < kMaxFaces; ++i) {
        FaceObjs& fo = f_[i];
        fo.box       = lv_line_create(parent);
        if (!fo.box) {
            failed++;
        } else {
            lv_obj_set_style_line_width(fo.box, 2, 0);
            lv_obj_set_style_line_color(fo.box, lv_color_hex(kColorFace), 0);
            lv_obj_set_style_line_rounded(fo.box, true, 0);
        }
        fo.label = lv_label_create(parent);
        if (!fo.label) {
            failed++;
        } else {
            lv_obj_set_style_text_color(fo.label, lv_color_white(), 0);
            lv_obj_set_style_bg_color(fo.label, lv_color_hex(0x0A2A4A), 0);
            lv_obj_set_style_bg_opa(fo.label, LV_OPA_70, 0);
            lv_obj_set_style_pad_all(fo.label, 2, 0);
        }
    }
    HideAll();
    if (failed) HW_WARN("overlay: 人脸层 %d 个对象创建失败", failed);
    HW_LOG("overlay: 人脸叠加层就绪(最多 %d 张)", kMaxFaces);
    return true;
}

void FaceOverlay::HideAll() {
    for (int i = 0; i < kMaxFaces; ++i) {
        Hide(f_[i].box, true);
        Hide(f_[i].label, true);
    }
}

void FaceOverlay::Update(const handwash::OverlayData& d) {
    if (!pane_) return;
    const int n = (int)d.faces.size();
    for (int i = 0; i < kMaxFaces; ++i) {
        FaceObjs&  fo  = f_[i];
        const bool has = i < n;
        Hide(fo.box, !has);
        Hide(fo.label, !has);
        if (!has || !fo.box) continue;

        const auto& face = d.faces[i];
        const float xs[4] = {face.x1, face.x2, face.x2, face.x1};
        const float ys[4] = {face.y1, face.y1, face.y2, face.y2};
        float lx[5], ly[5];
        for (int c = 0; c < 4; ++c) pane_->MapPoint(xs[c], ys[c], &lx[c], &ly[c]);
        lx[4] = lx[0];
        ly[4] = ly[0];
        for (int c = 0; c < 5; ++c) {
            fo.box_pts[c].x = lx[c];
            fo.box_pts[c].y = ly[c];
        }
        lv_line_set_points(fo.box, fo.box_pts, 5);

        if (fo.label) {
            char txt[64];
            if (!face.name.empty())
                snprintf(txt, sizeof(txt), "%s %.2f", face.name.c_str(), face.score);
            else if (face.track_id >= 0)
                snprintf(txt, sizeof(txt), "ID %d  %.2f", face.track_id, face.score);
            else
                snprintf(txt, sizeof(txt), "face %.2f", face.score);
            lv_label_set_text(fo.label, txt);
            lv_obj_set_pos(fo.label, (lv_coord_t)lx[0], (lv_coord_t)(ly[0] > 20 ? ly[0] - 20 : 0));
        }
    }
}

// ---------------- StatusPanel ----------------
bool StatusPanel::Init(lv_obj_t* parent, int x, int y, int w, int h) {
    panel_ = lv_obj_create(parent);
    lv_obj_remove_flag(panel_, LV_OBJ_FLAG_SCROLLABLE);
    lv_obj_set_pos(panel_, x, y);
    lv_obj_set_size(panel_, w, h);
    lv_obj_set_style_bg_color(panel_, lv_color_hex(0x181C22), 0);
    lv_obj_set_style_border_color(panel_, lv_color_hex(0x2A3038), 0);
    lv_obj_set_style_border_width(panel_, 1, 0);
    lv_obj_set_style_radius(panel_, 6, 0);
    lv_obj_set_style_pad_all(panel_, 8, 0);

    static const lv_font_t* kCjk = &lv_font_ui_16;

    l1_ = lv_label_create(panel_);
    lv_obj_set_style_text_color(l1_, lv_color_hex(0xE8F0FF), 0);
    lv_obj_set_style_text_font(l1_, kCjk, 0);
    lv_obj_set_pos(l1_, 0, 0);

    l2_ = lv_label_create(panel_);
    lv_obj_set_style_text_color(l2_, lv_color_hex(0xA8B6C8), 0);
    lv_obj_set_style_text_font(l2_, kCjk, 0);
    lv_obj_set_pos(l2_, 0, 24);

    l3_ = lv_label_create(panel_);
    lv_obj_set_style_text_color(l3_, lv_color_hex(0x7A8899), 0);
    lv_obj_set_style_text_font(l3_, kCjk, 0);
    lv_obj_set_pos(l3_, 0, 48);

    SetLines("等待动作...", "请按七步洗手法洗手", "");
    return true;
}

void StatusPanel::SetLines(const char* l1, const char* l2, const char* l3) {
    if (l1_ && l1) lv_label_set_text(l1_, l1);
    if (l2_ && l2) lv_label_set_text(l2_, l2);
    if (l3_) lv_label_set_text(l3_, l3 ? l3 : "");
}

void StatusPanel::Update(const handwash::StatusData& s) {
    char l1[96];
    if (s.step >= 1 && s.step <= 7) {
        snprintf(l1, sizeof(l1), "当前动作: 第 %d 步   置信度 %.2f", s.step, s.conf);
    } else {
        snprintf(l1, sizeof(l1), "等待动作...(已识别 %d 个窗口)", s.windows);
    }

    char l2[160];
    if (s.last_steps > 0) {
        char who[64] = "";
        if (s.last_aligned && !s.last_name.empty())
            snprintf(who, sizeof(who), "  身份: %s", s.last_name.c_str());
        snprintf(l2, sizeof(l2), "最近一次洗手: 识别到 %d 个动作%s", s.last_steps, who);
    } else {
        snprintf(l2, sizeof(l2), "动作序列识别中(每 32 帧一个窗口, 步长 8)");
    }

    char l3[96];
    snprintf(l3, sizeof(l3), "STGCN 窗口累计: %d   当前人脸: %d", s.windows, s.faces_now);
    SetLines(l1, l2, l3);
}

}  // namespace hwdisplay
