
#include <stdio.h>
#include <freertos/FreeRTOS.h>
#include <esp_timer.h>
#include <esp_log.h>

#include "display_bsp.h"
#include "lvgl_bsp.h"
#include "esp_wifi_bsp.h"
#include "user_app.h"

static const char *TAG = "main";

DisplayPort RlcdPort(12, 11, 5, 40, 41, 400, 300);

static void Lvgl_FlushCallback(lv_disp_drv_t *drv, const lv_area_t *area, lv_color_t *color_map)
{
    uint16_t *buffer = (uint16_t *)color_map;
    for (int y = area->y1; y <= area->y2; y++) {
        for (int x = area->x1; x <= area->x2; x++) {
            uint8_t color = (*buffer < 0x7fff) ? ColorBlack : ColorWhite;
            RlcdPort.RLCD_SetPixel(x, y, color);
            buffer++;
        }
    }
    RlcdPort.RLCD_Display();
    lv_disp_flush_ready(drv);
}

extern "C" void app_main(void)
{
    /* --- Hardware init (non-WiFi) --- */
    UserApp_AppInit();

    /* --- Display + LVGL --- */
    RlcdPort.RLCD_Init();
    Lvgl_PortInit(400, 300, Lvgl_FlushCallback);

    /* --- Boot screen: show WiFi connection status --- */
    lv_obj_t *boot_label = NULL;
    if (Lvgl_lock(-1)) {
        boot_label = lv_label_create(lv_scr_act());
        lv_obj_set_style_text_font(boot_label, &lv_font_montserrat_16, 0);
        lv_obj_set_style_text_color(boot_label, lv_color_black(), 0);
        lv_label_set_text(boot_label, "Connecting to WiFi...");
        lv_obj_center(boot_label);
        Lvgl_unlock();
    }

    /* --- Start WiFi --- */
    wifi_sta_init();
    ESP_LOGI(TAG, "Waiting for WiFi connection (15s timeout)...");
    bool connected = wifi_sta_wait_connected(15000);

    /* --- Update boot screen with result --- */
    if (Lvgl_lock(-1)) {
        if (connected) {
            char ip_buf[20];
            wifi_sta_get_ip_str(ip_buf, sizeof(ip_buf));
            char msg[48];
            snprintf(msg, sizeof(msg), "Connected: %s", ip_buf);
            lv_label_set_text(boot_label, msg);
            ESP_LOGI(TAG, "WiFi connected: %s", ip_buf);
        } else {
            lv_label_set_text(boot_label, "WiFi Failed - Retrying...");
            ESP_LOGW(TAG, "WiFi connection timed out, continuing...");
        }
        Lvgl_unlock();
    }

    /* Brief pause so the user can read the boot status */
    vTaskDelay(pdMS_TO_TICKS(1000));

    /* --- Transition to full dashboard UI --- */
    if (Lvgl_lock(-1)) {
        lv_obj_del(boot_label);
        UserApp_UiInit();
        Lvgl_unlock();
    }

    /* --- Start background tasks --- */
    UserApp_TaskInit();

    ESP_LOGI(TAG, "Pi Dashboard running");
}
