import {Box, Flex} from '@chakra-ui/react'
import {GatsbySSR} from 'gatsby'
import React from 'react'
import {RootChakraProvider, ThemeProvider} 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'

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

export const wrapPageElement: GatsbySSR['wrapPageElement'] = (
  {element, props},
  pluginOptions
) => {
  const options = (pluginOptions as unknown) as IJaenConfig

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

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

  if (props.location.pathname.startsWith('/admin')) {
    return <ThemeProvider>{inner}</ThemeProvider>
  }

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