#include "native_ui/settings_panel.hpp"
#include "platform/i18n.hpp"

#include <format>

namespace poe2::ui {

SettingsPanelLayout SettingsPanel::BuildLayout(
    const SettingsPanelState& state,
    int screenW,
    int screenH
) {
    SettingsPanelLayout layout;
    const int panelW = 460;
    const int panelH = 460;

    int px = (screenW > panelW) ? (screenW - panelW) / 2 : 50;
    int py = (screenH > panelH) ? (screenH - panelH) / 2 : 50;
    layout.bounds = Rect{px, py, panelW, panelH};

    // 1. Bản quyền & Trạng thái
    if (state.licenseInfo.isValid) {
        if (state.licenseInfo.tier == security::LicenseTier::LIFETIME) {
            layout.statusText = std::string(platform::I18n::T("license_lifetime"));
            layout.statusColor = colors::GreenSuccess;
        } else if (state.licenseInfo.tier == security::LicenseTier::TRIAL) {
            layout.statusText = std::format("{} ({} ngay)", platform::I18n::T("license_trial"), state.licenseInfo.daysLeft);
            layout.statusColor = colors::YellowWarning;
        } else {
            layout.statusText = std::format("{} ({} ngay)", platform::I18n::T("license_subscription"), state.licenseInfo.daysLeft);
            layout.statusColor = colors::CyanStrongbox;
        }
    } else {
        layout.statusText = std::string(platform::I18n::T("license_unregistered"));
        layout.statusColor = colors::BrickRed;
    }

    // 2. Danh sách các nút gạt cấu hình (Toggles)
    struct ToggleDef {
        std::string id;
        std::string_view i18nKey;
        bool val;
    };

    const ToggleDef defs[] = {
        {"zoom", "chk_zoom", state.zoomEnabled},
        {"fog", "chk_fog", state.fogDisabled},
        {"minimap", "chk_minimap", state.minimapReveal},
        {"inspector", "chk_inspector", state.itemInspector},
        {"radar", "chk_radar", state.poiRadar},
        {"colorizer", "chk_colorizer", state.modColorizer},
        {"particle", "chk_particle", state.particleReducer},
        {"streamer", "chk_streamer", state.streamerMode},
    };

    int startY = py + 75;
    const int itemH = 32;

    for (size_t i = 0; i < sizeof(defs) / sizeof(defs[0]); ++i) {
        PanelToggle tog;
        tog.id = defs[i].id;
        tog.label = std::string(platform::I18n::T(defs[i].i18nKey));
        tog.checked = defs[i].val;
        tog.hitBox = Rect{px + 20, startY + static_cast<int>(i) * itemH, panelW - 40, 26};
        layout.toggles.push_back(std::move(tog));
    }

    // 3. Nút Panic Restore khẩn cấp & Đổi ngôn ngữ
    int btnY = py + panelH - 55;
    layout.panicButtonBox = Rect{px + 20, btnY, 240, 36};
    layout.langButtonBox = Rect{px + 275, btnY, panelW - 295, 36};

    return layout;
}

} // namespace poe2::ui
