cmake_minimum_required(VERSION 3.10)
project(imgui_wrapper NONE)

# Root of the imgui submodule (expected to live at external/imgui)
set(IMGUI_ROOT "${CMAKE_SOURCE_DIR}/external/imgui")

if(NOT EXISTS "${IMGUI_ROOT}/imgui.h")
    message(FATAL_ERROR "ImGui not found in ${IMGUI_ROOT}. Run: git submodule update --init --recursive")
endif()

# Options: build demo and/or backends. By default we only build the core library which
# avoids pulling in platform deps (SDL/Android/etc) from the backends and examples.
option(IMGUI_BUILD_DEMO "Include imgui_demo.cpp in the build" OFF)
option(IMGUI_BUILD_BACKENDS "Include selected backend implementations from backends/" OFF)

# Core sources (explicit list - avoids accidentally including examples)
set(IMGUI_CORE_SRC
    "${IMGUI_ROOT}/imgui.cpp"
    "${IMGUI_ROOT}/imgui_draw.cpp"
    "${IMGUI_ROOT}/imgui_tables.cpp"
    "${IMGUI_ROOT}/imgui_widgets.cpp"
)

if(IMGUI_BUILD_DEMO)
    list(APPEND IMGUI_CORE_SRC "${IMGUI_ROOT}/imgui_demo.cpp")
endif()

add_library(imgui STATIC ${IMGUI_CORE_SRC})

target_include_directories(imgui PUBLIC
    ${IMGUI_ROOT}
)

# Optionally include a small, safe set of backends (desktop common ones) when requested.
if(IMGUI_BUILD_BACKENDS)
    # Gather backend sources and whitelist a few common desktop backends
    file(GLOB IMGUI_BACKEND_SRCS "${IMGUI_ROOT}/backends/*.cpp")

    set(IMGUI_BACKEND_WHITELIST
        "imgui_impl_glfw.cpp"
        "imgui_impl_opengl3.cpp"
        "imgui_impl_win32.cpp"
        "imgui_impl_sdl2.cpp"
    )

    set(IMGUI_SELECTED_BACKENDS)
    foreach(_f IN LISTS IMGUI_BACKEND_SRCS)
        get_filename_component(_name ${_f} NAME)
        foreach(_allowed IN LISTS IMGUI_BACKEND_WHITELIST)
            if(_name STREQUAL _allowed)
                list(APPEND IMGUI_SELECTED_BACKENDS ${_f})
            endif()
        endforeach()
    endforeach()

    if(IMGUI_SELECTED_BACKENDS)
        target_sources(imgui PRIVATE ${IMGUI_SELECTED_BACKENDS})
        target_include_directories(imgui PUBLIC "${IMGUI_ROOT}/backends")
    endif()
endif()

# Build position independent code to make static lib usable in shared contexts
set_target_properties(imgui PROPERTIES POSITION_INDEPENDENT_CODE ON)