# FindImgui.cmake
# Finds ImGui library and sets up compilation
#
# This module defines:
#  Imgui_FOUND - System has ImGui
#  Imgui_INCLUDE_DIRS - ImGui include directories
#  Imgui_SOURCES - ImGui source files to compile
#  Imgui::Imgui - Imported target for ImGui

# Find ImGui directory
find_path(Imgui_DIR
    NAMES imgui.h
    PATHS
        ${IMGUI_DIR}
        ${CMAKE_SOURCE_DIR}/third_party/imgui-1.92.7
        ${CMAKE_SOURCE_DIR}/third_party/imgui
    DOC "ImGui root directory"
)

if(Imgui_DIR)
    set(Imgui_INCLUDE_DIRS 
        ${Imgui_DIR}
        ${Imgui_DIR}/backends
    )
    
    # Core ImGui source files
    set(Imgui_SOURCES
        ${Imgui_DIR}/imgui.cpp
        ${Imgui_DIR}/imgui_draw.cpp
        ${Imgui_DIR}/imgui_tables.cpp
        ${Imgui_DIR}/imgui_widgets.cpp
        ${Imgui_DIR}/imgui_demo.cpp
    )
    
    # Backend source files for Win32 + OpenGL3
    list(APPEND Imgui_SOURCES
        ${Imgui_DIR}/backends/imgui_impl_win32.cpp
        ${Imgui_DIR}/backends/imgui_impl_opengl3.cpp
    )
    
    set(Imgui_FOUND TRUE)
endif()

# Handle standard find_package arguments
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Imgui
    REQUIRED_VARS
        Imgui_DIR
        Imgui_INCLUDE_DIRS
        Imgui_SOURCES
)

if(Imgui_FOUND)
    # Create imported target
    if(NOT TARGET Imgui::Imgui)
        # Create the actual library target first
        add_library(imgui_lib STATIC ${Imgui_SOURCES})
        target_include_directories(imgui_lib PUBLIC ${Imgui_INCLUDE_DIRS})
        
        # Link against Windows libraries for Win32 backend and OpenGL
        target_link_libraries(imgui_lib PUBLIC
            opengl32
            gdi32
            dwmapi
            imm32
        )
        
        # Enable docking support
        # target_compile_definitions(imgui_lib PUBLIC IMGUI_HAS_DOCK)

        # Set C++ standard
        target_compile_features(imgui_lib PUBLIC cxx_std_17)
        
        # Create an alias with the :: namespace
        add_library(Imgui::Imgui ALIAS imgui_lib)
    endif()
    
    message(STATUS "Found ImGui: ${Imgui_DIR}")
endif()

mark_as_advanced(
    Imgui_DIR
)
