import { lazy, Suspense , useEffect } from 'react';
import { BrowserRouter, Switch } from 'react-router-dom';
import { ToastContainer } from 'react-toastify';
import { useSelector, useDispatch } from 'react-redux';

import s from './App.module.css';
import { getToken } from './redux/authorization/selector'
import { asyncLogout, asyncCurrentUser } from './redux/authorization/operations'
import { setToken } from './api-data'
import PrivateRoute from './components/reusableComponents/Routes/PrivateRoute';
import PublicRoute from './components/reusableComponents/Routes/PublicRoute';
import Loader from './components/reusableComponents/Loader/Loader';

const HomePage = lazy(
  () =>
    import(
      './components/HomePage' /* webpackChunkName: "HomePage" */
    ),
);

const AuthPage = lazy(
  () =>
    import(
      './components/AuthPage' /* webpackChunkName: "AuthPage" */
    ),
);

function App() {
  const token = useSelector(getToken)
  const dispatch = useDispatch()

  useEffect(() => {
    if(!localStorage.isChecked) localStorage.isChecked = 'true'
  }, [])

  useEffect(() => {
    if (token) {
      setToken.set(token)
      dispatch(asyncCurrentUser())
    }
    const handleKeepIn = () => {
     if (localStorage.isChecked === 'false') dispatch(asyncLogout())
    }
    window.addEventListener("beforeunload",handleKeepIn)
    return () => window.removeEventListener("beforeunload",handleKeepIn)
  }, [dispatch,token])

  return (
    <div className={s.appWrapper}>
      <Suspense fallback={<Loader />}>
        <BrowserRouter>
          <Switch>
            <PrivateRoute exact path="/">
              <HomePage/>
            </PrivateRoute>
              <PublicRoute  path={'/z/'} restricted>
                <AuthPage />
              </PublicRoute>
          </Switch>
        </BrowserRouter>
        <Loader/>
      </Suspense>
      <ToastContainer
        position="top-right"
        autoClose={5000}
        hideProgressBar={false}
        newestOnTop={false}
        closeOnClick
        rtl={false}
        pauseOnFocusLoss
        draggable
        pauseOnHover
      />
    </div>
  );
}


export default App;
