#include "TabPageWidget.hpp"
#include "esp_log.h"

static const char* TAG = "TabPageWidget";

TabPageWidget::TabPageWidget(const WidgetConfig& config)
    : Widget(config)
{
}

TabPageWidget::~TabPageWidget() {
}

lv_obj_t* TabPageWidget::create(lv_obj_t* parent) {
    // Parent MUST be a TabView
    if (!parent || !lv_obj_check_type(parent, &lv_tabview_class)) {
        ESP_LOGE(TAG, "Parent of TabPage must be a TabView!");
        // Fallback: create a container so we don't crash
        obj_ = lv_obj_create(parent ? parent : lv_scr_act());
        return obj_;
    }

    obj_ = lv_tabview_add_tab(parent, config_.text);
    
    // Pages fill the parent, so x/y/w/h are ignored usually,
    // but LVGL handles layout.
    
    ESP_LOGI(TAG, "Created TabPage '%s'", config_.text);
    return obj_;
}

void TabPageWidget::applyStyle() {
    if (obj_ == nullptr) return;
    
    // Pages usually transparent, but we can style them
    // Don't use applyCommonStyle fully as it sets pos/size which we don't want
    
    if (config_.bgOpacity > 0) {
        lv_obj_set_style_bg_color(obj_, lv_color_make(
            config_.bgColor.r, config_.bgColor.g, config_.bgColor.b), 0);
        lv_obj_set_style_bg_opa(obj_, config_.bgOpacity, 0);
    } else {
        lv_obj_set_style_bg_opa(obj_, LV_OPA_TRANSP, 0);
    }

    if (config_.borderRadius > 0) {
        lv_obj_set_style_radius(obj_, config_.borderRadius, 0);
    }

    if (config_.borderWidth > 0 && config_.borderOpacity > 0) {
        lv_obj_set_style_border_width(obj_, config_.borderWidth, 0);
        lv_obj_set_style_border_color(obj_, lv_color_make(
            config_.borderColor.r, config_.borderColor.g, config_.borderColor.b), 0);
        lv_obj_set_style_border_opa(obj_, config_.borderOpacity, 0);
    } else {
        lv_obj_set_style_border_width(obj_, 0, 0);
    }

    applyShadowStyle();
}
