// render.hpp
#pragma once
#include <Windows.h>
#include <iostream>
#include <d3d11.h>
#include <d3dx11.h>
#include <dwmapi.h>
#define IMGUI_DEFINE_MATH_OPERATORS
#include "../extern/Imgui/imgui.h"
using namespace ImGui;
#include "../utils/settings.hpp"
#include "../extern/Imgui/imgui_impl_dx11.h"
#include "../extern/Imgui/imgui_impl_win32.h"
#include "../sdk/loops.hpp"
#include "../utils/Bytes/ESPFONT.h"
#include "../utils/custom.hpp"
#include "../utils/Authentication/skStr.h"
#include "configs.h"
#include "../extern/Imgui/imgui_settings.h"
#include "../extern/Imgui/imgui_freetype.h"
//#include "gui/font.h"
#include "gui/font_defines.h" // Assuming this defines your ICON_* macros and possibly the icon font range
#include "gui/var.hpp"
#include "gui/notifications.h"
#include "../extern/fa/logo.h"
#include "../extern/fa/fa.h"
#include "../extern/fa/font.h"
#include <map>
#include "../extern/blur/directx_blur.h"
#include "gui/custom_widgets.hpp"
#include "gui/custom_popup.hpp"

#include "gui/agui.h"

static std::vector<s_tab> tabs_info;

c_tabs* p_tabs;

static bool tab_is_changed = false;

static float tab_offset = 0.f;

static float menu_alpha = 1.F;

DWORD picker_flags = ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_AlphaBar | ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_AlphaPreview;



struct OverlayResources {
    HWND hwnd{ nullptr };
    ID3D11Device* device{ nullptr };
    ID3D11DeviceContext* context{ nullptr };
    ID3D11RenderTargetView* rtv{ nullptr };
    IDXGISwapChain* swap{ nullptr };
} static inline Overlay;


inline ImFont* ESPFont = nullptr;
inline ConfigManager g_ConfigManager;
ImFont* tab;
CNotifications p_notif;




void UpdateFloatWithLerp(bool& condition, float& a, float b, float c) {
    // Получаем DeltaTime для плавного перехода
    float deltaTime = ImGui::GetIO().DeltaTime;
    float speed = 11.0f;

    if (condition) {
        // Если условие true, плавно изменяем a от b к c
        a = ImLerp(a, c, deltaTime * speed);

        // Если разница между a и c меньше 1.5f, меняем условие на false
        if (ImAbs(a - c) < 30.f) {
            condition = false;
        }
    }
    else {
        // Если условие false, плавно изменяем a от c к b
        a = ImLerp(a, b, deltaTime * speed);
    }
}

void BarSmallText(const char* text, const char* text2)
{
    ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
    ImGui::Text(text); ImGui::SameLine();
    ImGui::PushFont(font::small_font);
    ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 2);
    ImGui::TextDisabled(text2);  ImGui::SameLine();
    ImGui::SameLine();
    ImGui::PopFont();
    ImGui::PopStyleVar();
}

struct smooth_tab_info
{
    float prereview_storage_alpha, prereview_rect_alpha;
    bool drag_drop_enabled;
    int current_position;
    int wanted_position;
    ImRect preview_rect;
    ImVec2 preview_rect_target_pos;

    ImRect tabbar_rect;
};

