import h from '../shared/h.js'
import { ARROW_DOWN, ARROW_UP } from '../shared/icons.js'
import { Icon } from './icon.js'
import { LinkText } from './link-text.js'
import { Link } from './link.js'

const SIZE_CLASSES = { md: 8, lg: 12 }
const SELECTION_CLASSES = {
  default: 'p-2',
  top: 'border-t-4 px-1 pb-2 pt-1',
  bottom: 'border-b-4 px-1 pb-1 pt-2',
  right: 'border-e-4 ps-2 pe-1 py-1'
}

export function NavLink ({ _model, _level, _expanded, _textless, _size, _bold, _highlighted, _selection, ...props }) {
  const { name, value, icon, selected } = _model

  const size = SIZE_CLASSES[_size ?? 'md']
  const sizeClass = _textless ? `min-h-${size} min-w-${size}` : `w-full min-h-${size}`
  const highlightClass = _highlighted ? 'bg-txa/10' : ''
  const indentClass = `ps-${2 + (_level ?? 0) * 4}`
  const boldClass = _bold ? 'font-bold' : ''

  return h('div', {
    className: `h-full transition ${selected ? 'border-bgb/100' : 'border-bgb/0'} ${SELECTION_CLASSES[_selection ?? 'default']}`,
    children: h(Link, {
      ...props,
      title: _textless ? name : undefined,
      className: 'h-full',
      _model: { name, icon, value: value ?? '#' }, // Make sure it's tabbable.
      children: h('div', {
        className: `h-full transition hover:bg-txa/10 pe-2 py-1 flex space-x-2 items-center justify-center rounded overflow-hidden ${sizeClass} ${highlightClass} ${indentClass} ${boldClass}`,
        children: [
          // Custom icon.
          icon && h('div', { className: 'flex items-center' },
            h(Icon, icon)
          ),
          _textless || h('div', { className: 'grow' },
            h(LinkText, { _model })
          ),
          // Expand and collapse arrow.
          _expanded !== undefined && h('div', { className: 'flex items-center' },
            h(Icon, { _size: 'xs' }, _expanded ? ARROW_UP : ARROW_DOWN)
          )
        ]
      })
    })
  })
}
