"use client"
import Script from "next/script"
import { useEffect, useRef, useState } from "react"

import useLang from "@/hooks/useLang"

import styles from "./jotform.module.css"

type JotformProps = {
  formId: string | null | undefined
}

export default function Jotform({ formId }: JotformProps) {
  const lang = useLang()
  const [scriptInitialized, setScriptInitialized] = useState(
    () =>
      typeof window !== "undefined" &&
      typeof window.jotformEmbedHandler === "function"
  )
  const componentInitialized = useRef(false)

  useEffect(() => {
    if (
      formId &&
      scriptInitialized &&
      !componentInitialized.current &&
      window.jotformEmbedHandler
    ) {
      window.jotformEmbedHandler(
        `iframe[id='JotFormIFrame-${formId}']`,
        "https://scandichotels.jotform.com/"
      )
      componentInitialized.current = true
    }
  }, [formId, scriptInitialized])

  if (!formId) {
    return null
  }

  const src = `https://scandichotels.jotform.com/${formId}?language=${lang}`

  return (
    <>
      <Script
        src="https://scandichotels.jotform.com/s/umd/latest/for-form-embed-handler.js"
        onLoad={() => setScriptInitialized(true)}
        strategy="lazyOnload"
      />
      <iframe
        id={`JotFormIFrame-${formId}`}
        src={src}
        className={styles.iframe}
        scrolling="no"
      />
    </>
  )
}
