const { h, preactHooks, register, waitForConsent } = globalThis.ami
const { useEffect, useState } = preactHooks

function MouseflowAnalytics ({ id }) {
  if (!id) {
    return null
  }

  if (document.documentElement.dataset.mode !== 'publish') {
    return null
  }

  // Mouseflow is already loaded.
  if (globalThis._mfq) {
    return null
  }

  const [consent, setConsent] = useState(false)

  useEffect(() => {
    (async () => {
      // This will stop the execution util the consent is granted.
      await waitForConsent({ statistics: true })
      setConsent(true)
    })()
  }, [])

  if (!consent) {
    return null
  }

  globalThis._mfq = []
  return h('script', {
    src: `//cdn.mouseflow.com/projects/${id}.js`,
    defer: true
  })
}

register(MouseflowAnalytics, 'mouseflow-analytics')
