import { Suspense } from 'react'
import { Router } from 'react-router-dom'

import { createInstance, MatomoProvider } from '@jonkoops/matomo-tracker-react'

import { history } from 'config/history'
import { client } from 'config/clients'
import { PAGES } from 'config/pages'

import { setClientTitleAndDescription } from 'helpers/setClientHeads'
import { isMatchPage } from 'helpers/isMatchPage'

import { GlobalStores } from 'features/GlobalStores'
import { useAuthStore } from 'features/AuthStore'
import { Background } from 'features/Background'
import { GlobalStyles } from 'features/GlobalStyles'
import { Theme } from 'features/Theme'
import { JoinMatchPage } from 'features/JoinMatchPage'

import { AuthenticatedApp } from './AuthenticatedApp'

setClientTitleAndDescription(client.title, client.description)

const matomoInstance = createInstance({
  siteId: 1,
  urlBase: PAGES.matomoBaseUrl,
})

const Main = () => {
  const { loadingUser, user } = useAuthStore()

  if (!user && isMatchPage()) return <JoinMatchPage />

  // юзер считывается из localstorage или
  // access_token токен истек и запрашивается новый
  if (loadingUser || user?.expired) return null

  // имеется действующий токен
  return <AuthenticatedApp />
}

const OTTApp = () => (
  <MatomoProvider value={matomoInstance}>
    <Router history={history}>
      <Theme>
        <GlobalStyles />
        <GlobalStores>
          <Background>
            <Suspense fallback={null}>
              <Main />
            </Suspense>
          </Background>
        </GlobalStores>
      </Theme>
    </Router>
  </MatomoProvider>
)

export default OTTApp
