import { useEffect } from "react"
import useAuthStore from "./stores/useAuthStore.js"
import { Routes, Route , Navigate } from "react-router-dom"
import Navbar from "./components/Navbar.jsx"
import Dashboard from "./pages/Dashboard.jsx"
import Login from "./pages/Login.jsx"
import Register from "./pages/Register.jsx"
import Students from "./pages/Students.jsx"
import Courses from "./pages/Courses.jsx"

function App() {
  const { authUser, isLoading, checkAuth, logout } = useAuthStore((state) => state)

  useEffect(() => {
    checkAuth()
  }, [])

  if(isLoading) return <div>Loading...</div>
  return (
    <div>
      <Navbar authUser={authUser} logout={logout} />
      <Routes>
        <Route path="/dashboard" element={authUser ? <Dashboard /> : <Navigate to="/login" />} />
        <Route path="/register" element={!authUser ? <Register /> : <Navigate to="/dashboard" />} />
        <Route path="/login" element={!authUser ? <Login /> : <Navigate to="/dashboard" />} />

        <Route path="/students" element={authUser && authUser.role == "admin" ? <Students /> : <Navigate to="/login" />} />
        <Route path="/courses" element={authUser && authUser.role == "admin" ? <Courses /> : <Navigate to="/login" />} />
        <Route path="*" element={authUser ? <Navigate to="/dashboard" /> : <Navigate to="/login" />} />
      </Routes>
    </div>
  )
}

export default App