static inline bool InitializeD3D() {
    DXGI_SWAP_CHAIN_DESC desc{};
    ZeroMemory(&desc, sizeof(desc));
    desc.BufferCount = 2;
    desc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    desc.BufferDesc.RefreshRate.Numerator = 60;
    desc.BufferDesc.RefreshRate.Denominator = 1;
    desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    desc.OutputWindow = Overlay.hwnd;
    desc.SampleDesc.Count = 1;
    desc.SampleDesc.Quality = 0;
    desc.Windowed = TRUE;
    desc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
    desc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
    D3D_FEATURE_LEVEL levels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0 };
    D3D_FEATURE_LEVEL selectedLevel;
    if (FAILED(D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, 0, levels, _countof(levels),
        D3D11_SDK_VERSION, &desc, &Overlay.swap, &Overlay.device, &selectedLevel, &Overlay.context))) {
        return false;
    }
    ID3D11Texture2D* backBuffer = nullptr;
    if (FAILED(Overlay.swap->GetBuffer(0, IID_PPV_ARGS(&backBuffer))) || !backBuffer) return false;
    if (FAILED(Overlay.device->CreateRenderTargetView(backBuffer, nullptr, &Overlay.rtv))) return false;
    backBuffer->Release();

    ImGui::CreateContext();

    ImGuiIO& io = ImGui::GetIO(); (void)io;
    io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
    io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;
    ImFontConfig cfg;
    cfg.FontBuilderFlags = ImGuiFreeTypeBuilderFlags_NoHinting | ImGuiFreeTypeBuilderFlags_LightHinting | ImGuiFreeTypeBuilderFlags_LoadColor;

    io.Fonts->AddFontFromMemoryTTF(PoppinsMedium, sizeof(PoppinsMedium), 18.f, &cfg, io.Fonts->GetGlyphRangesChineseSimplifiedCommon());


    static ImWchar icomoon_ranges[] = { 0x1, 0x10FFFD, 0 };

    static ImFontConfig icomoon_config;
    icomoon_config.FontDataOwnedByAtlas = false;
    icomoon_config.OversampleH = icomoon_config.OversampleV = 1;
    icomoon_config.MergeMode = true;
    icomoon_config.GlyphOffset.y = 3.f;
    icomoon_config.FontBuilderFlags = ImGuiFreeTypeBuilderFlags_ForceAutoHint | ImGuiFreeTypeBuilderFlags_LightHinting | ImGuiFreeTypeBuilderFlags_LoadColor;

    ImFontConfig cfgcwel;
    cfgcwel.FontDataOwnedByAtlas = false;
    cfgcwel.OversampleH = cfgcwel.OversampleV = 1;
    cfgcwel.MergeMode = true;
    cfgcwel.GlyphOffset.y = 3.f;
    cfgcwel.FontBuilderFlags = ImGuiFreeTypeBuilderFlags_ForceAutoHint | ImGuiFreeTypeBuilderFlags_LightHinting | ImGuiFreeTypeBuilderFlags_LoadColor;

    //font::icomoontest = io.Fonts->AddFontFromMemoryCompressedBase85TTF(icomoon_compressed_data_base85, 18.f, &icomoon_config2, icomoon_ranges);
    static const ImWchar icons_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };

    font::default_r = io.Fonts->AddFontFromMemoryTTF(PoppinsRegular, sizeof(PoppinsRegular), 18.f, &cfg, io.Fonts->GetGlyphRangesChineseSimplifiedCommon());
    io.Fonts->AddFontFromMemoryCompressedTTF(FA_compressed_data, FA_compressed_size, 18.f, &cfgcwel, icons_ranges);
    font::default_m = io.Fonts->AddFontFromMemoryTTF(PoppinsMedium, sizeof(PoppinsMedium), 18.f, &cfg, io.Fonts->GetGlyphRangesChineseSimplifiedCommon());
    io.Fonts->AddFontFromMemoryCompressedTTF(FA_compressed_data, FA_compressed_size, 18.f, &cfgcwel, icons_ranges);
    font::default_s = io.Fonts->AddFontFromMemoryTTF(PoppinsSemiBold, sizeof(PoppinsSemiBold), 18.f, &cfg, io.Fonts->GetGlyphRangesChineseSimplifiedCommon());
    io.Fonts->AddFontFromMemoryCompressedTTF(FA_compressed_data, FA_compressed_size, 18.f, &cfgcwel, icons_ranges);



    font::esp_font = io.Fonts->AddFontFromMemoryTTF(PoppinsMedium, sizeof(PoppinsMedium), 15.f, &cfg, io.Fonts->GetGlyphRangesChineseSimplifiedCommon());
    icomoon_config.GlyphOffset.y = 0.f;
    //io.Fonts->AddFontFromMemoryCompressedBase85TTF(icomoon_compressed_data_base85, 15.f, &icomoon_config, icomoon_ranges);

    font::description_font = io.Fonts->AddFontFromMemoryTTF(PoppinsMedium, sizeof(PoppinsMedium), 16.f, &cfg, io.Fonts->GetGlyphRangesChineseSimplifiedCommon());
    io.Fonts->AddFontFromMemoryCompressedTTF(FA_compressed_data, FA_compressed_size, 16.f, &cfgcwel, icons_ranges);

    font::regular_m = io.Fonts->AddFontFromMemoryTTF(PoppinsRegular, sizeof(PoppinsRegular), 23.f, &cfg, io.Fonts->GetGlyphRangesChineseSimplifiedCommon());
    icomoon_config.GlyphOffset.y = 3.f;
    io.Fonts->AddFontFromMemoryCompressedTTF(FA_compressed_data, FA_compressed_size, 23.f, &cfgcwel, icons_ranges);

    font::regular_l = io.Fonts->AddFontFromMemoryTTF(PoppinsRegular, sizeof(PoppinsRegular), 35.f, &cfg, io.Fonts->GetGlyphRangesChineseSimplifiedCommon());
    icomoon_config.GlyphOffset.y = 0.f;
    io.Fonts->AddFontFromMemoryCompressedTTF(FA_compressed_data, FA_compressed_size, 35.f, &cfgcwel, icons_ranges);

    font::s_inter_semibold = io.Fonts->AddFontFromMemoryTTF(PoppinsSemiBold, sizeof(PoppinsSemiBold), 17.f, &cfg, io.Fonts->GetGlyphRangesChineseSimplifiedCommon());
    font::inter_bold = io.Fonts->AddFontFromMemoryTTF(PoppinsSemiBold, sizeof(PoppinsSemiBold), 18.f, &cfg, io.Fonts->GetGlyphRangesChineseSimplifiedCommon());

    font::inter_semibold = io.Fonts->AddFontFromMemoryTTF(PoppinsSemiBold, sizeof(PoppinsSemiBold), 29.f, &cfg, io.Fonts->GetGlyphRangesChineseSimplifiedCommon());
    io.Fonts->AddFontFromMemoryCompressedTTF(FA_compressed_data, FA_compressed_size, 27.f, &cfgcwel, icons_ranges);

    font::small_font = io.Fonts->AddFontFromMemoryTTF(PoppinsSemiBold, sizeof(PoppinsSemiBold), 14.f, &cfg, io.Fonts->GetGlyphRangesChineseSimplifiedCommon());
    font::inter_medium = io.Fonts->AddFontFromMemoryTTF(PoppinsMedium, sizeof(PoppinsMedium), 17.f, &cfg, io.Fonts->GetGlyphRangesChineseSimplifiedCommon());

    ImGui_ImplWin32_Init(Overlay.hwnd);
    ImGui_ImplDX11_Init(Overlay.device, Overlay.context);

    bool show_demo_window = true;
    bool show_another_window = false;
    ImVec4 clear_color = ImColor(0, 0, 0, 255);

    D3DX11_IMAGE_LOAD_INFO info; ID3DX11ThreadPump* pump{ nullptr };
    if (texture::xenoware_logo == nullptr) D3DX11CreateShaderResourceViewFromMemory(Overlay.device, xenoware_logo, sizeof(xenoware_logo), &info, pump, &texture::xenoware_logo, 0);

    current_scroll = 0.f;

    g_ConfigManager.RefreshConfigList();

    ImGuiStyle& s = ImGui::GetStyle();
    s.FramePadding = ImVec2(15, 20);
    s.ItemSpacing = ImVec2(10, 10);
    s.FrameRounding = 2.f;
    s.WindowRounding = 20.f;
    s.WindowBorderSize = 0.f;
    s.PopupBorderSize = 0.f;
    s.WindowPadding = ImVec2(0, 0);
    s.ChildBorderSize = 1.f;
    s.Colors[ImGuiCol_Border] = ImVec4(0.f, 0.f, 0.f, 0.f);
    s.Colors[ImGuiCol_Separator] = ImVec4(1.f, 1.f, 1.f, 0.2f);
    s.Colors[ImGuiCol_BorderShadow] = ImVec4(0.f, 0.f, 0.f, 0.f);
    s.WindowShadowSize = 0;
    s.PopupRounding = 5.f;
    s.ScrollbarSize = 1;
    s.SeparatorTextPadding = ImVec2(10, 10);

    tabs_info.push_back({ {ICON_FA_CAR, ICON_FA_EYE, ICON_FA_LANGUAGE }, {"Car", "ESP", "Lang"} });

    //Overlay.device->Release();

    RAWINPUTDEVICE rid{};
    rid.usUsagePage = 0x01;
    rid.usUsage = 0x02; // mouse
    rid.dwFlags = RIDEV_INPUTSINK;
    rid.hwndTarget = Overlay.hwnd; // MUSISZ mieć hwnd

    RegisterRawInputDevices(&rid, 1, sizeof(rid));

    return true;
}

