# FindGlad.cmake - Find or configure the GLAD OpenGL loader
#
# This module looks for glad in the third_party/glad directory (pre-generated).
# It creates a static library target glad::glad.
#
# Inputs:
#   GLAD_DIR  - Path to glad root (contains include/ and src/)
#
# Outputs:
#   Glad_FOUND
#   Glad::Glad  (imported INTERFACE/STATIC target)

if(NOT GLAD_DIR)
    set(GLAD_DIR "${CMAKE_SOURCE_DIR}/third_party/glad")
endif()

find_path(GLAD_INCLUDE_DIR
    NAMES glad/gl.h
    PATHS "${GLAD_DIR}/include"
    NO_DEFAULT_PATH
)

find_file(GLAD_SOURCE
    NAMES gl.c
    PATHS "${GLAD_DIR}/src"
    NO_DEFAULT_PATH
)

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Glad
    REQUIRED_VARS GLAD_INCLUDE_DIR GLAD_SOURCE
)

if(Glad_FOUND AND NOT TARGET Glad::Glad)
    add_library(glad_impl STATIC "${GLAD_SOURCE}")

    # The project enables only CXX; tell CMake that glad's C source
    # should be compiled as C and linked with the C linker.
    set_source_files_properties("${GLAD_SOURCE}" PROPERTIES LANGUAGE C)
    set_target_properties(glad_impl PROPERTIES LINKER_LANGUAGE C)

    target_include_directories(glad_impl PUBLIC "${GLAD_INCLUDE_DIR}")
    # glad needs opengl32 on Windows
    if(WIN32)
        target_link_libraries(glad_impl PUBLIC opengl32)
    else()
        find_package(OpenGL REQUIRED)
        target_link_libraries(glad_impl PUBLIC OpenGL::GL)
    endif()

    add_library(Glad::Glad ALIAS glad_impl)
    message(STATUS "Glad found: ${GLAD_INCLUDE_DIR}")
endif()
