import { Box } from '../atoms/box.js'
import { Heading } from '../atoms/heading.js'
import { Icon } from '../atoms/icon.js'
import { Link } from '../atoms/link.js'
import { RichText } from '../atoms/rich-text.js'
import h from '../shared/h.js'
import idFromString from '../shared/id-from-string.js'
import { ARROW_NEXT } from '../shared/icons.js'

function LinkTrail ({ _model }) {
  const { links } = _model

  // Get a list of <LI> elements.
  const lis = []
  for (let ii = 0; ii < links.length; ++ii) {
    const { [ii]: link } = links
    const isLast = ii === links.length - 1

    // Item
    lis.push(h('li',
      h('span',
        h(Link, { _variant: 'simple', _model: link })
      )
    ))

    // >
    isLast || lis.push(
      h('li', { 'aria-hidden': true },
        h(Icon, { _size: 'xs', _rtlFlip: true }, ARROW_NEXT)
      )
    )
  }

  return h('div',
    h('ol', {
      className: 'flex sm:flex-wrap md:flex-wrap items-center p-0 space-x-2',
      children: lis
    })
  )
}

export function SearchResult ({ _model, ...props }) {
  const { links, text } = _model
  const lastBreadcrumbLink = links?.at(-1)

  return h(Box, { ...props, className: 'bg-bga text-txa rounded-2xl' },
    h(Heading, { _level: 3, id: idFromString(lastBreadcrumbLink.name) },
      h(Link, { _model: { ...lastBreadcrumbLink, icon: null }, _variant: 'full' })
    ),
    h(LinkTrail, { _model: { links: _model.links.slice(0, -1) } }),
    h(RichText, text)
  )
}
