import 'focus-visible/dist/focus-visible'
import 'typeface-ibm-plex-sans'

import { ChakraProvider, Flex } from '@chakra-ui/react'
import { AppProps } from 'next/app'
import Head from 'next/head'
import { useRouter } from 'next/router'
import NProgress from 'nprogress'
import { useEffect } from 'react'
import { FormProvider, useForm } from 'react-hook-form'

import NavBar from '../components/NavBar'
import theme from '../theme'

const App: React.FC<AppProps> = ({ Component, pageProps }) => {
  const router = useRouter()
  const methods = useForm({ shouldUnregister: false })

  useEffect(() => {
    const setDocHeight = () => {
      document.documentElement.style.setProperty('--vh', `${window.innerHeight / 100}px`)
    }

    const load = () => {
      NProgress.start()
    }

    const stop = () => {
      NProgress.done()
    }

    router.events.on('routeChangeStart', load)
    router.events.on('routeChangeComplete', stop)
    router.events.on('routeChangeError', stop)

    setDocHeight()
    window.addEventListener('resize', function () {
      setDocHeight()
    })
    window.addEventListener('orientationchange', function () {
      setDocHeight()
    })
  }, [])

  return (
    <>
      <Head>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
      </Head>
      <ChakraProvider theme={theme} resetCSS>
        <FormProvider {...methods}>
          <Flex direction="column" minH="calc(var(--vh, 1vh) * 100)" w="100%">
            <NavBar />
            <Component {...pageProps} />
          </Flex>
        </FormProvider>
      </ChakraProvider>
    </>
  )
}

export default App
