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

const DEFAULT_ICON_SIZE_MAPPING = { s: 6, m: 8, l: 12, xl: 16 }
const DEFAULT_ICON_SIZE = DEFAULT_ICON_SIZE_MAPPING.s

function ShoutOut ({ src }) {
  const [data, setData] = useState()
  useEffect(() => {
    (async () => {
      const res = await fetch(src)
      if (!res.ok) {
        throw new Error(`Error fetching ${src}. Status: ${res.status}`)
      }
      const json = await res.json()
      setData(json)
    })().catch(console.error)
  }, [src])

  if (!data) {
    return null
  }

  const iconSize = DEFAULT_ICON_SIZE_MAPPING[data.customModel.elements.iconSize.value] || DEFAULT_ICON_SIZE
  const title = data.customModel.elements.title.value

  return h(Box, { className: 'bg-bga text-txa h-full rounded-2xl' },
    h('div', { className: 'flex gap-3' },
      h('div', { className: 'shrink' },
        h('div', { className: `block w-${iconSize} h-${iconSize}` },
          h(SVG, {
            _style: id => `
              ${id} path, ${id} polygon {
                fill: currentColor;
            }`,
            _model: { src: data.customModel.elements.icon.value }
          })
        )
      ),
      title && h('div', { className: 'shrink' },
        h(Heading, { _level: 3 }, title)
      ),
      h('div', { className: 'flex items-center' },
        h(RichText, data.customModel.elements.description.value)
      )
    )
  )
}

register(ShoutOut, 'shout-out')
