#include "timer.h"
#include "utils.h"
#include <math.h>

namespace esp32 {
namespace timer {

using namespace esp32::ui;
using namespace esp32::utils;

static float deg2rad(float d){ return d * 3.1415926f / 180.0f; }
static const int CHAR_W = 6;
static const int CHAR_H = 8;
static const uint16_t CYAN_COLOR = rgbTo565(0x00FFFF);

void init(ClockState& s){
    s.startMs = millis();
    s.elapsedMs = 0;
    s.lapCount = 0;
    s.running = true;
}

void reset(ClockState& s){
    s.startMs = millis();
    s.elapsedMs = 0;
    s.lapCount = 0;
    s.running = true;
}

void update(ClockState& s, uint32_t nowMs){
    if (s.running){
        s.elapsedMs = nowMs - s.startMs;
    }
}

void addLap(ClockState& s){
    if (s.lapCount >= ClockState::MAX_LAPS) return;
    // 记录当前秒针角度（0-60秒 -> 0-360度）
    uint32_t sec = (s.elapsedMs / 1000) % 60;
    float angleDeg = (sec / 60.0f) * 360.0f;
    s.lapAngles[s.lapCount] = angleDeg;
    s.lapMs[s.lapCount] = s.elapsedMs;
    s.lapCount++;
}

void buildScene(const ClockState& s, DisplayList& out,
                int16_t screenW, int16_t screenH){
    // 标题
    out.addText(6000, 4, 4, WHITE, "Timer");
    // 时间文本 mm:ss.cc (cc=厘秒)
    uint32_t totalCs = s.elapsedMs / 10;
    uint32_t totalSec = totalCs / 100;
    uint32_t mm = totalSec / 60;
    uint32_t ss = totalSec % 60;
    uint32_t cs = totalCs % 100;
    char buf[16];
    snprintf(buf, sizeof(buf), "%02lu:%02lu.%02lu", (unsigned long)mm, (unsigned long)ss, (unsigned long)cs);
    // 背景擦除该区域避免残影
    // out.addFillRect(5999, 0, 14, 72, 9, BLACK);
    out.addText(6001, 4, 14, YELLOW, buf);

    // 钟表圆心与半径
    int16_t radius = 54; // 缩小一点，右侧留空间展示 laps
    int16_t cx = screenW / 2 ; // 向左偏移为右侧列表腾位置
    int16_t cy = screenH / 2 + 5; // 稍微偏下

    // 外圈
    out.addCircle(6002, cx, cy, radius, WHITE);

    // 刻度 (12 个, 每 30°)，使用短线
    for (int i=0;i<12;++i){
        float ang = deg2rad(i * 30.0f - 90.0f); // 使 0 点在顶端
        int16_t x1 = cx + (int16_t)((radius - 8) * cosf(ang));
        int16_t y1 = cy + (int16_t)((radius - 8) * sinf(ang));
        int16_t x2 = cx + (int16_t)((radius - 2) * cosf(ang));
        int16_t y2 = cy + (int16_t)((radius - 2) * sinf(ang));
        out.addLine(6100 + i, x1, y1, x2, y2, WHITE);
    }

    // 时针、分针、秒针角度
    float totalMinutes = s.elapsedMs / 60000.0f;
    float hours = fmodf(totalMinutes / 60.0f, 12.0f);
    float minutes = fmodf(totalMinutes, 60.0f);
    float seconds = fmodf(s.elapsedMs / 1000.0f, 60.0f);

    float hourDeg = (hours / 12.0f) * 360.0f - 90.0f;
    float minuteDeg = (minutes / 60.0f) * 360.0f - 90.0f;
    float secondDeg = (seconds / 60.0f) * 360.0f - 90.0f;

    // 指针长度
    int16_t hourLen = (int16_t)(radius * 0.5f);
    int16_t minuteLen = (int16_t)(radius * 0.7f);
    int16_t secondLen = (int16_t)(radius * 0.85f);

    // 计算并添加指针
    auto addHand = [&](uint16_t key, float deg, int16_t len, uint16_t color){
        float rad = deg2rad(deg);
        int16_t x2 = cx + (int16_t)(len * cosf(rad));
        int16_t y2 = cy + (int16_t)(len * sinf(rad));
        out.addLine(key, cx, cy, x2, y2, color);
    };
    addHand(6200, hourDeg, hourLen, WHITE);
    addHand(6201, minuteDeg, minuteLen, GREEN);
    addHand(6202, secondDeg, secondLen, RED);

    // Laps：在圆周上标记记录点(用小线段或小圆点)
    for (uint16_t i=0;i<s.lapCount;++i){
        float lapDeg = s.lapAngles[i] - 90.0f;
        float rad = deg2rad(lapDeg);
        int16_t lx = cx + (int16_t)((radius - 4) * cosf(rad));
        int16_t ly = cy + (int16_t)((radius - 4) * sinf(rad));
        out.addCircle(6300 + i, lx, ly, 2, BLUE);
    }

    // Laps 列表（右侧显示最近记录）
    int16_t lapListX = screenW - 52;
    int16_t lapListY = 4;
    out.addText(6400, lapListX, lapListY, WHITE, "Laps");
    int visible = s.lapCount;
    if (visible > 6) visible = 6; // 最多显示 6 条
    // 显示最近的 visible 条（倒序）
    for (int i = 0; i < visible; ++i) {
        int idx = s.lapCount - 1 - i;
        uint32_t lapCs = s.lapMs[idx] / 10;
        uint32_t lapSec = lapCs / 100;
        uint32_t lmm = lapSec / 60;
        uint32_t lss = lapSec % 60;
        uint32_t lcs = lapCs % 100;
        char lapBuf[16];
        snprintf(lapBuf, sizeof(lapBuf), "%02lu:%02lu.%02lu", (unsigned long)lmm, (unsigned long)lss, (unsigned long)lcs);
    out.addText(6401 + i, lapListX, lapListY + (i + 1) * CHAR_H + 2, CYAN_COLOR, lapBuf);
    }

    // 底部操作提示
    out.addText(6450, 2, screenH - 12, WHITE, "Up: Lap  Right: Reset  Left: Home");
}

} // namespace timer
} // namespace esp32
