# Threads setup.
#
# When cross-compiling against a hand-assembled Debian sysroot, CMake's FindThreads
# is unreliable: pthread.h lives in <sysroot>/usr/include (not the multiarch dir),
# and its try_compile probe does not consistently see it. Rather than fight that,
# we provide Threads::Threads directly with -pthread, which covers both the compile
# and link steps on glibc.
#
# Important: do NOT add <sysroot>/usr/include to the target's include dirs here.
# That would propagate it as a system include to every consumer (spdlog, lws, ...)
# and breaks <linux/*.h> -> <asm/*.h> resolution. Header search is owned solely by
# the toolchain file (-isystem <multiarch> + -idirafter usr/include).
function(joyinside_setup_threads)
    if(TARGET Threads::Threads)
        return()
    endif()

    if(CMAKE_CROSSCOMPILING AND CMAKE_SYSROOT)
        add_library(Threads::Threads INTERFACE IMPORTED GLOBAL)
        set_target_properties(Threads::Threads PROPERTIES
            INTERFACE_COMPILE_OPTIONS "-pthread"
            INTERFACE_LINK_OPTIONS "-pthread")
        set(Threads_FOUND TRUE CACHE BOOL "" FORCE)
        set(CMAKE_THREAD_LIBS_INIT "-pthread" CACHE STRING "" FORCE)
        set(CMAKE_USE_PTHREADS_INIT 1 CACHE STRING "" FORCE)
        message(STATUS "Threads: cross sysroot, using -pthread")
        return()
    endif()

    find_package(Threads REQUIRED)
endfunction()
