#include <string.h>

#include "bsp/display.h"
#include "bsp/esp32_s3_touch_amoled_1_75c.h"
#include "bsp/touch.h"
#include "driver/gpio.h"
#include "driver/i2c_master.h"
#include "esp_err.h"
#include "esp_heap_caps.h"
#include "esp_lcd_panel_ops.h"
#include "esp_lcd_touch.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#include "clock.h"
#include "hud.h"

static const char *TAG = "wood_clock";
static const gpio_num_t k_boot = GPIO_NUM_0;
static const int64_t k_frame_us = 16667;
static const int k_strip = HUD_W * HUD_TILE;

static uint16_t s_dummy;
static int s_dummy_x;
static int s_dummy_y;

#define AXP_ADDR 0x34
#define AXP_INTEN2 0x41
#define AXP_INTSTS2 0x49
#define AXP_PKEY_SHORT (1u << 3)

static i2c_master_dev_handle_t s_axp;
static volatile int s_touch_irq;
static int s_show_dirty;
static hud_tiles_t s_hl_prev;

static void send_rect(esp_lcd_panel_handle_t panel, const uint8_t *rgb,
                      uint16_t *scratch[2], int *s, int x0, int y0, int x1, int y1)
{
    hud_pack_rect(rgb, scratch[*s], x0, y0, x1, y1);
    ESP_ERROR_CHECK(esp_lcd_panel_draw_bitmap(panel, x0, y0, x1, y1, scratch[*s]));
    s_dummy = scratch[*s][0];
    s_dummy_x = x0;
    s_dummy_y = y0;
    *s ^= 1;
}

static void send_rect_inv(esp_lcd_panel_handle_t panel, const uint8_t *rgb,
                          uint16_t *scratch[2], int *s, int x0, int y0, int x1, int y1)
{
    hud_pack_rect_inv(rgb, scratch[*s], x0, y0, x1, y1);
    ESP_ERROR_CHECK(esp_lcd_panel_draw_bitmap(panel, x0, y0, x1, y1, scratch[*s]));
    s_dummy = scratch[*s][0];
    s_dummy_x = x0;
    s_dummy_y = y0;
    *s ^= 1;
}

static void send_dummy(esp_lcd_panel_handle_t panel)
{
    ESP_ERROR_CHECK(esp_lcd_panel_draw_bitmap(panel, s_dummy_x, s_dummy_y,
                                              s_dummy_x + 1, s_dummy_y + 1, &s_dummy));
}

static void blit_full(esp_lcd_panel_handle_t panel, const uint8_t *rgb,
                      uint16_t *scratch[2], int *s)
{
    for (int y = 0; y < HUD_H; y += HUD_TILE) {
        int y2 = y + HUD_TILE;
        if (y2 > HUD_H) {
            y2 = HUD_H;
        }
        send_rect(panel, rgb, scratch, s, 0, y, HUD_W, y2);
    }
}

static void blit_full_inv(esp_lcd_panel_handle_t panel, const uint8_t *rgb,
                          uint16_t *scratch[2], int *s)
{
    for (int y = 0; y < HUD_H; y += HUD_TILE) {
        int y2 = y + HUD_TILE;
        if (y2 > HUD_H) {
            y2 = HUD_H;
        }
        send_rect_inv(panel, rgb, scratch, s, 0, y, HUD_W, y2);
    }
}

static int blit_tiles(esp_lcd_panel_handle_t panel, uint8_t *rgb,
                      const uint8_t *bg, const hud_tiles_t dirty,
                      uint16_t *scratch[2], int *s)
{
    int prev_tx = -1;
    int prev_ty = -1;
    int n = 0;
    for (int ty = 0; ty < HUD_TY; ty++) {
        uint32_t bits = dirty[ty];
        while (bits) {
            int tx = __builtin_ctz(bits);
            bits &= bits - 1u;
            int x0, y0, x1, y1;
            hud_tile_rect(tx, ty, &x0, &y0, &x1, &y1);
            send_rect(panel, rgb, scratch, s, x0, y0, x1, y1);
            if (prev_tx >= 0 && bg) {
                hud_restore_tile(rgb, bg, prev_tx, prev_ty);
            }
            prev_tx = tx;
            prev_ty = ty;
            n++;
        }
    }
    send_dummy(panel);
    if (prev_tx >= 0 && bg) {
        hud_restore_tile(rgb, bg, prev_tx, prev_ty);
    }
    return n;
}

