import { h, type FunctionComponent } from 'preact'
import { useRouter } from 'preact-router'

import NavigationItem from './navigation_item.tsx'
import NavigationGroup from './navigation_group.tsx'
import s from './navigation.module.scss'

import type { Route } from '../../../shared/types.ts'

type NavigationProps = {
  base: string
  routes: Route[]
}

const Navigation: FunctionComponent<NavigationProps> = ({ base, routes }) => {
  const [{ url }] = useRouter()

  const currentPath = base ? url.slice(base.length) : url

  return (
    <nav className={s.base}>
      <ul>
        {routes
          .filter(({ nav }) => nav !== false)
          .map(({ path, title, routes }) =>
            routes ? (
              <NavigationGroup
                key={path}
                base={base}
                currentPath={currentPath}
                path={path}
                title={title}
                routes={routes}
              />
            ) : (
              <NavigationItem
                key={path}
                base={base}
                currentPath={currentPath}
                path={path}
                title={title}
                name={title.toLowerCase()}
              />
            ),
          )}
      </ul>
    </nav>
  )
}

export default Navigation
