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

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

import { history } from 'config/history'
import { client } from 'config/clients'
import { matomoInstance } from 'config/matomo'

import { setClientTitleAndDescription } from 'helpers/setClientHeads'
import { isMatchPage, isMatchPageRFEF } 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 { JoinMatchPageRFEF } from 'features/JoinMatchPageRFEF'

import { AuthenticatedApp } from './AuthenticatedApp'

setClientTitleAndDescription(client.title, client.description)

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

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

  if (user && isMatchPageRFEF()) {
    window.location.href = 'https://instat.tv/football/tournaments/131'
  }
  // юзер считывается из 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