static int blit_tiles_hl(esp_lcd_panel_handle_t panel, uint8_t *rgb,
                         const uint8_t *bg, const hud_tiles_t dirty,
                         uint16_t *scratch[2], int *s)
{
    hud_tiles_t send;
    hud_tiles_or(send, dirty, s_hl_prev);
    int prev_tx = -1;
    int prev_ty = -1;
    int n = 0;
    for (int ty = 0; ty < HUD_TY; ty++) {
        uint32_t bits = send[ty];
        uint32_t inv_bits = dirty[ty];
        while (bits) {
            int tx = __builtin_ctz(bits);
            bits &= bits - 1u;
            int x0, y0, x1, y1;
            hud_tile_rect(tx, ty, &x0, &y0, &x1, &y1);
            if ((inv_bits >> tx) & 1) {
                send_rect_inv(panel, rgb, scratch, s, x0, y0, x1, y1);
            } else {
                send_rect(panel, rgb, scratch, s, x0, y0, x1, y1);
            }
            if (prev_tx >= 0 && bg) {
                hud_restore_tile(rgb, bg, prev_tx, prev_ty);
            }
            prev_tx = tx;
            prev_ty = ty;
            n++;
        }
    }
    send_dummy(panel);
    if (prev_tx >= 0 && bg) {
        hud_restore_tile(rgb, bg, prev_tx, prev_ty);
    }
    memcpy(s_hl_prev, dirty, sizeof s_hl_prev);
    return n;
}

static void boot_button_init(void)
{
    gpio_config_t io = {
        .pin_bit_mask = 1ULL << k_boot,
        .mode = GPIO_MODE_INPUT,
        .pull_up_en = GPIO_PULLUP_ENABLE,
        .pull_down_en = GPIO_PULLDOWN_DISABLE,
        .intr_type = GPIO_INTR_DISABLE,
    };
    ESP_ERROR_CHECK(gpio_config(&io));
}

static int axp_read(uint8_t reg, uint8_t *v)
{
    if (!s_axp) {
        return -1;
    }
    return i2c_master_transmit_receive(s_axp, &reg, 1, v, 1, 50) == ESP_OK ? 0 : -1;
}

static int axp_write(uint8_t reg, uint8_t v)
{
    if (!s_axp) {
        return -1;
    }
    uint8_t buf[2] = { reg, v };
    return i2c_master_transmit(s_axp, buf, 2, 50) == ESP_OK ? 0 : -1;
}

static void pwr_button_init(void)
{
    if (bsp_i2c_init() != ESP_OK) {
        ESP_LOGW(TAG, "i2c init failed; PWR unused");
        return;
    }
    i2c_device_config_t cfg = {
        .dev_addr_length = I2C_ADDR_BIT_LEN_7,
        .device_address = AXP_ADDR,
        .scl_speed_hz = 400000,
    };
    if (i2c_master_bus_add_device(bsp_i2c_get_handle(), &cfg, &s_axp) != ESP_OK) {
        ESP_LOGW(TAG, "axp2101 missing; PWR unused");
        s_axp = nullptr;
        return;
    }
    uint8_t en2 = 0;
    if (axp_read(AXP_INTEN2, &en2) != 0) {
        ESP_LOGW(TAG, "axp2101 read failed; PWR unused");
        s_axp = nullptr;
        return;
    }
    (void)axp_write(AXP_INTEN2, (uint8_t)(en2 | AXP_PKEY_SHORT));
    (void)axp_write(AXP_INTSTS2, 0xFF);
    ESP_LOGI(TAG, "PWR short-press cycles faces");
}

static void touch_isr(esp_lcd_touch_handle_t tp)
{
    (void)tp;
    s_touch_irq = 1;
}

/* Same press-edge path as usage-hud: INT or IRQ, fire on finger-down. */
static int tap_pressed(esp_lcd_touch_handle_t tp, int *held)
{
    int irq = s_touch_irq;
    s_touch_irq = 0;
    int int_low = gpio_get_level(BSP_LCD_TOUCH_INT) == 0;
    if (!irq && !int_low && !*held) {
        return 0;
    }
    if (esp_lcd_touch_read_data(tp) != ESP_OK) {
        *held = 0;
        return 0;
    }
    esp_lcd_touch_point_data_t pts[1] = {};
    uint8_t n = 0;
    if (esp_lcd_touch_get_data(tp, pts, &n, 1) == ESP_OK && n > 0) {
        int fresh = !*held;
        *held = 1;
        return fresh;
    }
    *held = 0;
    return 0;
}

static int pwr_clicked(void)
{
    uint8_t st = 0;
    if (axp_read(AXP_INTSTS2, &st) != 0) {
        return 0;
    }
    if ((st & AXP_PKEY_SHORT) == 0) {
        return 0;
    }
    (void)axp_write(AXP_INTSTS2, AXP_PKEY_SHORT);
    return 1;
}

