import {Box, Flex} from '@chakra-ui/react'
import {GatsbyBrowser} from 'gatsby'
import React from 'react'
import {RootChakraProvider} from './src/chakra-providers'
import {IncomingBuildCheckerProvider} from './src/services/IncomingBuildChecker'
import {AnalyticsProvider} from './src/services/tracking/AnalyticsProvider'
import {IJaenConfig} from './src/types'
import AdminToolbarContainer from './src/ui/AdminToolbar'
import {SnekFinder} from './src/withSnekFinder'

export const wrapRootElement: GatsbyBrowser['wrapRootElement'] = ({
  element
}) => {
  return (
    <RootChakraProvider>
      <IncomingBuildCheckerProvider>{element}</IncomingBuildCheckerProvider>
    </RootChakraProvider>
  )
}

export const wrapPageElement: GatsbyBrowser['wrapPageElement'] = (
  {element, props},
  pluginOptions
) => {
  const pathname = window.location.pathname

  const options = (pluginOptions as unknown) as IJaenConfig

  let inner = (
    <Flex direction={'column'} h="100vh" overflow="none">
      <AdminToolbarContainer />

      <Box flex="1" overflow="auto" id="jaen-content-container">
        {element}
      </Box>
    </Flex>
  )

  if (pathname.startsWith('/admin')) {
    inner = <SnekFinder>{element}</SnekFinder>
  }

  return (
    <AnalyticsProvider
      pageProps={props}
      snekAnalyticsId={options.snekAnalyticsId}>
      {inner}
    </AnalyticsProvider>
  )
}
