'use client'

import type { ComponentType } from 'react'
import React from 'react'
import { type NavConfig, config } from '../config'
import { extendConfig } from '../extendConfig'

type Context = {
  config: NavConfig
  linkComponent?: ComponentType<{ href: string; children: React.ReactNode }>
}

export const NavConfigContext = React.createContext<Context>({ config })

type Props = {
  topNavConfig?: NavConfig
  bottomNavConfig?: NavConfig
  topNavExtendedConfig?: NavConfig
  linkComponent?: ComponentType<{ href: string; children: React.ReactNode }>
}
export function NavConfigContextProvider({
  topNavExtendedConfig,
  topNavConfig,
  children,
  linkComponent,
}: React.PropsWithChildren<Props>) {
  const extendedConfig = React.useMemo(() => {
    // Override the top nav config
    if (topNavConfig) {
      return topNavConfig
    }
    // Extend the base top nav config
    if (topNavExtendedConfig) {
      return extendConfig(topNavExtendedConfig)
    }
    // Use the base top nav config
    return config
  }, [topNavConfig, topNavExtendedConfig])

  return (
    <NavConfigContext.Provider
      value={{ config: extendedConfig, linkComponent }}
    >
      {children}
    </NavConfigContext.Provider>
  )
}

export const useNavConfig = () => {
  const ctx = React.useContext(NavConfigContext)
  if (!ctx) {
    throw new Error(
      'useNavConfig must be used within a NavConfigContextProvider',
    )
  }
  return ctx
}
