#pragma once
#include "imgui.h"
#include "skin_changer.h"
#include "esp.h"
#include "aimbot.h"
#include "bhop.h"
#include "triggerbot.h"
#include "paint_kits.h"
#include <cstdlib>
#include <ctime>

// ============================================
// ImGui Menu — Cs2 Rage Skin Changer
// ============================================

namespace Menu
{
    // --- State ---
    inline int selectedTab = 0;
    inline int selectedWeaponIdx = 0;
    inline char searchBuffer[128] = "";

    // Weapons list for the combo box
    struct WeaponEntry
    {
        int defIndex;
        const char* name;
    };

    inline WeaponEntry weaponList[] = {
        { 7,  "AK-47" },
        { 8,  "AUG" },
        { 9,  "AWP" },
        { 1,  "Desert Eagle" },
        { 2,  "Dual Berettas" },
        { 10, "FAMAS" },
        { 3,  "Five-SeveN" },
        { 13, "Galil AR" },
        { 11, "G3SG1" },
        { 4,  "Glock-18" },
        { 14, "M249" },
        { 16, "M4A4" },
        { 60, "M4A1-S" },
        { 17, "MAC-10" },
        { 27, "MAG-7" },
        { 33, "MP7" },
        { 34, "MP9" },
        { 23, "MP5-SD" },
        { 28, "Negev" },
        { 35, "Nova" },
        { 19, "P90" },
        { 32, "P2000" },
        { 36, "P250" },
        { 26, "PP-Bizon" },
        { 64, "R8 Revolver" },
        { 29, "Sawed-Off" },
        { 38, "SCAR-20" },
        { 39, "SG 553" },
        { 40, "SSG 08" },
        { 30, "Tec-9" },
        { 24, "UMP-45" },
        { 61, "USP-S" },
        { 25, "XM1014" },
        { 63, "CZ75-Auto" },
        // Knives
        { 500, "Bayonet" },
        { 505, "Flip Knife" },
        { 506, "Gut Knife" },
        { 507, "Karambit" },
        { 508, "M9 Bayonet" },
        { 509, "Huntsman Knife" },
        { 512, "Falchion Knife" },
        { 514, "Bowie Knife" },
        { 515, "Butterfly Knife" },
        { 516, "Shadow Daggers" },
        { 517, "Paracord Knife" },
        { 519, "Ursus Knife" },
        { 520, "Navaja Knife" },
        { 521, "Nomad Knife" },
        { 522, "Stiletto Knife" },
        { 523, "Talon Knife" },
        { 525, "Skeleton Knife" },
        { 526, "Kukri Knife" },
    };
    inline constexpr int weaponListCount = sizeof(weaponList) / sizeof(weaponList[0]);

    // --- Helper: get or create skin config ---
    inline SkinChanger::SkinConfig& GetSkinConfig(int defIndex)
    {
        return SkinChanger::weaponSkins[defIndex];
    }
}

// ============================================
// RenderMenu — called from hooks.h Present hook
// ============================================

#include <d3d11.h>
#include "stb_image.h"

namespace Menu
{
    inline ID3D11ShaderResourceView* bgTextureView = nullptr;
    inline bool bgLoaded = false;
    inline bool flipBackground = false;

    inline void LoadBackgroundImage(ID3D11Device* device)
    {
        if (bgLoaded || !device) return;
        
        int w, h, channels;
        stbi_set_flip_vertically_on_load(false); // Do not flip on load automatically
        unsigned char* data = stbi_load("c:\\Users\\MSZ\\source\\repos\\cs2\\Cs2 Rage\\bg.jpg", &w, &h, &channels, 4);
        if (!data) return;
        
        D3D11_TEXTURE2D_DESC desc;
        ZeroMemory(&desc, sizeof(desc));
        desc.Width = w;
        desc.Height = h;
        desc.MipLevels = 1;
        desc.ArraySize = 1;
        desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
        desc.SampleDesc.Count = 1;
        desc.Usage = D3D11_USAGE_DEFAULT;
        desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
        desc.CPUAccessFlags = 0;

        D3D11_SUBRESOURCE_DATA subResource;
        subResource.pSysMem = data;
        subResource.SysMemPitch = desc.Width * 4;
        subResource.SysMemSlicePitch = 0;
        
        ID3D11Texture2D* pTexture = nullptr;
        if (SUCCEEDED(device->CreateTexture2D(&desc, &subResource, &pTexture)))
        {
            D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
            ZeroMemory(&srvDesc, sizeof(srvDesc));
            srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
            srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
            srvDesc.Texture2D.MipLevels = desc.MipLevels;
            srvDesc.Texture2D.MostDetailedMip = 0;
            device->CreateShaderResourceView(pTexture, &srvDesc, &bgTextureView);
            pTexture->Release();
            bgLoaded = true;
        }
        stbi_image_free(data);
    }
    
