#include "../Menu.h"
#include "../../Backend/Image.h"
#include "../../Initialization/Initialization.h"
#include "../../Backend/Font/FontManager.h"
#include "../../Backend/TokenStore/TokenStore.h"
#include "../../Backend/Network/NetworkClient.h"
#include "../../Backend/Steam/Steam.h"
#include <iostream>
#include <chrono>
#include <thread>

menu::Load* menu::Load::Get() {
    static Load instance;
    return &instance;
}

static RLTexture2D GetCsTexture() {
    static RLTexture2D tex = []() {
        RLImage img = RLLoadImageFromMemory(".png", CSTexture, sizeof(CSTexture));
        RLTexture2D t = RLLoadTextureFromImage(img);
        RLUnloadImage(img);
        return t;
    }();
    return tex;
}

static void DrawImage(RLTexture2D texture, RLRectangle dest, RLColor tint = {255, 255, 255, 255}) {
    RLRectangle src = {0, 0, (float)texture.width, (float)texture.height};
    RLDrawTexturePro(texture, src, dest, {0, 0}, 0, tint);
}

static void DoLogout() {
    auto* login = menu::Login::Get();
    auto* connect = menu::Connect::Get();
    auto* load = menu::Load::Get();

    // Clear local session (server token expires after 7 days naturally)
    TokenStore::Get()->Clear();
    login->Reset();
    connect->Reset();
    load->Reset();

    Menu::Get()->ClearLogs();
    Menu::Get()->SetAutoLoginDone(false);
}

void menu::Load::bgDraw() const {
    auto win_size = Initialization::Get()->Get_WinSize();
    RLDrawRectangleLines(Rect.x, Rect.y, Rect.width + 15, Rect.height, RLColor{ 0, 0, 0, 255 });
    RLDrawRectangle(Rect.x + 1, Rect.y + 1, Rect.width - 2 + 15, Rect.height - 2, RLColor{ 35, 35, 35, 255 });

    RLDrawRectangleLines(Rect.x + Rect.width + 8 + 15, Rect.y, Rect.width - 6 - 15, Rect.height, RLColor{ 0, 0, 0, 255 });
    RLDrawRectangle(Rect.x + Rect.width + 8 + 1 + 15, Rect.y + 1, Rect.width - 8 - 15, Rect.height - 2, RLColor{ 23, 23, 23, 255 });

    RLDrawRectangleLines(Rect.x, Rect.y + Rect.height + 8, win_size.x - (Rect.x * 2), win_size.y - (Rect.y + Rect.height + 18), RLColor{ 0, 0, 0, 255 });
    RLDrawRectangle(Rect.x + 1, Rect.y + Rect.height + 9, win_size.x - (Rect.x * 2) - 2, win_size.y - (Rect.y + Rect.height + 18) - 2, RLColor{ 35, 35, 35, 255 });
}

void menu::Load::DrawLoadMenu() {
    auto username = Login::Get()->GetDisplayName();
    auto Log = Menu::Get();
    if (!m_welcomeShown) {
        Log->AddLog("Welcome back, " + username);
        m_welcomeShown = true;
    }

    auto* font = Font::Get();
    auto Win_size = Initialization::Get()->Get_WinSize();
    auto* ui = Framework::Get();
    bgDraw();

    bool Cs_button = ui->Toggle(NULL, { Rect.x, Rect.y, Rect.width + 15, Rect.height / 2 - 11 }, &is_cstoggle);
    DrawImage(GetCsTexture(), { Rect.x + 6, Rect.y + 6, 41.5, 42 }, is_cstoggle? RLColor{ 255,255,255,255 }:RLColor{155,155,155,255});
    font->DrawTextEX("Counter-Strike Global Offensive", { Rect.x + 6 + 45, Rect.y + 6 }, 18, is_cstoggle ? RLColor{ 80, 118, 23, 255} : RLColor{ 120, 120, 120, 255 }, -1);
    font->DrawTextEX("Updated 2023/03/24 13:32", { Rect.x + 6 + 45, Rect.y + 6 + font->MeasureText("Updated 2023/03/24 13:32", 17, -1).y}, 17, is_cstoggle ? RLColor{ 220, 220, 220, 255 } : RLColor{ 120, 120, 120, 255 }, -1);

    if (Cs_button){
        Log->ClearLogs();
        m_welcomeShown = false;
    }

    // ── Load button ─────────────────────────────────
    if (ui->Button("Load", { Rect.x + Rect.width + 17 + 15, Rect.y + 9, Rect.width - 24 - 15, 53 }, Load_lock) && !Load_lock) {
        if (!is_cstoggle) {
            Log->AddLog("Please select game!");
        }
        else {
            Log->AddLog("Injector...");
            auto Init = Initialization::Get();

            if (Init->GetFailedToFindPattern())
                std::thread([](Load* self) {
                    auto SteamMgr = Steam::Get();
                    SteamMgr->ReplaceOverlayFiles();
                }, this).detach();
            std::thread([](Load* self) {
                std::this_thread::sleep_for(std::chrono::milliseconds(1500));
                self->m_injecting = true;
            }, this).detach();
        }
    }

    // ── Logout button ───────────────────────────────
    //if (ui->Button("Logout", { Rect.x + Rect.width + 17 + 15, Rect.y + 9 + 33 + 6, Rect.width - 24 - 15, 25 })) {
    //    DoLogout();
    //    return;  // Immediately rendered Connect on next frame
    //}

    // ── Exit button ─────────────────────────────────
    if (ui->Button("Exit", { Rect.x + Rect.width + 17 + 15, Rect.y + 9 + 53 + 9, Rect.width - 24 - 15, 53 }))
        Initialization::Get()->RequestClose();

    // Log area with auto-scroll: clip to the log rectangle, then offset Y
    // so the bottom of the text stays visible when it overflows.
    {
        const RLRectangle logArea = {
            Rect.x + 6,
            Rect.y + Rect.height + 14,
            Win_size.x - (Rect.x * 2) - 12,
            Win_size.y - (Rect.y + Rect.height + 18) - 2
        };
        const auto& logText = Log->GetLogs();
        if (!logText.empty()) {
            constexpr int fontSize = 18;
            const char* text = logText.c_str();
            const RLVector2 textSize = font->MeasureText(text, fontSize, 0);
            const bool overflow = textSize.y > logArea.height;
            if (overflow)
                RLBeginScissorMode((int)logArea.x, (int)logArea.y, (int)logArea.width, (int)logArea.height);
            const float offsetY = overflow ? textSize.y - logArea.height : 0.0f;
            ui->Label(text, {Rect.x + 6, Rect.y + Rect.height + 12 - offsetY}, fontSize);
            if (overflow)
                RLEndScissorMode();
        }
    }
}