extern "C" void app_main(void)
{
    const bsp_display_config_t cfg = {
        .max_transfer_sz = HUD_W * HUD_TILE * BSP_LCD_BITS_PER_PIXEL / 8,
    };
    esp_lcd_panel_handle_t panel = nullptr;
    esp_lcd_panel_io_handle_t io = nullptr;
    ESP_ERROR_CHECK(bsp_display_new(&cfg, &panel, &io));
    ESP_ERROR_CHECK(bsp_display_backlight_on());
    (void)bsp_display_brightness_set(70);
    boot_button_init();
    pwr_button_init();

    bsp_display_cfg_t touch_cfg = {};
    touch_cfg.touch_flags.swap_xy = 0;
    touch_cfg.touch_flags.mirror_x = 1;
    touch_cfg.touch_flags.mirror_y = 1;
    esp_lcd_touch_handle_t tp = nullptr;
    ESP_ERROR_CHECK(bsp_touch_new(&touch_cfg, &tp));
    gpio_set_pull_mode(BSP_LCD_TOUCH_INT, GPIO_PULLUP_ONLY);
    ESP_ERROR_CHECK(esp_lcd_touch_register_interrupt_callback(tp, touch_isr));
    vTaskDelay(pdMS_TO_TICKS(50));

    if (clock_init() != 0) {
        ESP_LOGW(TAG, "face cache alloc failed; drawing face each frame");
    }
    uint8_t *rgb = (uint8_t *)heap_caps_malloc((size_t)HUD_W * HUD_H * 3,
                                               MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
    uint16_t *scratch[2];
    scratch[0] = (uint16_t *)heap_caps_malloc((size_t)k_strip * 2,
                                              MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
    scratch[1] = (uint16_t *)heap_caps_malloc((size_t)k_strip * 2,
                                              MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
    if (!scratch[0]) {
        scratch[0] = (uint16_t *)heap_caps_malloc((size_t)k_strip * 2,
                                                  MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
    }
    if (!scratch[1]) {
        scratch[1] = (uint16_t *)heap_caps_malloc((size_t)k_strip * 2,
                                                  MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
    }
    if (!rgb || !scratch[0] || !scratch[1]) {
        ESP_LOGE(TAG, "framebuffer alloc failed");
        return;
    }
    ESP_LOGI(TAG, "clock %dx%d  tiles %dx%d  face %s  single-buffer tiles",
             HUD_W, HUD_H, HUD_TX, HUD_TY, clock_face_name());

    int prev_boot = 1;
    int was_hl = 0;
    int touch_held = 0;
    int s = 0;
    uint32_t frame = 0;
    int64_t fps_t0 = esp_timer_get_time();
    while (true) {
        int64_t t0 = esp_timer_get_time();
        int boot_down = gpio_get_level(k_boot) == 0;
        if (boot_down && !prev_boot) {
            s_show_dirty ^= 1;
            ESP_LOGI(TAG, "dirty highlight %s", s_show_dirty ? "on" : "off");
        }
        if (pwr_clicked() || tap_pressed(tp, &touch_held)) {
            clock_next_face();
            ESP_LOGI(TAG, "face %d %s", clock_face_index(), clock_face_name());
        }
        prev_boot = boot_down;

        hud_tiles_t dirty;
        int full = 0;
        clock_frame(rgb, dirty, &full);
        int nsent = 0;
        const uint8_t *bg = clock_background();
        if (full) {
            if (s_show_dirty) {
                blit_full_inv(panel, rgb, scratch, &s);
                hud_tiles_all(s_hl_prev);
            } else {
                blit_full(panel, rgb, scratch, &s);
                if (was_hl) {
                    memset(s_hl_prev, 0, sizeof s_hl_prev);
                }
            }
            send_dummy(panel);
            if (bg) {
                memcpy(rgb, bg, (size_t)HUD_W * HUD_H * 3);
            }
            nsent = HUD_TY;
        } else if (s_show_dirty) {
            nsent = blit_tiles_hl(panel, rgb, bg, dirty, scratch, &s);
        } else if (was_hl) {
            hud_tiles_t send;
            hud_tiles_or(send, dirty, s_hl_prev);
            nsent = blit_tiles(panel, rgb, bg, send, scratch, &s);
            memset(s_hl_prev, 0, sizeof s_hl_prev);
        } else {
            nsent = blit_tiles(panel, rgb, bg, dirty, scratch, &s);
        }
        was_hl = s_show_dirty;

        if ((frame % 120) == 0 && frame > 0) {
            int64_t now = esp_timer_get_time();
            int fps = (int)(120 * 1000000LL / (now - fps_t0));
            fps_t0 = now;
            ESP_LOGI(TAG, "face %s fps=%d tiles=%d sent=%d frame=%d us",
                     clock_face_name(), fps, hud_tiles_count(dirty), nsent,
                     (int)(now - t0));
        }
        frame++;

        int64_t used = esp_timer_get_time() - t0;
        if (used < k_frame_us) {
            int64_t target = t0 + k_frame_us;
            while (esp_timer_get_time() < target) {
                if (target - esp_timer_get_time() > 12000) {
                    vTaskDelay(1);
                }
            }
        }
    }
}
