import { useMemo } from 'preact/hooks'
import h from '../shared/h.js'
import useLink from '../shared/use-link.js'
import { Icon } from './icon.js'
import { LinkText } from './link-text.js'

const VARIANTS_CLICKABLE = {
  default: 'clickable cursor-pointer',
  simple: 'clickable cursor-pointer hover:underline',
  underline: 'clickable cursor-pointer underline',
  bold: 'clickable cursor-pointer hover:underline font-bold',
  full: 'clickable cursor-pointer font-bold underline',
  tag: 'clickable cursor-pointer transition px-2 py-1 text-sm bg-txa/10 hover:text-bga hover:bg-txa/100 rounded-sm',
}

const VARIANTS_NON_CLICKABLE = {
  bold: 'font-bold',
  full: 'font-bold',
  tag: 'transition px-2 py-1 text-sm bg-txa/10 rounded-sm',
}

export function Link ({ _model, _variant, target: forcedTarget, className = '', children, ...props }) {
  const { name, value, icon } = _model
  const { href, onClick, target } = useLink({ href: value, text: name, target: forcedTarget })
  const isClickable = value || props.onClick
  const variant = _variant || 'default'
  const variantMap = isClickable ? VARIANTS_CLICKABLE : VARIANTS_NON_CLICKABLE

  const isContainer = useMemo(() => {
    const arr = (Array.isArray(children) ? children : [children]).filter(Boolean) // Normalize to array.
    return arr.some(c => typeof c !== 'string')
  }, [children])

  const linkProps = {
    onClick,
    ...props,
    target,
    rel: target === '_blank' ? 'noopener' : undefined,
    className: [variantMap[variant], className].map(x => x ?? '').join(' ').trim() || undefined,
    href
  }

  // Container link.
  if (isContainer) {
    return h('a', linkProps, children)
  }

  // Add classes for icon alignment.
  if (icon) {
    linkProps.className += ' space-x-2 inline-flex items-center'
  }

  // Output regular link.
  return h('a', linkProps,
    icon && h('span', { className: 'grow-0' },
      h(Icon, icon)
    ),
    h(LinkText, { _model, target })
  )
}
