import { useMemo, useState } from 'preact/hooks'
import { NavLink } from '../atoms/nav-link.js'
import getId from '../shared/get-id.js'
import h from '../shared/h.js'
import t from '../shared/t.js'

export function Tree ({ _model, _level = 0, ...props }) {
  return h('div', { ...props, className: _level === 0 ? 'py-1' : '', role: 'list' }, _model.links.map((link, index) =>
    h('div', { role: 'listitem' },
      // Make the first link bold.
      h(Node, { _bold: (index === 0) ? true : undefined, _level, _model: link })
    )
  ))
}

function Node ({ _model, _level, _bold }) {
  const { children, name, value } = _model

  const ids = useMemo(() => ({ button: getId(), container: getId() }), [])
  const [isVisible, setIsVisible] = useState(false)

  const containerProps = { className: 'animate-expand' }
  const linkProps = { _model, _level, _bold, _selection: 'right' }
  const treeProps = {}

  if (children) {
    // Prepend children with 'go to' link.
    const links = children.slice()
    links.unshift({ name: t('Go to: {0}', name), value })
    treeProps._model = { links }
    treeProps._level = _level + 1
    treeProps.id = ids.container
    treeProps['aria-labelledby'] = ids.button

    // Link is now parent.
    linkProps._level = _level
    linkProps._expanded = isVisible
    linkProps.id = ids.button
    linkProps.role = 'button'
    linkProps['aria-expanded'] = `${isVisible}`
    linkProps['aria-controls'] = ids.container
    linkProps.onClick = event => setIsVisible(!isVisible) || event.preventDefault()
  }

  return [
    h(NavLink, linkProps),
    children && isVisible && h('div', containerProps, [
      h(Tree, treeProps)
    ])
  ]
}
