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

const REACH = 4

export function SearchNav ({ _model, ...props }) {
  const { links } = _model

  // Do not render if no selected link.
  const selectedIndex = links.findIndex(l => l.selected) || 0

  // Get base indexes.
  let startIndex = selectedIndex - REACH
  let endIndex = selectedIndex + REACH + 1

  // Offset
  endIndex -= Math.min(0, startIndex)
  startIndex += Math.min(0, links.length - endIndex)

  // Cap
  startIndex = Math.max(startIndex, 0)
  endIndex = Math.min(endIndex, links.length)

  const items = links.slice(startIndex, endIndex).map(link => h('li',
    h(Link, {
      _model: link,
      _variant: link.selected ? 'bold' : 'simple',
      children: h('div', { className: 'w-6 text-center' }, link.name)
    })
  ))

  const prev = links[selectedIndex - 1]
  items.unshift(h('li', { className: prev ? null : 'opacity-50' },
    h(Link, {
      'aria-label': prev?.value && t('Previous'),
      _variant: prev ? 'simple' : null,
      _model: { value: prev?.value, icon: ARROW_BACK },
      children: h('div', { className: 'flex items-center justify-center min-w-6' },
        h(Icon, { _size: 'sm' }, ARROW_BACK),
        h('div', { className: 'sm:hidden md:hidden ms-1 me-3' }, t('Previous'))
      )
    })
  ))

  const next = links[selectedIndex + 1]
  items.push(h('li', { className: next ? null : 'opacity-50' },
    h(Link, {
      'aria-label': next?.value && t('Next'),
      _variant: next ? 'simple' : null,
      _model: { value: next?.value, icon: ARROW_NEXT },
      children: h('div', { className: 'flex items-center justify-center min-w-6' },
        h('div', { className: 'sm:hidden md:hidden ms-3 me-1' }, t('Next')),
        h(Icon, { _size: 'sm' }, ARROW_NEXT)
      )
    })
  ))

  return h('ol', {
    ...props,
    className: 'w-full p-8 flex flex-wrap justify-center items-center bg-bga text-txa rounded-2xl',
    children: items
  })
}
