import { useContext } from 'react'
import Context from '../../redux/context'
import { FILTER_GRID_DATA_BY_ROUTE, SET_ROUTE } from '../../redux/reducersTypes'

const TabList = ({ slug = '', label = 'Untitled' }) => {
  const { nav, route, dispatchRoute, dispatchStorage } = useContext(Context)
  const cls = nav.tabClassList.split(' ')

  if( route === slug ){
    cls.push(nav.activeClass)
  }

  const showGrid = e => {
    e.preventDefault()
    const pathname = new URL(e.target.href).pathname
    const newRoute = pathname.slice(1)
    window.history.pushState('', e.target.innerText, pathname)
    dispatchRoute({ type: SET_ROUTE, payload: newRoute })
    dispatchStorage({ type: FILTER_GRID_DATA_BY_ROUTE, payload: newRoute })
  }

  return (
    <li className={cls.join(' ')}>
      <a href={'/' + slug} onClick={e => showGrid(e)}>{label}</a>
    </li>
  )
}

const HeaderNavigation = () => {
  const { nav } = useContext(Context)

  if ((nav.routes || []).length <= 0) {
    return <></>
  }

  return (
    <nav className="uk-container">
      <ul id={nav.parentID} className={nav.parentClassList}>
        {nav.routes.map((item, key) => <TabList key={key} {...item} />)}
      </ul>
    </nav>
  )
}

export default HeaderNavigation