cmake_minimum_required(VERSION 3.10)
project(rlImGui_wrapper NONE)

# Path to the rlImGui sources (submodule should be under external/rlImGui)
set(RLIMGUI_ROOT "${CMAKE_SOURCE_DIR}/external/rlImGui")

if(NOT EXISTS "${RLIMGUI_ROOT}/README.md")
    message(FATAL_ERROR "rlImGui not found in ${RLIMGUI_ROOT}. Add it as a submodule: git submodule add <url> external/rlImGui")
endif()

# Collect sources - rlImGui has sources under src/ and maybe example/backends

# Look for sources either under src/ or at the project root
file(GLOB RLIMGUI_ROOT_SRCS "${RLIMGUI_ROOT}/*.c" "${RLIMGUI_ROOT}/*.cpp")
file(GLOB RLIMGUI_SRC_DIR_SRCS "${RLIMGUI_ROOT}/src/*.c" "${RLIMGUI_ROOT}/src/*.cpp")

set(RLIMGUI_SOURCES ${RLIMGUI_ROOT_SRCS} ${RLIMGUI_SRC_DIR_SRCS})

# Exclude examples/tests if present
list(FILTER RLIMGUI_SOURCES EXCLUDE REGEX ".*example.*|.*test.*")

if(RLIMGUI_SOURCES)
    add_library(rlImGui STATIC ${RLIMGUI_SOURCES})

    # Add includes: rlImGui root and src if present
    target_include_directories(rlImGui PUBLIC
        ${RLIMGUI_ROOT}
        ${RLIMGUI_ROOT}/src
    )

    # Ensure ImGui's headers are available (imgui submodule expected at external/imgui)
    set(IMGUI_ROOT "${CMAKE_SOURCE_DIR}/external/imgui")
    if(EXISTS "${IMGUI_ROOT}/imgui.h")
        target_include_directories(rlImGui PUBLIC ${IMGUI_ROOT})
    endif()

    # If the imgui target exists (from cmake/imgui wrapper), link it so we reuse the same lib
    if(TARGET imgui)
        target_link_libraries(rlImGui PRIVATE imgui)
    endif()
else()
    message(FATAL_ERROR "No rlImGui sources found under ${RLIMGUI_ROOT}. Expected rlImGui.cpp or src/*.cpp")
endif()

# Provide a property so consumers can check availability
set_target_properties(rlImGui PROPERTIES EXPORT_NAME rlImGui)

# Try to link to raylib if available in the parent project
if(TARGET raylib)
    target_link_libraries(rlImGui PRIVATE raylib)
endif()
