# The GLFW adapter: the reference host for the library. It owns the window, the
# context and the loop, and translates GLFW's events into plot::input events.
#
# Dependency discovery follows the design spec's order: find_package first,
# pkg-config next, FetchContent only when neither can supply GLFW (the last
# resort, because it needs the network).
set(plot_glfw_dep "")

find_package(glfw3 3.3 QUIET)
if(TARGET glfw)
  set(plot_glfw_dep glfw)
elseif(TARGET glfw3::glfw3)
  set(plot_glfw_dep glfw3::glfw3)
endif()

if(NOT plot_glfw_dep)
  find_package(PkgConfig QUIET)
  if(PkgConfig_FOUND)
    pkg_check_modules(GLFW_PC QUIET IMPORTED_TARGET glfw3)
    if(TARGET PkgConfig::GLFW_PC)
      set(plot_glfw_dep PkgConfig::GLFW_PC)
    endif()
  endif()
endif()

if(NOT plot_glfw_dep)
  message(STATUS "plot: glfw3 not found via find_package or pkg-config; fetching it")
  include(FetchContent)
  set(GLFW_BUILD_DOCS OFF CACHE BOOL "" FORCE)
  set(GLFW_BUILD_TESTS OFF CACHE BOOL "" FORCE)
  set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
  set(GLFW_INSTALL OFF CACHE BOOL "" FORCE)
  FetchContent_Declare(glfw
    GIT_REPOSITORY https://github.com/glfw/glfw.git
    GIT_TAG 3.4
    GIT_SHALLOW TRUE)
  FetchContent_MakeAvailable(glfw)
  set(plot_glfw_dep glfw)
endif()

message(STATUS "plot: GLFW adapter dependency: ${plot_glfw_dep}")

add_library(plot_glfw STATIC glfw_host.cpp)
add_library(plot::glfw ALIAS plot_glfw)
# The public include root is `adapters/`, so the header is reached as
# <glfw/glfw_host.hpp> -- the toolkit's name first, like every other adapter's.
target_include_directories(plot_glfw PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/..")
# GLFW stays PRIVATE: the header forward-declares GLFWwindow and includes no GLFW
# header, so a consumer of plot::glfw does not inherit the toolkit.
target_link_libraries(plot_glfw PUBLIC plot::core PRIVATE ${plot_glfw_dep})
plot_apply_warnings(plot_glfw)
