
if(NOT EMSCRIPTEN)
    message(FATAL_ERROR
        "wasm/CMakeLists.txt requires the Emscripten toolchain. "
        "Use: cmake --preset wasm  (after activating emsdk).")
endif()

add_executable(hello hello.cpp)

set_target_properties(hello PROPERTIES
    OUTPUT_NAME "hello"
    SUFFIX ".mjs"
    RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)

target_link_options(hello PRIVATE
    "-sMODULARIZE=1"
    "-sEXPORT_ES6=1"
    "-sENVIRONMENT=node,web"
    "-sEXPORTED_FUNCTIONS=['_add','_hello_version']"
    "-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap']"
    "-sALLOW_MEMORY_GROWTH=1"
)

target_compile_features(hello PRIVATE cxx_std_23)

message(STATUS "WASM hello-world configured")
message(STATUS "  Output ............... ${CMAKE_BINARY_DIR}/bin/hello.mjs (+ hello.wasm)")

add_executable(pdfengine_wasm
    bindings/wasm_engine.cpp
)

set_target_properties(pdfengine_wasm PROPERTIES
    OUTPUT_NAME "pdfengine"
    SUFFIX ".mjs"
    RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)

target_include_directories(pdfengine_wasm PRIVATE
    "${CMAKE_CURRENT_SOURCE_DIR}/bindings"
)

target_link_libraries(pdfengine_wasm PRIVATE pdfengine::pdfengine)

target_link_directories(pdfengine_wasm PRIVATE
    "${CMAKE_BINARY_DIR}/vcpkg_installed/wasm32-emscripten/lib")

set(_wasm_font_src "${CMAKE_SOURCE_DIR}/engine/assets/fonts")
set(_wasm_font_dir "${CMAKE_BINARY_DIR}/embed_fonts")
file(COPY "${_wasm_font_src}/" DESTINATION "${_wasm_font_dir}")

target_link_options(pdfengine_wasm PRIVATE
    "-Wl,--allow-multiple-definition"
    "--embed-file" "${_wasm_font_dir}@/fonts"
    "-sMODULARIZE=1"
    "-sEXPORT_ES6=1"
    "-sENVIRONMENT=node,web"
    "-sALLOW_MEMORY_GROWTH=1"
    "-sWASM_BIGINT"                 
    "-sSTACK_SIZE=5MB"              
    "-sEXPORTED_FUNCTIONS=['_loadDocument','_pageCount','_renderPagePng','_previewRender','_previewRenderRegion','_previewRenderPaginated','_lastRegionCount','_lastRegionPtr','_lastRegionW','_lastRegionH','_lastRegionPage','_lastRegionYTop','_lastRenderPtr','_lastRenderW','_lastRenderH','_lastLayoutJson','_registerAuxFont','_freeDocument','_engineBuildInfo','_debugValidateLayout','_malloc','_free']"
    "-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap','getValue','setValue','HEAPU8']"
)

target_compile_features(pdfengine_wasm PRIVATE cxx_std_23)

message(STATUS "WASM pdfengine configured")
message(STATUS "  Output ............... ${CMAKE_BINARY_DIR}/bin/pdfengine.mjs (+ pdfengine.wasm)")
