import { IS_BROWSER } from '../configs'
import React from 'react'

const ViewportContext = React.createContext({})
interface ViewportProviderProps {
  children: React.ReactNode
}

export const ViewportProvider: React.FunctionComponent<ViewportProviderProps> = ({ children }) => {
  const [width, setWidth] = React.useState(IS_BROWSER ? window.innerWidth : 0)
  const [height, setHeight] = React.useState(IS_BROWSER ? window.innerHeight : 0)

  const handleWindowResize = () => {
    setWidth(IS_BROWSER ? window.innerWidth : 0)
    setHeight(IS_BROWSER ? window.innerHeight : 0)
  }

  React.useEffect(() => {
    handleWindowResize()
    window.addEventListener('resize', handleWindowResize)
    return () => window.removeEventListener('resize', handleWindowResize)
  }, [])

  return <ViewportContext.Provider value={{ width, height }}>{children}</ViewportContext.Provider>
}

export const useViewport = (mobileBreakpoint = '') => {
  const BREAKPOINT = parseInt(mobileBreakpoint) || 992
  const { width, height }: any = React.useContext(ViewportContext)

  const isMobile = React.useMemo(() => {
    return width < BREAKPOINT
  }, [BREAKPOINT, width])

  const isDesktop = React.useMemo(() => {
    return width >= BREAKPOINT
  }, [BREAKPOINT, width])

  return {
    width,
    height,
    isMobile,
    isDesktop,
  }
}