static inline bool AttachDiscordOverlay() {
    Overlay.hwnd = FindWindowA(nullptr, skCrypt("Discord Overlay").decrypt());
    if (!Overlay.hwnd) {
        MessageBoxA(nullptr, skCrypt("Overlay not found. Try restarting cheat?").decrypt(), skCrypt("Error").decrypt(), MB_OK);
        return false;
    }

    int screenW = GetSystemMetrics(SM_CXSCREEN);
    int screenH = GetSystemMetrics(SM_CYSCREEN);

    SetMenu(Overlay.hwnd, nullptr);
    SetWindowPos(Overlay.hwnd, HWND_TOPMOST, 0, 0, screenW, screenH, SWP_SHOWWINDOW);

    LONG exStyle = WS_EX_LAYERED | WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT;

    if (settings::ui.streamproof) {
        exStyle |= WS_EX_NOREDIRECTIONBITMAP;
    }

    SetWindowLongA(Overlay.hwnd, GWL_EXSTYLE, exStyle);
    SetWindowLongA(Overlay.hwnd, GWL_STYLE, WS_VISIBLE);
    SetWindowLongA(Overlay.hwnd, -20, GetWindowLongA(Overlay.hwnd, -20) | 0x20);

    MARGINS margins = { -1, -1, -1, -1 };
    DwmExtendFrameIntoClientArea(Overlay.hwnd, &margins);
    SetLayeredWindowAttributes(Overlay.hwnd, 0, 255, LWA_ALPHA);

    ShowWindow(Overlay.hwnd, SW_SHOW);
    UpdateWindow(Overlay.hwnd);

    return true;
}

