'use client'

import { useEffect, useRef } from "react"
import { themeSignal } from "./Appearance"

interface Module {
  setup?: (params: any, wasmModule: WebAssembly.Instance | undefined) => Promise<undefined>
  cleanup?: () => Promise<undefined>
  onThemeChange?: () => void
}

export default function ScriptLoaderClient({ src, wasmSrc, ...rest }: { src: string, wasmSrc?: string }) {
  const moduleRef = useRef<Module | null>(null)

  useEffect(() => {
    if (!src) return undefined;

    (async () => {
      const scriptModule = await import(/*webpackIgnore: true */ src)

      let wasmModule: WebAssembly.Instance | undefined = undefined;

      if (wasmSrc) {
        const wasm = await WebAssembly.instantiateStreaming(fetch(wasmSrc))
        wasmModule = wasm.instance
      }

      moduleRef.current = scriptModule


      if (scriptModule.setup && typeof scriptModule.setup === 'function')
        scriptModule.setup(rest, wasmModule)
    })();

    return () => {
      const mod = moduleRef.current

      if (mod?.cleanup && typeof mod.cleanup === 'function') {
        mod.cleanup()
      }
    }
  }, [])

  useEffect(() => {
    function onThemeChange() {
      const mod = moduleRef.current

      if (mod?.onThemeChange && typeof mod?.onThemeChange === 'function') {
        mod.onThemeChange()
      }
    }

    themeSignal.addListener('change', onThemeChange)
    return () => { themeSignal.removeListener('change', onThemeChange) }
  }, [])

  return null
}
