#include "../Menu.h"
#include "raylib.h"
#include "../../Initialization/Initialization.h"
#include "../../Backend/Font/FontManager.h"
#include "../../Backend/Network/NetworkClient.h"
#include <thread>
#include <mutex>

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

void menu::Connect::DrawConnectMenu() {
    auto* font = Font::Get();
    RLVector2 Win_size = Initialization::Get()->Get_WinSize();
    auto* ui = Framework::Get();

    // ── Trigger status check on first frame ─────────
    if (!m_connecting && !m_statusChecked) {
        m_connecting = true;
        m_startTime = RLGetTime();
        m_statusPending = true;

        // Spawn detached thread for server status check
        std::thread([](Connect* self) {
            auto result = NetworkClient::Get()->CheckStatus();

            std::lock_guard<std::mutex> lock(self->m_mutex);
            if (result.online) {
                self->m_connected = true;
            } else {
                self->m_statusError = result.errorMessage;
            }
            self->m_statusPending = false;
            self->m_statusChecked = true;
        }, this).detach();
    }

    // ── Check completion ────────────────────────────
    {
        std::lock_guard<std::mutex> lock(m_mutex);
        if (m_connected) {
            // Connected — flow will advance to Login on next frame
            return;
        }
    }

    // ── Pulsing "Connecting..." animation ───────────
    double elapsed = RLGetTime() - m_startTime;
    float alpha = (float)(25 + (sin(elapsed * 2.5) + 1.0) * 0.5 * 180.0);

    if (m_statusPending) {
        auto size = font->MeasureText("Connecting...", 18);
        font->DrawTextEX("Connecting...",
            { (Win_size.x - size.x) / 2, (Win_size.y - size.y) / 2 },
            18, { 250, 250, 250, (unsigned char)alpha }, 2);
    }

    // ── Error state + retry/exit ────────────────────
    {
        std::lock_guard<std::mutex> lock(m_mutex);
        if (!m_statusPending && m_statusChecked && !m_connected) {
            auto errSize = font->MeasureText(m_statusError.c_str(), 14);
            font->DrawTextEX(m_statusError.c_str(),
                { (Win_size.x - errSize.x) / 2, (Win_size.y - errSize.y) / 2 - 40 },
                14, { 255, 80, 80, 255 }, 2);

            // Retry button
            if (ui->Button("Retry", { (Win_size.x - 120) / 2, (Win_size.y - 35) / 2 + 10, 120, 35 })) {
                m_statusChecked = false;
                m_statusError.clear();
                m_connecting = false;
            }
        }

        // Exit button always shown during connect
        if (!m_connected) {
            if (ui->Button("Exit", { (Win_size.x - 120) / 2, (Win_size.y - 35) / 2 + 55, 120, 35 })) {
                Initialization::Get()->RequestClose();
            }
        }
    }
}