static inline void DrawMenu() {

    /*ImGui::Begin("guwno");

    ImGui::End();*/
    //std::cout << "render\n";

    ImGuiStyle& s = ImGui::GetStyle();

    static bool hovered_esp_preview = false;

    float off = 0.0f;
    float th = 90.0f;
    auto& bb = c::bg::menu_bb;

    std::vector<ImDrawFlags> tab_flags = {
        ImDrawFlags_RoundCornersTop, ImDrawFlags_RoundCornersBottom, ImDrawFlags_RoundCornersLeft, ImDrawFlags_RoundCornersRight
    };

    std::vector<ImDrawFlags> menu_draw_flags = {
        ImDrawFlags_RoundCornersBottom, ImDrawFlags_RoundCornersTop, ImDrawFlags_RoundCornersRight, ImDrawFlags_RoundCornersLeft
    };

    std::vector<ImRect> tab_storages = {
        // 0 — сверху
        { ImRect(
            ImVec2(bb.Min.x - off,       bb.Min.y - off - th),
            ImVec2(bb.Max.x + off,       bb.Min.y - off)
          )
        },
            // 1 — снизу
            { ImRect(
                ImVec2(bb.Min.x - off,       bb.Max.y + off),
                ImVec2(bb.Max.x + off,       bb.Max.y + off + th)
              )
            },
            // 2 — слева
            { ImRect(
                ImVec2(bb.Min.x - off - th * 2.5f,  bb.Min.y - off),
                ImVec2(bb.Min.x - off,       bb.Max.y + off)
              )
            },
            // 3 — справа
            { ImRect(
                ImVec2(bb.Max.x + off,       bb.Min.y - off),
                ImVec2(bb.Max.x + off + th * 2.5f,  bb.Max.y + off)
              )
            }
    };

    static std::map<ImGuiID, smooth_tab_info> anim;
    auto it_anim = anim.find(GetID("TAB_BAR"));

    if (it_anim == anim.end())
    {
        anim.insert({ GetID("TAB_BAR"), smooth_tab_info() });
        it_anim = anim.find(GetID("TAB_BAR"));
    }


    for (int i = 0; i < tab_storages.size(); i++)
    {
        ImGui::GetForegroundDrawList()->AddRectFilled(tab_storages[i].Min, tab_storages[i].Max, ImColor(1.f, 1.f, 1.f, it_anim->second.prereview_storage_alpha), c::bg::rounding);
        if (it_anim->second.drag_drop_enabled)
        {
            if (tab_storages[i].Contains(ImGui::GetMousePos())) {
                it_anim->second.wanted_position = i;
                it_anim->second.preview_rect_target_pos = tab_storages[it_anim->second.wanted_position].Min;
            }

            if (!tab_storages[0].Contains(ImGui::GetMousePos()) && !tab_storages[1].Contains(ImGui::GetMousePos()) && !tab_storages[2].Contains(ImGui::GetMousePos()) && !tab_storages[3].Contains(ImGui::GetMousePos())) {
                it_anim->second.preview_rect.Max = ImLerp(it_anim->second.preview_rect.Max, it_anim->second.preview_rect.Min + tab_storages[it_anim->second.wanted_position].GetSize(), c::anim::speed * 4);
                it_anim->second.preview_rect_target_pos = ImGui::GetMousePos();
            }
            else
                it_anim->second.preview_rect.Max = ImLerp(it_anim->second.preview_rect.Max, it_anim->second.preview_rect.Min + tab_storages[it_anim->second.wanted_position].GetSize(), c::anim::speed / 2);

            if (!ImGui::IsMouseDown(ImGuiMouseButton_Left))
            {
                it_anim->second.prereview_rect_alpha = 1.f;
                it_anim->second.current_position = it_anim->second.wanted_position;
                it_anim->second.drag_drop_enabled = false;
            }
        }
    }

    if (!it_anim->second.drag_drop_enabled)
    {
        it_anim->second.tabbar_rect = tab_storages[it_anim->second.current_position];
    }


    it_anim->second.preview_rect.Min = ImLerp(it_anim->second.preview_rect.Min, it_anim->second.preview_rect_target_pos, c::anim::speed);
    it_anim->second.preview_rect.Max = ImLerp(it_anim->second.preview_rect.Max, it_anim->second.preview_rect.Min + tab_storages[it_anim->second.wanted_position].GetSize(), c::anim::speed);

    //ImGui::ShowStyleEditor();

    ImGui::GetForegroundDrawList()->AddRectFilled(it_anim->second.preview_rect.Min, it_anim->second.preview_rect.Max, ImColor(1.f, 1.f, 1.f, it_anim->second.prereview_rect_alpha), c::bg::rounding);

    ImGui::SetNextWindowPos(it_anim->second.tabbar_rect.Min);
    ImGui::SetNextWindowSize(it_anim->second.tabbar_rect.GetSize());
    Begin("TAB BAR", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoMove);
    {
        const ImVec2& pos = ImGui::GetWindowPos();

        ImGui::PushClipRect(ImVec2(0, 0), ImVec2(4000, 4000), false);
        draw_background_blur(ImGui::GetBackgroundDrawList(), Overlay.swap, Overlay.device, Overlay.context, pos, pos + ImGui::GetWindowSize(), c::bg::rounding, tab_flags[it_anim->second.current_position]);
        ImGui::GetBackgroundDrawList()->AddRectFilled(pos, pos + ImGui::GetWindowSize(), utils::GetColorWithAlpha(c::window_bg_color, c::window_bg_color.Value.w * s.Alpha), c::bg::rounding, tab_flags[it_anim->second.current_position]);
        PopClipRect();

        it_anim->second.prereview_rect_alpha = ImLerp(it_anim->second.prereview_rect_alpha, it_anim->second.drag_drop_enabled ? 0.4f : 0.f, c::anim::speed);
        it_anim->second.prereview_storage_alpha = ImLerp(it_anim->second.prereview_storage_alpha, it_anim->second.drag_drop_enabled ? 0.1f : 0.f, c::anim::speed);

        if (ImGui::GetCurrentWindow()->Rect().Contains(ImGui::GetMousePos()) && ImGui::IsMouseDown(ImGuiMouseButton_Left) && (ImGui::GetIO().MouseDelta.x != 0 || ImGui::GetIO().MouseDelta.y != 0))
        {
            it_anim->second.drag_drop_enabled = true;
        }


        p_tabs->DrawTabs(menu_draw_flags[it_anim->second.current_position] != ImDrawFlags_RoundCornersLeft && menu_draw_flags[it_anim->second.current_position] != ImDrawFlags_RoundCornersRight);

    }ImGui::End();

    ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar
        | ImGuiWindowFlags_NoBringToFrontOnFocus
        | ImGuiWindowFlags_NoResize
        | ImGuiWindowFlags_AlwaysAutoResize
        | ImGuiWindowFlags_NoBackground;

    if (hovered_esp_preview)
        flags |= ImGuiWindowFlags_NoMove;

    ImGui::SetNextWindowSize(c::bg::size);
    Begin("IMGUI MENU MENTALITY V2", nullptr, flags);
    {
        c::anim::speed = ImGui::GetIO().DeltaTime * 12.f;

        c::bg::menu_bb = ImGui::GetCurrentWindow()->Rect();

        const ImVec2& pos = ImGui::GetWindowPos();
        const ImVec2& region = ImGui::GetContentRegionMax();
        const ImVec2& spacing = s.ItemSpacing;

        menu_alpha = ImLerp(menu_alpha, var->c_settings.opened ? 1.f : 0.f, c::anim::speed);

        s.Alpha = menu_alpha;

        draw_background_blur(ImGui::GetWindowDrawList(), Overlay.swap, Overlay.device, Overlay.context, pos, pos + c::bg::size, c::bg::rounding, menu_draw_flags[it_anim->second.current_position]);

        handle_input();

        GetWindowDrawList()->AddRectFilled(pos, pos + c::bg::size, utils::GetColorWithAlpha(c::window_bg_color, c::window_bg_color.Value.w * s.Alpha), c::bg::rounding, menu_draw_flags[it_anim->second.current_position]);
        //GetWindowDrawList()->AddRectFilled(pos, pos + ImVec2(c::bg::size.x, 80), utils::GetColorWithAlpha(c::window_bg_color, c::window_bg_color.Value.w * s.Alpha / 3), c::bg::rounding, ImDrawFlags_RoundCornersTop);

        /*for (int i = 0; i < 3; i++)
            ImGui::GetBackgroundDrawList()->AddShadowRect(ImGui::GetWindowPos(), ImGui::GetWindowPos() + ImGui::GetWindowSize(), ImColor(0.f, 0.f, 0.f, 1.f), 230, ImVec2(0, 0), ImDrawFlags_RoundCornersAll | ImDrawFlags_ShadowCutOutShapeBackground, c::bg::rounding);*/



            //top block
        GetWindowDrawList()->AddRectFilled(pos + ImVec2(0, 60), pos + c::bg::size, utils::GetColorWithAlpha(c::window_bg_color, c::window_bg_color.Value.w / 2), c::bg::rounding, menu_draw_flags[it_anim->second.current_position]);
        //GetWindowDrawList()->AddRectFilled(pos + ImVec2(0, 70), pos + ImVec2(c::bg::size.x, 71), GetColorU32(c::child::stroke));
        // top block

        ImVec2 logo_size(133, 83);

        PushFont(font::inter_bold);
        fade_text(GetWindowDrawList(), "XenoWare External", ImVec2(pos.x + 60, utils::center_text(pos, pos + ImVec2(c::bg::size.x, 60), "MENTALITY v2").y - CalcTextSize("MENTALITY v2").y / 2), c::label::active, c::label::active, 0);
        PopFont();

        fade_text(GetWindowDrawList(), "Best Cheats for Good Price", ImVec2(pos.x + 60, utils::center_text(pos, pos + ImVec2(c::bg::size.x, 60), "Fine-tuning for sure wins").y + CalcTextSize("Fine-tuning for sure wins").y / 2), c::label::defaultt, c::label::defaultt, 0);

        /*PushFont(font::regular_l);
        fade_text(GetWindowDrawList(), ICON_FA_BATTERY_FULL, ImVec2(pos.x + 35, pos.y + 30) - CalcTextSize(ICON_FA_BATTERY_FULL) / 2, c::anim::active, c::dark_color, 0);
        PopFont();*/

        ImGui::GetWindowDrawList()->AddImage(texture::xenoware_logo, pos + ImVec2(5, 5), pos + ImVec2(60, 55));

        ImGui::SetCursorPos(ImVec2(size.x - 95, 15));

        if (custom::InActiveButton(ICON_FA_GEAR, ImVec2(35, 35)))
            settings_popup.open();

        ImGui::SameLine();

        custom::InActiveButton(ICON_FA_XMARK, ImVec2(35, 35));

        ImGui::PushFont(font::inter_semibold);

        //fade_text(GetWindowDrawList(), "MENTALITY", utils::center_text(pos, pos + ImVec2(c::bg::size.x, 50), "MENTALITY"), anim::active, c::dark_color, ImGui::GetTime() / 3);

        ImGui::PopFont();


        {
            UpdateTheme(bTheme, ImGui::GetIO().DeltaTime * 12.f);
            /*GetWindowDrawList()->AddRect(pos, pos + c::bg::size, GetColorU32(c::child::stroke), c::bg::rounding);*/

            //p_tabs->DrawTabs();

            ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2(10.0f, 5.0f)); // 10px горизонтальный отступ, 5px вертикальный

            ImGui::SetCursorPos(ImVec2(10.f, 70 + tab_offset));
            ImGui::BeginChild("FRAMECHILD", ImVec2(1270 * 2 - 40, c::bg::size.y - 85), false, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse);
            {
                ImGuiContext& g = *GImGui;
                ImGuiWindow* window = g.CurrentWindow;

                window->Scroll.x = (p_tabs->GetCurrentScroll());

                if (p_tabs->IsTabActive(0)) {
                    ImGui::BeginGroup(); {
                        custom::Child("Aimbot:Aim Helper", ImVec2(350, ImGui::GetContentRegionAvail().y - ImGui::GetStyle().FramePadding.y * 2) + ImVec2(0, tab_offset), true, 0, 0, ICON_FA_CROSSHAIRS); {

                            if (custom::Featuresbox("Enable Aimbot", &var->c_aimbot.enabled))
                                features_popup.open();

                            static const char* combo_aimbone_list[] = { "Head", "Neck", "Chest", "Pelvis" };
                            static const char* combo_aimprior_list[] = { "Closest to Crosshair", "Closest Distance" };

                            custom::Combo("Aim Bone", &var->c_aimbot.aim_bone, combo_aimbone_list, IM_ARRAYSIZE(combo_aimbone_list));
                            custom::Combo("Aim Priority", &var->c_aimbot.aim_priority, combo_aimprior_list, IM_ARRAYSIZE(combo_aimprior_list));

                            custom::SliderInt("FOV", &var->c_aimbot.fov, 0, 360);
                            custom::SliderInt("Smoothing", &var->c_aimbot.smooth, 1, 20);

                            custom::Checkbox("Visible Check", &var->c_aimbot.visible_check);
                            custom::Checkbox("Draw FOV Circle", &var->c_aimbot.draw_fov);
                            custom::Checkbox("Prediction", &var->c_aimbot.prediction);

                        }
                        custom::EndChild();

                    } ImGui::EndGroup();
                }

                if (p_tabs->IsTabActive(1)) {

                    ImGui::SetCursorPos(ImVec2(735, 0));
                    ImGui::BeginGroup(); {
                        custom::Child("ESP:Esp features", ImVec2(350, ImGui::GetContentRegionAvail().y - ImGui::GetStyle().FramePadding.y * 2), true, 0, false, ICON_FA_EYE); {

                            static const char* combo_boxtype_list[] = { "Corner", "Filled", "Outlined Box" };

                            custom::Checkbox("Player Box", &var->c_esp.player_box);
                            custom::Combo("Box Type", &var->c_esp.box_type, combo_boxtype_list, IM_ARRAYSIZE(combo_boxtype_list));

                            custom::Checkbox("Skeleton ESP", &var->c_esp.skeleton_esp);
                            custom::Checkbox("SnapLines", &var->c_esp.snaplines);
                            custom::Checkbox("Distance", &var->c_esp.distance);
                            custom::Checkbox("Username", &var->c_esp.username);
                            custom::Checkbox("Platform", &var->c_esp.platform);
                            custom::Checkbox("Weapon", &var->c_esp.weapon);
                            custom::Checkbox("Rank", &var->c_esp.rank);

                            custom::SliderInt("ESP Distance", &var->c_esp.esp_distance, 0, 1000);
                            custom::SliderInt("Text size", &var->c_esp.text_size, 1, 10);

                            custom::ColorEdit4("Box Visible Color", var->c_esp.box_vis_col, picker_flags);
                            custom::ColorEdit4("Box InVisible Color", var->c_esp.box_invis_col, picker_flags);

                            custom::ColorEdit4("Skeleton Visible Color", var->c_esp.skel_vis_col, picker_flags);
                            custom::ColorEdit4("Skeleton InVisible Color", var->c_esp.skel_invis_col, picker_flags);

                        }
                        custom::EndChild();
                    }
                    ImGui::EndGroup();
                }

                if (p_tabs->IsTabActive(2)) {

                    ImGui::SetCursorPos(ImVec2(735 * 2, 0));
                    ImGui::BeginGroup(); {
                        custom::Child("World ESP:World Objects ESP", ImVec2(350, ImGui::GetContentRegionAvail().y - ImGui::GetStyle().FramePadding.y * 2), true, 0, false, ICON_FA_GLOBE); {

                            custom::Checkbox("World ESP", &var->c_world.world_esp);
                            custom::Checkbox("Uncommon Loot", &var->c_world.uncommon_loot);
                            custom::Checkbox("Common Loot", &var->c_world.common_loot);
                            custom::Checkbox("Rare Loot", &var->c_world.rare_loot);
                            custom::Checkbox("Epic Loot", &var->c_world.epic_loot);
                            custom::Checkbox("Legendary Loot", &var->c_world.legendary_loot);
                            custom::Checkbox("Mythic Loot", &var->c_world.mythical_loot);
                            custom::Checkbox("Exotic Loot", &var->c_world.exotic_loot);
                            custom::Checkbox("Chests", &var->c_world.chests);
                            custom::Checkbox("Ammo", &var->c_world.ammo);
                            custom::Checkbox("Llamas", &var->c_world.llamas);
                            custom::Checkbox("Supply Drop", &var->c_world.supply_drop);
                            custom::Checkbox("Chicken", &var->c_world.chicken);

                            custom::SliderInt("Render Distance", &var->c_world.render_distance, 0, 1000);
                            custom::SliderInt("Loot Distance", &var->c_world.loot_distance, 0, 1000);

                        }
                        custom::EndChild();
                    }
                    ImGui::EndGroup();
                }

                if (p_tabs->IsTabActive(3)) {

                    ImGui::SetCursorPos(ImVec2(735 * 3, 0));
                    ImGui::BeginGroup(); {
                        custom::Child("Exploits:Miscellaneous Exploitation", ImVec2(350, ImGui::GetContentRegionAvail().y - ImGui::GetStyle().FramePadding.y * 2), true, 0, false, ICON_FA_BOMB); {

                            custom::Checkbox("Bullet Teleport", &var->c_exploits.bullet_teleport);
                            custom::Checkbox("No Spread", &var->c_exploits.no_spread);
                            custom::Checkbox("ADS in Air", &var->c_exploits.ads_in_air);
                            custom::Checkbox("Car Fly", &var->c_exploits.car_fly);
                            custom::Checkbox("Car Speed Mod", &var->c_exploits.car_speed_mod);
                            custom::Checkbox("Car Gravity Mod", &var->c_exploits.car_gravity_mod);
                            custom::Checkbox("Speed Hack", &var->c_exploits.speed_hack);

                        }
                        custom::EndChild();
                    }
                    ImGui::EndGroup();
                }

                if (p_tabs->IsTabActive(4)) {

                    ImGui::SetCursorPos(ImVec2(735 * 4, 0));
                    ImGui::BeginGroup(); {
                        custom::Child("Config:Config", ImVec2(350, ImGui::GetContentRegionAvail().y - ImGui::GetStyle().FramePadding.y * 2), true, 0, false, ICON_FA_FILE); {



                        }
                        custom::EndChild();
                    }
                    ImGui::EndGroup();
                }

                if (p_tabs->IsTabActive(5)) {

                    ImGui::SetCursorPos(ImVec2(735 * 5, 0));
                    ImGui::BeginGroup(); {
                        custom::Child("Settings:Settings", ImVec2(350, ImGui::GetContentRegionAvail().y - ImGui::GetStyle().FramePadding.y * 2), true, 0, false, ICON_FA_GEAR); {

                            static bool   checkboxes[2] = {};

                            custom::Checkbox("V-Sync", &var->c_settings.vsync);
                            custom::Checkbox("Streamproof Mode", &var->c_settings.streamproof);

                            ImGui::Text("Press INSERT to toggle menu");
                            ImGui::Text("Version 1.0.0");
                            ImGui::Text((std::string("FPS: ") + std::to_string((int)ImGui::GetIO().Framerate)).c_str());

                        }
                        custom::EndChild();
                    }
                    ImGui::EndGroup();
                }
            }
            ImGui::EndChild(); ImGui::PopStyleVar(1);

        }
        p_notif.Render();

        if (features_popup.begin(300.0f))
        {
            // Внутри попапа рисуем свою сетку
            //ShowAccessoryGrid(data, ImColor(1.0f, 1.0f, 1.0f, 1.0f));

            // Закрывающая кнопка внизу попапа

            custom::MiniBind("keybind mini", &var->c_aimbot.keybind, &var->c_aimbot.keybind_mode);

            custom::ToggleButton("Toggle", "Hold", &var->c_aimbot.toggle_or_hold, ImVec2(ImGui::GetContentRegionAvail().x, 40));
            custom::ToggleButton("Memory", "Mouse", &var->c_aimbot.memory_or_mouse, ImVec2(ImGui::GetContentRegionAvail().x, 40));

            if (custom::Button("Close", ImVec2(ImGui::GetContentRegionAvail().x, 40)))
                features_popup.close();


            features_popup.end();
        }

        if (settings_popup.begin(340.0f))
        {
            // Внутри попапа рисуем свою сетку
            //ShowAccessoryGrid(data, ImColor(1.0f, 1.0f, 1.0f, 1.0f));

            // Закрывающая кнопка внизу попапа

            custom::ColorEdit4(c::lang ? "第一渐变色" : "First gradient color", (float*)&c::anim::active, picker_flags);
            custom::ColorEdit4(c::lang ? "子一渐变色" : "Second gradient color", (float*)&c::dark_color, picker_flags);

            const char* offset_sides[] = { ICON_FA_ARROW_ROTATE_LEFT " From the left", ICON_FA_ARROW_ROTATE_RIGHT " From the right" };
            const char* font_weights[] = { "Regular", "Medium", "Semibold" };

            ImFont* deafult_fonts[] = { font::default_r, font::default_m, font::default_s };

            custom::Combo(c::lang ? "启用透视" : "Font weight", &c::selected_font, font_weights, IM_ARRAYSIZE(font_weights));


            ImGui::GetIO().FontDefault = deafult_fonts[c::selected_font];


            custom::Combo(c::lang ? "启用透视" : "Animation side", &c::anim_offset_side, offset_sides, IM_ARRAYSIZE(offset_sides));

            custom::ToggleButton(ICON_FA_SUN, ICON_FA_MOON, &bTheme, ImVec2(ImGui::GetContentRegionAvail().x, 40));

            if (custom::Button("Save", ImVec2(ImGui::GetContentRegionAvail().x, 50)))
                settings_popup.close();


            features_popup.end();
        }

        if (vehicle_popup.begin(340.0f))
        {
            static const char* car_models[] = {
                "Ford Mustang",
                "Chevrolet Camaro",
                "Dodge Charger",
                "BMW M3",
                "Audi R8",
                "Porsche 911",
                "Ferrari 488",
                "Lamborghini Huracán",
                "McLaren 720S",
                "Tesla Model S",
                "Nissan GT-R",
                "Mercedes-AMG GT",
                "Aston Martin DB11",
                "Chevrolet Corvette",
                "Jaguar F-Type"
            };

            static bool car_box[15] = { false };

            for (int i = 0; i < IM_ARRAYSIZE(car_models); i++)
            {
                custom::Checkbox(car_models[i], &car_box[i]);
            }
            if (custom::Button("Close", ImVec2(ImGui::GetContentRegionAvail().x, 40)))
                vehicle_popup.close();


            vehicle_popup.end();
        }

        //particle::RenderEffects(ImGui::GetForegroundDrawList(), ImVec2(1, 1), 2.f);
    }
    End();
}

