import h from '../shared/h.js'
import { Icon } from '../atoms/icon.js'
import { Link } from '../atoms/link.js'
import { ARROW_BACK, ARROW_NEXT } from '../shared/icons.js'

export function Breadcrumb ({ _model, ...props }) {
  return h('div', {
    ...props,
    className: 'text-sm w-full px-6 py-2 min-h-9 m-auto max-w-page',
    children: _model.links.length > 1 && h(LinkTrail, { _model })
  })
}

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
    const isSecondLast = ii === links.length - 2

    const liProps = {
      className: isSecondLast ? undefined : 'sm:hidden md:hidden',
      itemscope: '',
      itemtype: 'https://schema.org/ListItem',
      itemprop: 'itemListElement'
    }

    const linkProps = {
      'aria-current': isLast ? 'page' : null,
      itemprop: 'name',
      _variant: 'simple',
      _model: link
    }

    // <
    isSecondLast && lis.push(
      h('li', { className: 'lg:hidden', 'aria-hidden': true },
        h(Icon, { _size: 'xs', _rtlFlip: true }, ARROW_BACK)
      )
    )

    // Item
    lis.push(h('li', liProps,
      h('span', { itemprop: 'item' },
        h(Link, linkProps)
      ),
      h('meta', { itemprop: 'position', content: ii + 1 })
    ))

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

  return h('nav',
    h('ol', {
      className: 'flex items-center p-0 gap-2',
      itemscope: '',
      itemtype: 'https://schema.org/BreadcrumbList',
      children: lis
    })
  )
}
