import { useEffect, useRef } from 'preact/hooks'
import { Box } from '../atoms/box.js'
import { Heading } from '../atoms/heading.js'
import { Icon } from '../atoms/icon.js'
import { RichText } from '../atoms/rich-text.js'
import { Asset } from '../molecules/asset.js'
import { Links } from '../molecules/links.js'
import { ValidationError } from '../routing/error-handler.js'
import h from '../shared/h.js'
import { ARROW_DOWN } from '../shared/icons.js'
import idFromString from '../shared/id-from-string.js'

export function AccordionItem ({ _model, children, ...props }) {
  const { title, links } = _model

  if (!title) {
    throw new ValidationError()
  }

  const ref = useRef(null)
  const icon = links?.[0]?.icon
  const microdata = getMicrodata(props._variant === 'faq')
  const hashHandler = () => location.hash.substring(1) === idFromString(title) && ref.current?.setAttribute('open', '')

  useEffect(() => {
    hashHandler()
    globalThis.addEventListener('hashchange', hashHandler)
    return () => globalThis.removeEventListener('hashchange', hashHandler)
  }, [title])

  return h('details', {
    ...props,
    ...microdata.question,
    ref,
    className: 'bg-bga text-txa w-full rounded-2xl relative border-txa/20 border',
    _style: id => `
      ${id}::details-content { opacity: 0; transform: translateY(-8px); transition: all var(--anim-time) }
      ${id}[open]::details-content { opacity: 1; transform: translateY(0) }
      ${id}[open] summary div:last-child { transform: rotate(180deg) }
    `,
    children: [
      h('summary', {
        className: 'clickable w-full flex items-center gap-2 px-6 py-3 cursor-pointer rounded-2xl relative',
        children: [
          icon && h('div', { className: 'bg-bgb text-txb w-10 h-10 flex items-center justify-center rounded-full' },
            h(Icon, icon)
          ),
          h('div', { className: 'grow' },
            h(Heading, { _level: '3', _size: '4', ...microdata.name }, title)
          ),
          h('div', { className: 'shrink transition-all' },
            h(Icon, { _size: 'sm' }, ARROW_DOWN)
          )
        ]
      }),
      h('div', { ...microdata.answer },
        h('div', { ...microdata.text },
          h(Content, { _model, children })
        )
      )
    ]
  })
}

// PromoText cannot be reused due to legacy children support.
function Content ({ _model, children }) {
  const { text, links, asset, image, video } = _model
  const hasContent = text || asset.src || links.length > 0
  if (hasContent) {
    const filteredModel = { links: links.filter(l => l.name).map(l => ({ ...l, icon: null })) }
    return h(Box,
      asset.src && h('div', { className: 'rounded-lg overflow-hidden' },
        h(Asset, { _model: { image, video } })
      ),
      h(RichText, text),
      links && h(Links, { _variant: 'full', _model: filteredModel })
    )
  }

  // Legacy children support.
  return children
}

function getMicrodata (isFaq) {
  const microdata = {}

  if (isFaq) {
    microdata.question = {
      itemscope: '',
      itemtype: 'https://schema.org/Question'
    }
    microdata.name = {
      itemprop: 'name'
    }
    microdata.answer = {
      itemscope: '',
      itemtype: 'https://schema.org/Answer',
      itemprop: 'acceptedAnswer'
    }
    microdata.text = {
      itemprop: 'text'
    }
  }

  return microdata
}