static inline void RenderLoop() {
    constexpr float clearColor[4] = { 0.f, 0.f, 0.f, 0.f };
    MSG msg{};

    //ImGuiIO& io = ImGui::GetIO(); (void)io;

    tabs_info[0] = { {ICON_FA_CROSSHAIRS, ICON_FA_EYE, ICON_FA_GLOBE, ICON_FA_BOMB, ICON_FA_FILE, ICON_FA_GEAR  }, { "Aimbot", "Visuals", "World ESP", "Exploits", "Config", "Settings" } };
    p_tabs = new c_tabs(tabs_info);

    while (msg.message != WM_QUIT) {
        while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        auto& io = ImGui::GetIO();

        io.DeltaTime = 1.f / 60.f;

        if (GetAsyncKeyState(VK_INSERT) & 1)
            var->c_settings.opened = !var->c_settings.opened;


        if (var->c_settings.opened) {
            POINT cur{};
            GetCursorPos(&cur);
            io.MousePos = ImVec2(static_cast<float>(cur.x), static_cast<float>(cur.y));

            // Wszystkie przyciski myszy
            io.MouseDown[0] = (GetAsyncKeyState(VK_LBUTTON) & 0x8000) != 0;  // Lewy
            io.MouseDown[1] = (GetAsyncKeyState(VK_RBUTTON) & 0x8000) != 0;  // Prawy
            io.MouseDown[2] = (GetAsyncKeyState(VK_MBUTTON) & 0x8000) != 0;  // Środkowy
            io.MouseDown[3] = (GetAsyncKeyState(VK_XBUTTON1) & 0x8000) != 0; // X1
            io.MouseDown[4] = (GetAsyncKeyState(VK_XBUTTON2) & 0x8000) != 0; // X2

            // Klawiatura - wszystkie klawisze (0-255)
            for (int i = 0; i < 256; i++) {
                io.KeysDown[i] = (GetAsyncKeyState(i) & 0x8000) != 0;
            }

            // Modyfikatory klawiatury
            io.KeyCtrl = (GetAsyncKeyState(VK_CONTROL) & 0x8000) != 0;
            io.KeyShift = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
            io.KeyAlt = (GetAsyncKeyState(VK_MENU) & 0x8000) != 0;
            io.KeySuper = false; // Windows key (opcjonalnie)
        }

        ImGui_ImplDX11_NewFrame();
        ImGui_ImplWin32_NewFrame();
        ImGui::NewFrame();

        //LoadImages();

        UpdateFloatWithLerp(tab_is_changed, tab_offset, 0.f, 600.f);

        ActorLoop();

        //std::cout << "render\n";
        if (var->c_settings.opened)
            DrawMenu();

        auto text = skCrypt("DC: chxnzz. IF PURCHASED = SCAMMED");
        ImGui::GetBackgroundDrawList()->AddText(ImVec2(100, 100), ImColor(255, 0, 0), text.decrypt());
        text.encrypt();

        ImGui::Render();
        Overlay.context->OMSetRenderTargets(1, &Overlay.rtv, nullptr);
        Overlay.context->ClearRenderTargetView(Overlay.rtv, clearColor);
        ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
        Overlay.swap->Present(settings::ui.vsync, 0);
    }

    ImGui_ImplDX11_Shutdown();
    ImGui_ImplWin32_Shutdown();
    ImGui::DestroyContext();
}

static inline void StartOverlay() {
    AttachDiscordOverlay();
    InitializeD3D();
    RenderLoop();
}