'use client'

import React from 'react'
import { useIsMediumMediaQuery } from '../../../../hooks/MediaQueries/useMediaQuery'

type Context = {
  isCollapsed: boolean
  collapse: () => void
  expand: () => void
}
export const CollapseContext = React.createContext<Context>({
  isCollapsed: true,
  collapse: () => {},
  expand: () => {},
})

// Manages the full-screen expansion state of the vertical nav bar
export function CollapseContextProvider({ children }: React.PropsWithChildren) {
  const [isCollapsed, setIsCollapsed] = React.useState<boolean>(true)

  const collapse = React.useCallback(() => {
    document.body.classList.remove('overflow-hidden')
    setIsCollapsed(true)
  }, [])

  const expand = React.useCallback(() => {
    // Prevent scroll bar from showing when the nav bar is expanded
    document.body.classList.add('overflow-hidden')
    setIsCollapsed(false)
  }, [])

  const isMobileViewport = useIsMediumMediaQuery()
  React.useEffect(() => {
    if (!isMobileViewport) {
      collapse()
    }
  }, [isMobileViewport])

  const value = React.useMemo(
    () => ({
      isCollapsed,
      collapse,
      expand,
    }),
    [isCollapsed, collapse, expand],
  )

  return (
    <CollapseContext.Provider value={value}>
      {children}
    </CollapseContext.Provider>
  )
}
