const { register, h, matter, preactHooks } = globalThis.ami
const { Box, Heading, Link, Button } = matter
const { useEffect, useState } = preactHooks

async function getData (url) {
  const profile = location.pathname.split('.html').at(-1)

  if (!profile) {
    return null
  }

  const profilePath = `${url}${profile}.json`

  const res = await fetch(`${location.origin}/${profilePath}`)
  if (!res.ok) {
    console.error(`Failed to load resource: ${url}`)
    return null
  }

  const json = await res.json()
  const data = json?.properties?.elements

  if (!data) {
    return null
  }

  return {
    name: data?.name?.value,
    phone: data?.phone?.value,
    mobile: data?.mobile?.value,
    contactFilePath: data?.contactFile?.value,
    email: data?.email?.value,
    jobTitle: data?.jobTitle?.value,
    ctaLink: data?.ctaLink?.value
  }
}

function DynamicContactDetails (props) {
  const {
    src,
    'phone-number-text': phoneNumberText,
    'mobile-number-text': mobileNumberText,
    'email-text': emailText,
    'download-contact-text': downloadContactText,
    'download-contact-icon': downloadContactIcon,
    'call-to-action-text': callToActionText,
    'call-to-action-icon': callToActionIcon
  } = props

  const [data, setData] = useState()

  if (!src) {
    console.error('Missing data source.')
    return null
  }

  useEffect(() => {
    const fetchData = () => {
      getData(src).then(setData).catch(console.error)
    }
    fetchData()
    globalThis.addEventListener('popstate', fetchData)

    return () => {
      globalThis.removeEventListener('popstate', fetchData)
    }
  }, [])

  if (!data) {
    return null
  }

  return h(Box, { className: 'bg-bga text-txa rounded-2xl', itemscope: true, itemtype: 'https://schema.org/Person' },
    h(Heading, { _level: 3, itemprop: 'name', className: 'text-2xl' }, data.name),
    h(Heading, { _level: 4, itemprop: 'jobTitle' }, data.jobTitle),
    h('div', { className: 'space-y-2' },
      data.phone && phoneNumberText && h('div',
        h('span', { className: 'font-bold' }, `${phoneNumberText}: `),
        h(Link, { _variant: 'underline', itemprop: 'telephone', _model: { name: data.phone, value: `tel:${data.phone}` } })
      ),
      data.mobile && mobileNumberText && h('div',
        h('span', { className: 'font-bold' }, `${mobileNumberText}: `),
        h(Link, { _variant: 'underline', itemprop: 'telephone', _model: { name: data.mobile, value: `tel:${data.mobile}` } })
      ),
      h('div',
        h('span', { className: 'font-bold' }, `${emailText}: `),
        h(Link, { _variant: 'underline', itemprop: 'email', _model: { name: data.email, value: `mailto:${data.email}` } })
      )
    ),
    h('div', { className: 'flex gap-5 sm:flex-col' },
      h(Button, {
        _model: {
          name: downloadContactText,
          value: data.contactFilePath,
          icon: downloadContactIcon
        }
      }),
      data.ctaLink && callToActionText && h(Button, {
        target: '_blank',
        rel: 'noopener',
        _model: {
          name: callToActionText,
          value: data.ctaLink,
          icon: callToActionIcon
        }
      })
    )
  )
}

register(DynamicContactDetails, 'dynamic-contact-details')
