import { google, apple } from './badges.js'
import { NAVIGATION_CLOSE } from '#amidala/main/shared/icons.js'
import { encodeQR } from 'qr'

const { h, t, register, matter, preactHooks } = globalThis.ami
const { useState, useMemo } = preactHooks
const { Box, Heading, Link, SVG, Popup, Button } = matter

function StoreBadges ({
  title,
  text,
  'app-store-link': appStoreLink,
  'play-store-link': playStoreLink,
}) {
  return h(Box, { className: 'rounded-2xl bg-bga text-txa h-full' },
    title && h(Heading, { _level: 3, _align: 'center' }, title),
    text && h('p', { className: 'text-center' }, text),
    h('div', { className: 'flex gap-5 justify-center max-h-16' },
      h(StoreLink, {
        name: t('Download on the {0}', ''),
        value: appStoreLink,
        'aria-label': t('Download on the {0}', 'App Store'),
        iconFunc: apple
      }),
      h(StoreLink, {
        name: t('Get it on {0}', ''),
        value: playStoreLink,
        'aria-label': t('Get it on {0}', 'Google Play'),
        iconFunc: google
      })
    )
  )
}

function StoreLink ({ name, value, 'aria-label': ariaLabel, iconFunc }) {
  const popupTitle = t('Scan the QR code to download the app or click the link below')
  const [showPopup, setShowPopup] = useState(false)
  const isMobile = useMemo(() => /iPad|iPhone|iPod|Android/.test(navigator.userAgent), [])
  const qrCode = useMemo(() => value ? encodeQR(value, 'svg', { ecc: 'low' }) : null, [value])

  if (isMobile || !value) {
    return h(Link, { _model: { name, value }, 'aria-label': ariaLabel, className: 'h-16' },
      h(SVG, { _tall: true, _model: { src: iconFunc(name) } })
    )
  }

  return [
    h('button', {
      className: 'clickable cursor-pointer h-16',
      'aria-label': ariaLabel,
      'aria-haspopup': 'dialog',
      type: 'button',
      onClick: () => {
        setShowPopup(true)
      },
      children: h(SVG, { _tall: true, _model: { src: iconFunc(name) } }),
    }),
    h(Popup, {
      _show: showPopup,
      _layout: 'center',
      // Synchronise state with native popup open/close.
      onBeforeToggle: event => setShowPopup(event.newState === 'open'),
      children: [
        h('div', { className: 'flex gap-2' },
          h('div', { className: 'shrink-0 grow-0 order-last' },
            h(Button, {
              _variant: 'plain',
              _textless: true,
              _size: 'xs',
              _model: {
                name: t('Dismiss'),
                icon: NAVIGATION_CLOSE
              },
              onClick: event => {
                event.preventDefault()
                setShowPopup(false)
              }
            })
          ),
          h(Heading, { _level: 3 }, popupTitle)
        ),
        qrCode && h('div', { style: 'fill: currentColor', className: 'm-auto w-4/5' },
          h(SVG, { _model: { src: qrCode, alt: popupTitle } })
        ),
        h('div',
          h(Link, { _variant: 'underline', _model: { name: ariaLabel, value } })
        )
      ]
    })
  ]
}

register(StoreBadges, 'store-badges')
