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

// Define Preact component.
function FuelPrices ({ src }) {
  const [data, setData] = useState()

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

  useEffect(() => {
    (async () => {
      const res = await fetch(src)
      if (!res.ok) {
        console.error(`Error fetching ${src}. Status: ${res.status}`)
        return
      }
      const obj = await res.json()
      setData({ ...obj, trail: [] })
    })().catch(console.error)
  }, [src])

  if (!data) {
    return null
  }

  const prices = data?.listPrices?.[0] ?? {}
  const products = prices.products ?? []

  return h(Box, { className: 'rounded-2xl bg-bga text-txa h-full' },
    h(Heading, { _level: 3 }, data.title),
    h('p', prices.date),
    products.length > 0 && h(Table, products.map(p =>
      h('tr',
        h('th', { className: 'w-1/2' }, p.type),
        h('td', { className: 'text-right' }, `${Number(p.price).toFixed(2)}\xa0${p.currencyCode}`)
      )
    ))
  )
}

register(FuelPrices, 'fuel-prices')
