import { useEffect } from "react"
import RequireAuth from "./components/Auth/RequireAuth"
import OnlyUnauthorized from "./components/Auth/OnlyUnauthorized"
import IndexPage from "./pages/IndexPage"
import LoginForm from "./components/LoginForm"
import RegisterForm from "./components/RegisterForm"
import { BrowserRouter, Routes, Route } from 'react-router-dom'
import { checkAuth, userSlice } from "./store/reducers/UserSlice";
import { useAppDispatch, useAppSelector } from "./hooks/redux"


function App() {
    const {isLoading} = useAppSelector(state => state.UserSlice);
    const {storeLoad} = userSlice.actions
    const dispatch = useAppDispatch();
    
    useEffect(()=>{
        const CheckLogin = async () => {
            if(localStorage.getItem('token')) {
                await dispatch(checkAuth());
            } else {
                dispatch(storeLoad());
            }
        }
        CheckLogin().catch(console.error);
    }, [dispatch, storeLoad])
    
    

    if(!isLoading) {
        return (
            <BrowserRouter>
                <Routes>
                    <Route path='/' element={<RequireAuth><IndexPage/></RequireAuth>}/>
                    <Route path='/login' element={<OnlyUnauthorized><LoginForm/></OnlyUnauthorized>}/>
                    <Route path='/register' element={<OnlyUnauthorized><RegisterForm/></OnlyUnauthorized>}/>
                </Routes>
            </BrowserRouter>
        )
    }
}

export default App
