'use client'

import React from 'react'

type Context = {
  navHighlight: string[] | null
  expandedParent: string | null
  toggleParent: (label: string | null) => void
  reset: () => void
}
export const LevelStateContext = React.createContext<Context>({
  navHighlight: null,
  expandedParent: null,
  toggleParent: () => {},
  reset: () => {},
})

type Props = {
  navHighlight?: string[] | null
}
export function LevelStateContextProvider({
  navHighlight = null,
  children,
}: React.PropsWithChildren<Props>) {
  const parentContext = React.useContext(LevelStateContext)
  const topHighlight = navHighlight?.[0] ?? null
  const [expandedParent, setActiveParent] = React.useState<string | null>(
    topHighlight,
  )
  const toggleParent = React.useCallback((parent: string | null) => {
    setActiveParent((prevParent) => (prevParent === parent ? null : parent))
  }, [])

  const reset = React.useCallback(() => {
    setActiveParent(topHighlight)
    parentContext.reset()
  }, [topHighlight])

  React.useEffect(() => {
    if (
      navHighlight &&
      navHighlight[0] !== undefined &&
      expandedParent !== navHighlight[0]
    ) {
      toggleParent(navHighlight[0])
    }
  }, [toggleParent, navHighlight])

  return (
    <LevelStateContext.Provider
      value={{ navHighlight, expandedParent, toggleParent, reset }}
    >
      {children}
    </LevelStateContext.Provider>
  )
}
