import { ReactNode, useEffect } from 'react'

import { useMatomo } from '@jonkoops/matomo-tracker-react'

import { getLanguageUrlParam } from 'helpers/languageUrlParam'

import { AuthStore } from 'features/AuthStore'
import { LexicsStore } from 'features/LexicsStore'
import { useLocation } from 'react-router'

const initialLanguage = getLanguageUrlParam()

type Props = {
  children: ReactNode,
}

export const GlobalStores = ({ children }: Props) => {
  const { pathname, search } = useLocation()
  const { trackPageView } = useMatomo()

  useEffect(() => {
    const isProduction = process.env.REACT_APP_ENV === 'production'

    if (isProduction) trackPageView()
  }, [trackPageView, pathname, search])

  return (
    <LexicsStore initialLanguage={initialLanguage}>
      <AuthStore>
        {children}
      </AuthStore>
    </LexicsStore>
  )
}
