import { BrowserRouter as Router, Routes, Route, Navigate, Outlet } from "react-router-dom"
import { ThemeProvider } from "./components/ThemeProvider"
import { LanguageProvider } from "./components/LanguageProvider"
import { Toaster } from "./components/ui/toaster"
import { Navbar } from "./components/Navbar"
import { WorkspaceProvider } from "./context/WorkspaceContext"
import Auth from "./pages/Auth"
import Profile from "./pages/Profile"
import Terms from "./pages/Terms"
import Workspaces from "./pages/Workspaces"
import CreateWorkspace from "./pages/WorkspaceCreate"
import WorkspaceDetail from "./pages/WorkspaceDetail"
import EditWorkspace from "./pages/WorkspaceEdit"
import Clients from "./pages/Clients"

const MainLayout = () => {
  return (
    <div className="min-h-screen bg-slate-50 dark:bg-slate-950 transition-colors">
      <Navbar />
      <main>
        <Outlet />
      </main>
    </div>
  )
}

const RootRedirect = () => {
  const isAuthenticated = !!localStorage.getItem("accessToken")  
  return isAuthenticated ? <Navigate to="/workspaces" replace /> : <Navigate to="/auth" replace />
}

function App() {
  return (
    <ThemeProvider>
      <LanguageProvider>
        <Router>
          <WorkspaceProvider>
            <Routes>
              <Route path="/" element={<RootRedirect />} />
              <Route path="/auth" element={<Auth />} />
              <Route path="/terms" element={<Terms />} />
              
              <Route element={<MainLayout />}>
                <Route path="/profile" element={<Profile />} />
                <Route path="/workspaces" element={<Workspaces />} />
                <Route path="/workspaces/create" element={<CreateWorkspace />} />
                <Route path="/workspaces/:id" element={<WorkspaceDetail />} />
                <Route path="/workspaces/:id/edit" element={<EditWorkspace />} />
                <Route path="/clients" element={<Clients />} />
              </Route>
            </Routes>
          </WorkspaceProvider>
        </Router>
        <Toaster />
      </LanguageProvider>
    </ThemeProvider>
  )
}

export default App
