#include "display/ui/home/home_view.h"

#include "display/ui/components/primitives.h"
#include "display/ui/theme.h"

#include <cmath>
#include <cstring>

LV_FONT_DECLARE(lv_font_home_22)
LV_FONT_DECLARE(lv_font_home_44)

namespace hwdisplay::ui {
namespace {

using components::Box;
using components::Text;

constexpr float kPi = 3.14159265358979323846f;

}  // namespace

bool HomeView::Create(lv_obj_t* parent) {
    if (!parent) return false;
    const int sw = lv_obj_get_width(parent);
    const int sh = lv_obj_get_height(parent);
    if (sw != theme::kScreenWidth || sh != theme::kScreenHeight) return false;

    // Production page hides developer counters; the old camera/debug layout
    // still retains them when selected through display.mode=debug.
    lv_display_t* disp = lv_display_get_default();
    if (disp) {
        lv_sysmon_hide_performance(disp);
        lv_sysmon_hide_memory(disp);
    }

    root_ = Box(parent, 0, 0, sw, sh, theme::kCanvas);
    if (!root_) return false;
    if (!Box(root_, 527, -193, 345, 328, 0xDDF8F0, LV_RADIUS_CIRCLE) ||
        !Box(root_, -78, 405, 220, 220, 0xE9F6FF, LV_RADIUS_CIRCLE)) return false;

    // Neutral functional heading; no product brand on the child-facing screen.
    lv_obj_t* icon = Box(root_, 27, 21, 32, 32, 0x25A9B5, 11);
    if (!icon) return false;
    lv_obj_t* dot = Box(icon, 0, 0, 9, 9, theme::kWhite, LV_RADIUS_CIRCLE);
    lv_obj_t* title = Text(root_, 0, 0, "洗手引导", &lv_font_home_22, theme::kInk);
    if (!dot || !title) return false;
    lv_obj_align(dot, LV_ALIGN_CENTER, 0, 0);
    lv_obj_align_to(title, icon, LV_ALIGN_OUT_RIGHT_MID, 11, 1);
    if (!Box(root_, 644, 20, 133, 36, theme::kWhite, 18)) return false;
    status_ = Text(root_, 658, 26, "等待靠近", &lv_font_home_22, 0x537A81);
    if (!status_) return false;

    if (!Box(root_, 48, 123, 17, 3, 0x29B9A7, LV_RADIUS_CIRCLE) ||
        !Text(root_, 73, 109, "小手洗干净，开心每一天", &lv_font_home_22, 0x229D90))
        return false;
    if (!Text(root_, 48, 151, "洗洗小手", &lv_font_home_44, theme::kInk) ||
        !Text(root_, 48, 207, "一起开始吧", &lv_font_home_44, theme::kTeal) ||
        !Text(root_, 48, 291, "跟着画面，学会认真洗手", &lv_font_home_22, theme::kMuted))
        return false;

    if (!Box(root_, 48, 347, 366, 45, theme::kTealSoft, 17) ||
        !Box(root_, 56, 355, 29, 29, 0x1BA99D, 10) ||
        !Box(root_, 67, 366, 7, 7, theme::kWhite, LV_RADIUS_CIRCLE)) return false;
    cue_ = Text(root_, 94, 355, "把脸放进右边画面", &lv_font_home_22, 0x147F78);
    if (!cue_) return false;

    // 首页常显人脸取景，开始洗手后随首页销毁。视频帧只在显示线程置脏。
    if (!Box(root_, 458, 76, 304, 311, theme::kWhite, 24) ||
        !Box(root_, 470, 96, 8, 8, 0x25B89A, LV_RADIUS_CIRCLE) ||
        !Text(root_, 486, 87, "人脸摄像头", &lv_font_home_22, theme::kInk) ||
        !Box(root_, 470, 120, kFaceWidth, kFaceHeight, 0x315B69, 14)) return false;
    if (!external_face_buffer_) own_face_buffer_.assign(kFaceBytes, 0xFF);
    uint8_t* pixels = external_face_buffer_ ? external_face_buffer_ : own_face_buffer_.data();
    if (!pixels || (external_face_buffer_ && external_face_bytes_ < kFaceBytes)) return false;
    face_canvas_ = lv_canvas_create(root_);
    if (!face_canvas_) return false;
    lv_canvas_set_buffer(face_canvas_, pixels, kFaceWidth, kFaceHeight,
                         LV_COLOR_FORMAT_XRGB8888);
    lv_obj_set_pos(face_canvas_, 470, 120);
    lv_obj_add_flag(face_canvas_, LV_OBJ_FLAG_HIDDEN);
    face_hint_ = Text(root_, 522, 198, "画面准备中", &lv_font_home_22, theme::kWhite);
    if (!face_hint_) return false;

    for (size_t i = 0; i < guide_points_.size(); ++i) {
        const float angle = 2.f * kPi * static_cast<float>(i) /
                            static_cast<float>(guide_points_.size() - 1);
        guide_points_[i].x = static_cast<int32_t>(61.f + 61.f * std::cos(angle));
        guide_points_[i].y = static_cast<int32_t>(79.f + 77.f * std::sin(angle));
    }
    face_guide_ = lv_line_create(root_);
    if (!face_guide_) return false;
    lv_line_set_points(face_guide_, guide_points_.data(), guide_points_.size());
    lv_obj_set_pos(face_guide_, 549, 132);
    lv_obj_set_style_line_width(face_guide_, 2, 0);
    lv_obj_set_style_line_color(face_guide_, lv_color_hex(theme::kWhite), 0);
    lv_obj_set_style_line_opa(face_guide_, LV_OPA_80, 0);

    face_result_box_ = Box(root_, 470, 316, 280, 62, 0xE8F5F1, 14);
    if (!face_result_box_ || !Box(root_, 480, 330, 33, 33, 0xCCE9E1, 11)) return false;
    face_result_icon_ = Text(root_, 487, 332, "○", &lv_font_home_22, theme::kTeal);
    face_result_main_ = Text(root_, 522, 318, "请把脸放进框内", &lv_font_home_22, theme::kInk);
    face_result_detail_ = Text(root_, 522, 346, "画面里要看到整张脸", &lv_font_home_22, theme::kMuted);
    if (!face_result_icon_ || !face_result_main_ || !face_result_detail_ ||
        !steps_.Create(root_, 38, 404, 724, 56)) return false;
    return true;
}

void HomeView::Render(const HomeModel& model) {
    if (!root_ || !status_ || !cue_) return;
    std::string personalized;
    const char* main = "请把脸放进框内";
    const char* detail = "画面里要看到整张脸";
    const char* icon = "○";
    uint32_t card_color = 0xE8F5F1;
    uint32_t guide_color = theme::kWhite;
    switch (model.presence) {
        case HomePresence::Waiting:
            lv_label_set_text(status_, "等待靠近");
            lv_label_set_text(cue_, "把脸放进右边画面");
            break;
        case HomePresence::FaceVisible:
            lv_label_set_text(status_, "已看到你");
            lv_label_set_text(cue_, "看到脸了，保持一下");
            main = "看到脸了，保持一下";
            detail = "请看向镜头";
            icon = "✓";
            card_color = 0xDDF8E9;
            guide_color = 0x76EFC1;
            break;
        case HomePresence::KnownFace:
            lv_label_set_text(status_, "欢迎回来");
            lv_label_set_text(cue_, (model.nickname + "，准备开始洗手").c_str());
            personalized = "认出" + model.nickname + "了";
            main = personalized.c_str();
            detail = "马上开始洗手";
            icon = "✓";
            card_color = 0xDDF8E9;
            guide_color = 0x76EFC1;
            break;
        case HomePresence::MultiFace:
            lv_label_set_text(status_, "请排好队");
            lv_label_set_text(cue_, "一次一位小朋友哦");
            main = "一次一位小朋友";
            detail = "请其他伙伴稍等";
            icon = "2";
            card_color = 0xFFF1D4;
            break;
        case HomePresence::HandsVisible:
            lv_label_set_text(status_, "已看到小手");
            lv_label_set_text(cue_, "小手已到位，准备开始");
            break;
        case HomePresence::CameraOffline:
            lv_label_set_text(status_, "相机异常");
            lv_label_set_text(cue_, "请老师检查摄像头");
            main = "画面暂时不可用";
            detail = "请老师检查摄像头";
            icon = "!";
            card_color = 0xEDF2F0;
            break;
    }
    lv_label_set_text(face_result_main_, main);
    lv_label_set_text(face_result_detail_, detail);
    lv_label_set_text(face_result_icon_, icon);
    lv_obj_set_style_bg_color(face_result_box_, lv_color_hex(card_color), 0);
    lv_obj_set_style_line_color(face_guide_, lv_color_hex(guide_color), 0);
    if (model.presence == HomePresence::CameraOffline) {
        lv_obj_add_flag(face_canvas_, LV_OBJ_FLAG_HIDDEN);
        lv_label_set_text(face_hint_, "画面暂时不可用");
        lv_obj_remove_flag(face_hint_, LV_OBJ_FLAG_HIDDEN);
    }
}

void HomeView::SetFaceFrameBuffer(uint8_t* pixels, size_t bytes) {
    if (root_) return;
    external_face_buffer_ = pixels;
    external_face_bytes_ = bytes;
}

void HomeView::ShowFaceFrame(const uint8_t* bgra, size_t bytes) {
    if (!face_canvas_ || !bgra || bytes < kFaceBytes) return;
    uint8_t* pixels = external_face_buffer_ ? external_face_buffer_ : own_face_buffer_.data();
    if (bgra != pixels) std::memcpy(pixels, bgra, kFaceBytes);
    lv_obj_remove_flag(face_canvas_, LV_OBJ_FLAG_HIDDEN);
    lv_obj_add_flag(face_hint_, LV_OBJ_FLAG_HIDDEN);
    lv_obj_invalidate(face_canvas_);
}

void HomeView::Destroy() {
    if (root_) lv_obj_delete(root_);
    root_ = nullptr;
    status_ = nullptr;
    cue_ = nullptr;
    face_canvas_ = nullptr;
    face_hint_ = nullptr;
    face_guide_ = nullptr;
    face_result_box_ = nullptr;
    face_result_icon_ = nullptr;
    face_result_main_ = nullptr;
    face_result_detail_ = nullptr;
    own_face_buffer_.clear();
}

}  // namespace hwdisplay::ui
