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

const POLL_INTERVAL = 1000

function StationLocator ({ src }) {
  const ref = useRef(null)

  // Deep linking.
  const url = new URL(src)
  const params = new URLSearchParams(location.search)
  const filters = params.get('station-locator-filters')
  filters && url.searchParams.set('prefilters', filters)

  useEffect(() => {
    let interval = null
    if (!ref.current) {
      return 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, ref.current])

  return h('iframe', {
    allow: 'clipboard-write; geolocation',
    ref,
    className: 'block w-full rounded-2xl border border-txa/20 sm:h-svh md:h-svh lg:aspect-4/3',
    style: 'max-height: calc(100svh - 48px)',
    src: url.href
  })
}

register(StationLocator, 'station-locator')
