/* global localStorage */
import { NAVIGATION_CLOSE } from '#amidala/main/shared/icons.js'

const { h, register, preactHooks, matter } = globalThis.ami
const { useState, useEffect } = preactHooks
const { Icon, Img } = matter

// Expire after 7 days (the value is in milliseconds).
const RETENTION = 604_800_000
const STORAGE_KEY = 'suppressed-smart-banners'

function getPlatform () {
  if (/iPad|iPhone|iPod/.test(navigator.userAgent)) {
    return 'ios'
  } else if (/android/i.test(navigator.userAgent)) {
    return 'android'
  }

  return null
}

function isHidden (url) {
  const obj = JSON.parse(localStorage.getItem(STORAGE_KEY)) ?? {}
  const date = new Date(obj[url] ?? null)
  if (Date.parse(date) + RETENTION < Date.now()) {
    delete obj[url]
    localStorage.setItem(STORAGE_KEY, JSON.stringify(obj))
    return false
  }

  return true
}

function hide (url) {
  const obj = JSON.parse(localStorage.getItem(STORAGE_KEY)) ?? {}
  obj[url] = new Date().toISOString()
  localStorage.setItem(STORAGE_KEY, JSON.stringify(obj))
}

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

  const platform = getPlatform()
  if (!platform) {
    return null
  }

  const [data, setData] = useState()
  useEffect(() => {
    (async () => {
      const res = await fetch(src)
      const json = await res.json()
      setData(json)
    })()
  }, [])

  if (!data) {
    return null
  }

  const suffix = data[`${platform}Suffix`]
  const url = data[`${platform}Url`]

  if (isHidden(url)) {
    return null
  }

  return h('div', { className: 'p-2 bg-bga text-txa w-full animate-fade flex gap-2 border-txa/90 border-b' },
    h('button', {
      className: 'm-2 cursor-pointer',
      title: data.closeText,
      'aria-label': data.closeText,
      children: h(Icon, { _size: 'sm' }, NAVIGATION_CLOSE),
      onClick: event => {
        event.preventDefault()
        hide(url)
        setData({ ...data }) // Force update.
      }
    }),
    h('div', { className: 'flex items-center' },
      h('div', { className: 'w-16 h-16' },
        h(Img, { _tall: true, _model: { src: data.icon } })
      )
    ),
    h('div', { className: 'grow flex items-center text-sm' },
      h('div',
        h('div', data.title),
        h('div', data.author),
        h('div', suffix)
      )
    ),
    h('div', { className: 'flex items-center pe-2' }, // Compensate for bigger close button.
      h('a', {
        className: 'transition rounded-lg overflow-hidden border bg-bgb text-txb border-bgb hover:bg-txb hover:text-bgb font-bold py-1 px-2',
        href: url
      }, data.viewText)
    )
  )
}

register(SmartBanner, 'smart-banner')