    inline void ApplyGrayTheme()
    {
        ImGuiStyle& style = ImGui::GetStyle();
        style.Colors[ImGuiCol_Text]                  = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
        style.Colors[ImGuiCol_TextDisabled]          = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
        style.Colors[ImGuiCol_WindowBg]              = ImVec4(0.12f, 0.12f, 0.12f, 0.94f);
        style.Colors[ImGuiCol_ChildBg]               = ImVec4(0.15f, 0.15f, 0.15f, 0.40f);
        style.Colors[ImGuiCol_PopupBg]               = ImVec4(0.08f, 0.08f, 0.08f, 0.94f);
        style.Colors[ImGuiCol_Border]                = ImVec4(0.30f, 0.30f, 0.30f, 0.50f);
        style.Colors[ImGuiCol_BorderShadow]          = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
        style.Colors[ImGuiCol_FrameBg]               = ImVec4(0.20f, 0.20f, 0.20f, 0.54f);
        style.Colors[ImGuiCol_FrameBgHovered]        = ImVec4(0.30f, 0.30f, 0.30f, 0.40f);
        style.Colors[ImGuiCol_FrameBgActive]         = ImVec4(0.40f, 0.40f, 0.40f, 0.67f);
        style.Colors[ImGuiCol_TitleBg]               = ImVec4(0.10f, 0.10f, 0.10f, 1.00f);
        style.Colors[ImGuiCol_TitleBgActive]         = ImVec4(0.15f, 0.15f, 0.15f, 1.00f);
        style.Colors[ImGuiCol_TitleBgCollapsed]      = ImVec4(0.00f, 0.00f, 0.00f, 0.51f);
        style.Colors[ImGuiCol_MenuBarBg]             = ImVec4(0.14f, 0.14f, 0.14f, 1.00f);
        style.Colors[ImGuiCol_ScrollbarBg]           = ImVec4(0.02f, 0.02f, 0.02f, 0.53f);
        style.Colors[ImGuiCol_ScrollbarGrab]         = ImVec4(0.31f, 0.31f, 0.31f, 1.00f);
        style.Colors[ImGuiCol_ScrollbarGrabHovered]  = ImVec4(0.41f, 0.41f, 0.41f, 1.00f);
        style.Colors[ImGuiCol_ScrollbarGrabActive]   = ImVec4(0.51f, 0.51f, 0.51f, 1.00f);
        style.Colors[ImGuiCol_CheckMark]             = ImVec4(0.70f, 0.70f, 0.70f, 1.00f);
        style.Colors[ImGuiCol_SliderGrab]            = ImVec4(0.40f, 0.40f, 0.40f, 1.00f);
        style.Colors[ImGuiCol_SliderGrabActive]      = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
        style.Colors[ImGuiCol_Button]                = ImVec4(0.25f, 0.25f, 0.25f, 0.40f);
        style.Colors[ImGuiCol_ButtonHovered]         = ImVec4(0.35f, 0.35f, 0.35f, 1.00f);
        style.Colors[ImGuiCol_ButtonActive]          = ImVec4(0.45f, 0.45f, 0.45f, 1.00f);
        style.Colors[ImGuiCol_Header]                = ImVec4(0.30f, 0.30f, 0.30f, 0.31f);
        style.Colors[ImGuiCol_HeaderHovered]         = ImVec4(0.40f, 0.40f, 0.40f, 0.80f);
        style.Colors[ImGuiCol_HeaderActive]          = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
        style.Colors[ImGuiCol_Separator]             = ImVec4(0.35f, 0.35f, 0.35f, 0.50f);
        style.Colors[ImGuiCol_SeparatorHovered]      = ImVec4(0.45f, 0.45f, 0.45f, 0.78f);
        style.Colors[ImGuiCol_SeparatorActive]       = ImVec4(0.55f, 0.55f, 0.55f, 1.00f);
        style.Colors[ImGuiCol_ResizeGrip]            = ImVec4(0.20f, 0.20f, 0.20f, 0.20f);
        style.Colors[ImGuiCol_ResizeGripHovered]     = ImVec4(0.30f, 0.30f, 0.30f, 0.67f);
        style.Colors[ImGuiCol_ResizeGripActive]      = ImVec4(0.40f, 0.40f, 0.40f, 0.95f);
        style.Colors[ImGuiCol_Tab]                   = ImVec4(0.18f, 0.18f, 0.18f, 0.86f);
        style.Colors[ImGuiCol_TabHovered]            = ImVec4(0.28f, 0.28f, 0.28f, 0.80f);
        style.Colors[ImGuiCol_TabActive]             = ImVec4(0.35f, 0.35f, 0.35f, 1.00f);
        style.Colors[ImGuiCol_TabUnfocused]          = ImVec4(0.11f, 0.11f, 0.11f, 0.97f);
        style.Colors[ImGuiCol_TabUnfocusedActive]    = ImVec4(0.14f, 0.14f, 0.14f, 1.00f);
    }
}

