import { useEffect, useContext } 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 { Context } from "./main"
import { observer } from "mobx-react-lite"

function App() {
    const {store} = useContext(Context);

    useEffect(()=>{
        const CheckLogin = async () => {
            if(localStorage.getItem('token')) {
                await store.checkAuth();
            } else {
                store.storeLoad();
            }
        }
        CheckLogin().catch(console.error);
    }, [])

    if(!store.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 observer(App)
