#include <Core/HAL/Display/Display.h>
#include <Core/ImGui/ImGuiService.h>
#include <Core/Memory/MemoryArena.h>
#include <cstdio>
#include <Graphics/Graphics.h>
#include <imgui.h>
#include <Juliet.h>

namespace Juliet::UnitTest
{
    void TestImGui()
    {
#ifdef JULIET_ENABLE_IMGUI
        ImGuiContext* ctx = ImGuiService::GetContext();

        if (ImGui::GetCurrentContext() != ctx)
        {
            printf("WARN: Context Mismatch! Service=%p, Current=%p. Fixing...\n", (void*)ctx, (void*)ImGui::GetCurrentContext());
            ImGui::SetCurrentContext(ctx);
        }
        Assert(ImGui::GetCurrentContext() == ctx);
        (void)ctx;
        printf("TestImGui: Context Verified.\n");

        ImGuiIO& io = ImGui::GetIO();
        Assert(io.BackendPlatformName != nullptr);
        printf("TestImGui: IO Verified. Backend: %s\n", io.BackendPlatformName);

        Assert(ImGui::GetVersion() != nullptr);
        printf("TestImGui: Version Verified: %s\n", ImGui::GetVersion());

        Assert(io.Fonts != nullptr);
        printf("TestImGui: Fonts Verified.\n");

        bool built = io.Fonts->IsBuilt();
        Assert(built);
        printf("TestImGui: Fonts Built Status: %d\n", built);

        unsigned char* pixels;
        int            width, height;
        io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
        Assert(pixels != nullptr);
        Assert(width > 0 && height > 0);
        (void)pixels;
        (void)width;
        (void)height;
        printf("TestImGui: Font Atlas Verified.\n");

        // 6. Verify Style
        ImGuiStyle& style = ImGui::GetStyle();
        Assert(style.Alpha > 0.0f);
        (void)style;
        printf("TestImGui: Style Verified.\n");

        // 7. Test New Frame
        Assert(ImGuiService::IsInitialized());

        // Simulate a frame
        if (io.DisplaySize.x <= 0.0f || io.DisplaySize.y <= 0.0f)
        {
            io.DisplaySize = ImVec2(1920, 1080);
        }
        io.DeltaTime = 1.0f / 60.0f;
        printf("TestImGui: About to DrawList check.\n");

        // 8. Check Draw List Access
        ImDrawList* drawList = ImGui::GetForegroundDrawList();
        Assert(drawList != nullptr);
        (void)drawList;

        printf("ImGui tests passed (Exhaustive).\n");
#endif
    }
} // namespace Juliet::UnitTest