namespace Hooks
{
    // Need to access global device from hooks.h (which implements this file)
    extern ID3D11Device* pDevice;

    inline void RenderMenu()
    {
        using namespace Menu;
        using namespace SkinChanger;

        if (!bgLoaded && pDevice)
        {
            LoadBackgroundImage(pDevice);
        }

        ApplyGrayTheme();

        ImGui::SetNextWindowSize(ImVec2(800, 600), ImGuiCond_Always);
        ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));

        ImGui::Begin("Cs2 Rage 【汉化版】 - 12游戏吧永久地址发布页：www.12gameb.co", &Hooks::showMenu, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse);

        ImVec2 winPos = ImGui::GetWindowPos();
        ImVec2 winSize = ImGui::GetWindowSize();
        ImDrawList* drawList = ImGui::GetWindowDrawList();

        // Draw Background if loaded.
        if (bgTextureView)
        {
            if (flipBackground) {
                // Upside down rendering coordinates
                drawList->AddImage(bgTextureView, winPos, ImVec2(winPos.x + winSize.x, winPos.y + winSize.y), ImVec2(0, 1), ImVec2(1, 0));
            }
            else {
                // Standard rendering coordinates
                drawList->AddImage(bgTextureView, winPos, ImVec2(winPos.x + winSize.x, winPos.y + winSize.y), ImVec2(0, 0), ImVec2(1, 1));
            }
        }

        // Inner Padding - move cursor right to give text breathing room
        ImGui::SetCursorPos(ImVec2(15, 30));

        // Restore internal padding so child windows look normal
        ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8, 8));
        ImGui::BeginChild("MainArea", ImVec2(winSize.x - 30, winSize.y - 45), false);

        if (ImGui::BeginTabBar("MainTabs", ImGuiTabBarFlags_NoTooltip))
        {
            // --------------- RAGE TAB ---------------
            if (ImGui::BeginTabItem("暴力"))
            {
                ImGui::Spacing();
                ImGui::Columns(2, "rageAimbotLayout", false);

                // Left Column
                ImGui::BeginChild("AimbotLeft", ImVec2(0, 0), true);
                ImGui::Text("主自瞄");
                ImGui::Separator();
                ImGui::Spacing();

                ImGui::Checkbox("启用自瞄", &Aimbot::config.enabled);

                const char* keys[] = { "自动", "鼠标右键", "鼠标4键", "鼠标5键", "Shift", "Alt" };
                int keyIdx = 0;
                if (Aimbot::config.aimKey == VK_RBUTTON) keyIdx = 1;
                else if (Aimbot::config.aimKey == VK_XBUTTON1) keyIdx = 2;
                else if (Aimbot::config.aimKey == VK_XBUTTON2) keyIdx = 3;
                else if (Aimbot::config.aimKey == VK_SHIFT) keyIdx = 4;
                else if (Aimbot::config.aimKey == VK_MENU) keyIdx = 5;
                if (ImGui::Combo("瞄准键", &keyIdx, keys, IM_ARRAYSIZE(keys)))
                {
                    const int vks[] = { 0, VK_RBUTTON, VK_XBUTTON1, VK_XBUTTON2, VK_SHIFT, VK_MENU };
                    Aimbot::config.aimKey = vks[keyIdx];
                }

                ImGui::Checkbox("自动射击", &Aimbot::config.autoShoot);
                ImGui::Checkbox("静默自瞄", &Aimbot::config.silentAim);
                ImGui::Checkbox("队友检测", &Aimbot::config.teamCheck);

                ImGui::EndChild();

                ImGui::NextColumn();

                // Right Column
                ImGui::BeginChild("AimbotRight", ImVec2(0, 0), true);
                ImGui::Text("配置");
                ImGui::Separator();
                ImGui::Spacing();

                const char* fovTypes[] = { "角度（度）", "屏幕（像素）" };
                ImGui::Combo("FOV模式", &Aimbot::config.fovType, fovTypes, IM_ARRAYSIZE(fovTypes));
                if (Aimbot::config.fovType == 0)
                    ImGui::SliderFloat("FOV", &Aimbot::config.fov, 1.0f, 180.0f, "%.1f 度");
                else
                    ImGui::SliderFloat("FOV", &Aimbot::config.screenFov, 10.0f, 1000.0f, "%.0f 像素");

                const char* bones[] = { "头部", "颈部", "胸部", "骨盆" };
                int boneIdx = 0;
                if (Aimbot::config.targetBone == 5) boneIdx = 1;
                else if (Aimbot::config.targetBone == 4) boneIdx = 2;
                else if (Aimbot::config.targetBone == 3) boneIdx = 3;
                if (ImGui::Combo("命中部位", &boneIdx, bones, IM_ARRAYSIZE(bones)))
                {
                    const int boneIds[] = { 6, 5, 4, 3 };
                    Aimbot::config.targetBone = boneIds[boneIdx];
                }

                ImGui::Spacing();
                ImGui::Separator();
                ImGui::Text("扳机");
                ImGui::Spacing();

                ImGui::Checkbox("启用扳机", &Triggerbot::config.enabled);

                const char* tbKeys[] = { "自动", "鼠标右键", "鼠标4键", "鼠标5键", "Shift", "Alt" };
                int tbKeyIdx = 0;
                if (Triggerbot::config.key == VK_RBUTTON) tbKeyIdx = 1;
                else if (Triggerbot::config.key == VK_XBUTTON1) tbKeyIdx = 2;
                else if (Triggerbot::config.key == VK_XBUTTON2) tbKeyIdx = 3;
                else if (Triggerbot::config.key == VK_SHIFT) tbKeyIdx = 4;
                else if (Triggerbot::config.key == VK_MENU) tbKeyIdx = 5;
                if (ImGui::Combo("扳机键", &tbKeyIdx, tbKeys, IM_ARRAYSIZE(tbKeys)))
                {
                    const int tbvks[] = { 0, VK_RBUTTON, VK_XBUTTON1, VK_XBUTTON2, VK_SHIFT, VK_MENU };
                    Triggerbot::config.key = tbvks[tbKeyIdx];
                    Triggerbot::config.useKey = (tbvks[tbKeyIdx] != 0);
                }
                ImGui::Checkbox("队友检测（扳机）", &Triggerbot::config.teamCheck);
                ImGui::SliderInt("延迟（毫秒）", &Triggerbot::config.delayMs, 0, 200);

                ImGui::EndChild();

                ImGui::Columns(1);
                ImGui::EndTabItem();
            }

            // --------------- VISUALS TAB ---------------
            if (ImGui::BeginTabItem("视觉"))
            {
                ImGui::Spacing();

                ImGui::BeginChild("VisualsMain", ImVec2(0, 0), true);
                ImGui::Text("透视");
                ImGui::Separator();
                ImGui::Spacing();

                ImGui::Checkbox("启用透视", &ESP::config.enabled);
                if (ESP::config.enabled)
                {
                    ImGui::Checkbox("方框", &ESP::config.bBox);
                    if (ESP::config.bBox)
                    {
                        const char* modes[] = { "普通", "边角" };
                        ImGui::Combo("方框样式", &ESP::config.boxMode, modes, IM_ARRAYSIZE(modes));
                    }
                    ImGui::ColorEdit4("方框颜色", ESP::config.boxColor, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_AlphaBar);
                    ImGui::Checkbox("骨骼", &ESP::config.bSkeleton);
                    ImGui::ColorEdit4("骨骼颜色", ESP::config.skeletonColor, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_AlphaBar);
                    ImGui::Checkbox("血条", &ESP::config.bHealthBar);
                    ImGui::Checkbox("名字", &ESP::config.bName);
                    ImGui::Checkbox("距离", &ESP::config.bDistance);
                    ImGui::Checkbox("队友检测", &ESP::config.teamCheck);
                    ImGui::Spacing();
                }
                ImGui::Separator();
                ImGui::Spacing();

                ImGui::Text("其他");
                ImGui::Checkbox("翻转背景图片", &Menu::flipBackground);
                ImGui::Checkbox("连跳", &Bhop::config.enabled);
                ImGui::Checkbox("弹道轨迹", &BulletTracer::config.enabled);
                ImGui::Checkbox("第三人称视角", &thirdPerson);

                ImGui::Separator();
                ImGui::Spacing();
                ImGui::Text("附加功能");
                ImGui::Checkbox("C4计时器", &ESP::config.bBombTimer);
                ImGui::Checkbox("观战列表", &ESP::config.bSpectators);
                ImGui::Checkbox("发光透视", &ESP::config.bGlow);
                if (ESP::config.bGlow)
                {
                    ImGui::ColorEdit4("发光颜色", ESP::config.glowColor, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_AlphaBar);
                }

                ImGui::EndChild();

                ImGui::EndTabItem();
            }

            // --------------- SKINS TAB ---------------
            if (ImGui::BeginTabItem("皮肤"))
            {
                ImGui::Spacing();

                // --- Knife Model Changer ---
                ImGui::Checkbox("刀具模型修改", &SkinChanger::knifeChangerEnabled);
                if (SkinChanger::knifeChangerEnabled)
                {
                    ImGui::SameLine();
                    ImGui::SetNextItemWidth(200);
                    if (ImGui::BeginCombo("##knifemodel", SkinChanger::knifeModels[SkinChanger::selectedKnifeModel].name))
                    {
                        for (int i = 0; i < SkinChanger::knifeModelCount; i++)
                        {
                            bool selected = (SkinChanger::selectedKnifeModel == i);
                            if (ImGui::Selectable(SkinChanger::knifeModels[i].name, selected))
                            {
                                SkinChanger::selectedKnifeModel = i;
                                SkinChanger::lastAppliedWeapon = 0; // force re-apply
                                SkinChanger::forceUpdate.store(true);
                            }
                            if (selected) ImGui::SetItemDefaultFocus();
                        }
                        ImGui::EndCombo();
                    }
                }
                ImGui::Separator();
                ImGui::Spacing();

                ImGui::Columns(2, "skinsLayout", false);

                // Left Column
                ImGui::BeginChild("WeaponsLeft", ImVec2(0, 0), true);
                ImGui::Text("库存");
                ImGui::Separator();
                ImGui::Spacing();

                if (ImGui::Button("强制刷新", ImVec2(-1, 0))) {
                    forceUpdate.store(true);
                }
                if (ImGui::Button("清除所有皮肤", ImVec2(-1, 0))) {
                    std::lock_guard<std::mutex> lock(configMutex);
                    weaponSkins.clear();
                    forceUpdate.store(true);
                }
                if (ImGui::Button("全部随机", ImVec2(-1, 0))) {
                    std::lock_guard<std::mutex> lock(configMutex);
                    if (!g_PaintKits.empty()) {
                        srand((unsigned int)time(NULL));
                        for (int i = 0; i < weaponListCount; i++) {
                            int defIdx = weaponList[i].defIndex;
                            SkinConfig& cfg = weaponSkins[defIdx];
                            cfg.enabled = true;
                            int randomIdx = rand() % g_PaintKits.size();
                            cfg.paintKit = g_PaintKits[randomIdx].id;
                            cfg.wear = 0.001f;
                            cfg.seed = 0;
                            cfg.statTrak = -1;
                        }
                        forceUpdate.store(true);
                    }
                }

                ImGui::Spacing();
                for (int i = 0; i < weaponListCount; i++)
                {
                    bool hasConfig = weaponSkins.count(weaponList[i].defIndex) > 0 && weaponSkins[weaponList[i].defIndex].enabled;
                    if (hasConfig) ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.5f, 0.9f, 0.5f, 1.0f));

                    if (ImGui::Selectable(weaponList[i].name, selectedWeaponIdx == i))
                        selectedWeaponIdx = i;

                    if (hasConfig) ImGui::PopStyleColor();
                }
                ImGui::EndChild();

                ImGui::NextColumn();

                // Right Column
                ImGui::BeginChild("WeaponsRight", ImVec2(0, 0), true);
                if (selectedWeaponIdx >= 0 && selectedWeaponIdx < weaponListCount)
                {
                    int defIdx = weaponList[selectedWeaponIdx].defIndex;
                    SkinConfig& cfg = GetSkinConfig(defIdx);

                    ImGui::Text("配置 %s", weaponList[selectedWeaponIdx].name);
                    ImGui::Separator();
                    ImGui::Spacing();

                    ImGui::Checkbox("启用", &cfg.enabled);

                    // Advanced Skin Selector
                    static int selectedRarity = 0; // 0 = All
                    static char skinSearchBuf[64] = "";
                    const char* rarityNames[] = { "全部", "消费级（灰色）", "工业级（浅蓝）", "军规级（蓝）", "受限（紫）", "保密（粉）", "隐秘（红）", "违禁（金）" };
                    ImGui::Combo("稀有度筛选", &selectedRarity, rarityNames, IM_ARRAYSIZE(rarityNames));
                    ImGui::InputTextWithHint("##skinSearch", "搜索皮肤...", skinSearchBuf, sizeof(skinSearchBuf));

                    std::string previewName = "自定义ID: " + std::to_string(cfg.paintKit);
                    for (const auto& pk : g_PaintKits) {
                        if (pk.id == cfg.paintKit) {
                            previewName = pk.name;
                            break;
                        }
                    }

                    if (ImGui::BeginCombo("皮肤图案", previewName.c_str())) {
                        bool customSelected = false;
                        ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 1));
                        ImGui::Selectable("--- 自定义ID ---", customSelected);
                        ImGui::PopStyleColor();

                        // Convert search to lowercase for case-insensitive matching
                        std::string searchLower = skinSearchBuf;
                        for (auto& c : searchLower) c = (char)tolower(c);

                        for (const auto& pk : g_PaintKits) {
                            if (selectedRarity != 0 && (int)pk.rarity != selectedRarity - 1)
                                continue;

                            // Filter by search text
                            if (searchLower.length() > 0) {
                                std::string nameLower = pk.name;
                                for (auto& c : nameLower) c = (char)tolower(c);
                                if (nameLower.find(searchLower) == std::string::npos)
                                    continue;
                            }

                            bool isSelected = (cfg.paintKit == pk.id);

                            // Show ID next to name for clarity
                            char label[128];
                            snprintf(label, sizeof(label), "[%d] %s", pk.id, pk.name);

                            ImGui::PushStyleColor(ImGuiCol_Text, GetRarityColor(pk.rarity));
                            if (ImGui::Selectable(label, isSelected)) {
                                cfg.paintKit = pk.id;
                            }
                            ImGui::PopStyleColor();
                            if (isSelected) {
                                ImGui::SetItemDefaultFocus();
                            }
                        }
                        ImGui::EndCombo();
                    }

                    ImGui::InputInt("自定义皮肤ID", &cfg.paintKit);
                    if (cfg.paintKit < 0) cfg.paintKit = 0;

                    ImGui::SliderFloat("磨损度", &cfg.wear, 0.0f, 1.0f, "%.4f");
                    ImGui::InputInt("种子", &cfg.seed);

                    bool useStatTrak = cfg.statTrak >= 0;
                    if (ImGui::Checkbox("暗金计数", &useStatTrak)) cfg.statTrak = useStatTrak ? 0 : -1;
                    if (useStatTrak) {
                        ImGui::SameLine();
                        ImGui::SetNextItemWidth(100);
                        ImGui::InputInt("##statval", &cfg.statTrak);
                    }

                    // --- Custom Texture (Runtime Replacement) ---
                    ImGui::Spacing();
                    ImGui::Separator();
                    ImGui::Spacing();
                    if (ImGui::TreeNode("自定义纹理（将你的图片贴到武器上）"))
                    {
                        ImGui::Checkbox("启用自定义纹理", &CustomTexture::enabled);

                        ImGui::InputText("图片路径", CustomTexture::imagePath, sizeof(CustomTexture::imagePath));

                        if (ImGui::Button("加载图片", ImVec2(-1, 0)))
                        {
                            if (pDevice)
                            {
                                if (CustomTexture::LoadCustomImage(pDevice, CustomTexture::imagePath))
                                    printf("[Menu] Custom image loaded!\n");
                                else
                                    printf("[Menu] Failed to load image\n");
                            }
                        }

                        if (CustomTexture::imageLoaded)
                        {
                            ImGui::TextColored(ImVec4(0.4f, 1.0f, 0.4f, 1.0f), "图片已加载！");
                        }
                        else
                        {
                            ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "未加载图片");
                        }

                        ImGui::Spacing();
                        ImGui::Text("纹理过滤（0 = 任意）");
                        ImGui::InputInt("宽度##filter", &CustomTexture::filterWidth, 256);
                        ImGui::InputInt("高度##filter", &CustomTexture::filterHeight, 256);
                        if (CustomTexture::filterWidth < 0) CustomTexture::filterWidth = 0;
                        if (CustomTexture::filterHeight < 0) CustomTexture::filterHeight = 0;

                        ImGui::Spacing();
                        ImGui::Separator();
                        ImGui::Spacing();

                        // Browse mode controls
                        if (!CustomTexture::browseMode)
                        {
                            if (ImGui::Button("开始浏览", ImVec2(-1, 0)))
                            {
                                CustomTexture::ResetBrowse();
                                CustomTexture::browseMode = true;
                            }
                        }
                        else
                        {
                            ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.3f, 1.0f),
                                "浏览模式 — 看着你的武器！");
                            ImGui::Text("候选纹理数量: %d", CustomTexture::candidateCount);
                            ImGui::Text("当前: %d / %d",
                                CustomTexture::browseIndex + 1, CustomTexture::candidateCount);

                            if (ImGui::Button("< 上一个 (F10)")) CustomTexture::BrowsePrev();
                            ImGui::SameLine();
                            if (ImGui::Button("下一个 > (F11)")) CustomTexture::BrowseNext();

                            ImGui::Spacing();
                            if (ImGui::Button("锁定此纹理 (F12)", ImVec2(-1, 0)))
                                CustomTexture::LockCurrent();

                            if (ImGui::Button("停止浏览", ImVec2(-1, 0)))
                                CustomTexture::browseMode = false;
                        }

                        // Show locked status
                        if (CustomTexture::lockedSRV)
                        {
                            ImGui::TextColored(ImVec4(0.3f, 1.0f, 0.3f, 1.0f), "已锁定！");
                            if (ImGui::Button("解锁", ImVec2(-1, 0)))
                                CustomTexture::Unlock();
                        }

                        if (ImGui::Button("全部重置", ImVec2(-1, 0)))
                            CustomTexture::ResetBrowse();

                        ImGui::Spacing();
                        ImGui::Separator();
                        ImGui::Spacing();

                        // Debug info
                        ImGui::TextColored(ImVec4(0.6f, 0.6f, 0.6f, 1.0f), "调试信息:");
                        ImGui::Text("钩子调用次数: %d", CustomTexture::hookCalls);
                        ImGui::Text("见过的唯一SRV数: %d", CustomTexture::totalUniqueSRVs);
                        ImGui::Text("钩子激活: %s", CustomTexture::hooked ? "是" : "否");
                        ImGui::Checkbox("无过滤（接受全部）", &CustomTexture::noFilter);
                        ImGui::InputInt("最小尺寸##min", &CustomTexture::minSize, 32);
                        if (CustomTexture::minSize < 1) CustomTexture::minSize = 1;

                        ImGui::Spacing();
                        ImGui::Separator();
                        ImGui::TextColored(ImVec4(0.7f, 0.85f, 1.0f, 1.0f), "使用方法:");
                        ImGui::BulletText("设置图片路径并点击“加载图片”");
                        ImGui::BulletText("启用后点击“开始浏览”");
                        ImGui::BulletText("使用 F10/F11 切换纹理");
                        ImGui::BulletText("当武器显示你的图片时，按 F12 锁定");
                        ImGui::BulletText("快捷键: F10=上一个 F11=下一个 F12=锁定");

                        ImGui::TreePop();
                    }
                }
                ImGui::EndChild();

                ImGui::Columns(1);
                ImGui::EndTabItem();
            }

            ImGui::EndTabBar();
        }

        ImGui::EndChild();
        ImGui::PopStyleVar(); // Inner padding

        ImGui::PopStyleVar(); // WindowPadding (0,0)
        ImGui::End();
    }
}
