const { h, register, preactHooks, getConsent } = globalThis.ami
const { useRef, useEffect } = preactHooks

const POLL_INTERVAL = 1000
const GAP = '48px'

function LNGMap ({ src }) {
  if (!src || !URL.canParse(src)) {
    console.error('Missing data source or invalid URL.')
    return null
  }

  const ref = useRef(null)

  useEffect(() => {
    let interval = null
    const iframe = ref.current
    const origin = new URL(src).origin

    // Post consent to iframe.
    const onLoad = () => {
      interval = setInterval(() => {
        iframe?.contentWindow?.postMessage({ consent: JSON.stringify(getConsent()) }, origin)
      }, POLL_INTERVAL)
    }

    iframe?.addEventListener('load', onLoad)

    // Clear interval and load event when destroyed.
    return () => {
      clearInterval(interval)
      iframe?.removeEventListener('load', onLoad)
    }
  }, [src])

  return h('iframe', {
    ref,
    className: 'block w-full rounded-2xl border border-txa/20 sm:h-svh md:h-svh lg:aspect-video',
    style: `max-height: calc(100svh - ${GAP})`,
    src
  })
}

register(LNGMap, 'lng-map')
