import { Routes, Route, Navigate } from 'react-router-dom'
import { AuthProvider, useAuth } from './context/AuthContext'
import { ThemeProvider } from './context/ThemeContext'
import AuthPage      from './pages/AuthPage'
import LandingPage   from './pages/LandingPage'
import Layout        from './components/Layout'
import DashboardPage from './pages/DashboardPage'
import AssessPage    from './pages/AssessPage'
import HistoryPage   from './pages/HistoryPage'
import ProfilePage   from './pages/ProfilePage'
import BreathePage      from './pages/BreathePage'
import BoxBreathingPage from './pages/BoxBreathingPage'
import GratitudePage    from './pages/GratitudePage'
import TodoPage      from './pages/TodoPage'

function PrivateRoute({ children }) {
  const { user, loading } = useAuth()
  if (loading) return <div className="full-loader"><div className="spinner" /></div>
  return user ? children : <Navigate to="/auth" replace />
}

function PublicRoute({ children }) {
  const { user, loading } = useAuth()
  if (loading) return <div className="full-loader"><div className="spinner" /></div>
  return user ? <Navigate to="/app/breathe" replace /> : children
}

export default function App() {
  return (
    <ThemeProvider>
      <AuthProvider>
      <Routes>
        {/* Public landing */}
        <Route path="/"     element={<PublicRoute><LandingPage /></PublicRoute>} />
        <Route path="/auth" element={<PublicRoute><AuthPage /></PublicRoute>} />

        {/* Breathe hub — full-screen, no sidebar */}
        <Route path="/app/breathe"     element={<PrivateRoute><BreathePage /></PrivateRoute>} />
        <Route path="/app/breathe/box" element={<PrivateRoute><BoxBreathingPage /></PrivateRoute>} />

        {/* Protected app shell (with sidebar) */}
        <Route path="/app" element={<PrivateRoute><Layout /></PrivateRoute>}>
          <Route index            element={<Navigate to="breathe" replace />} />
          <Route path="dashboard" element={<DashboardPage />} />
          <Route path="assess"    element={<AssessPage />} />
          <Route path="history"   element={<HistoryPage />} />
          <Route path="profile"   element={<ProfilePage />} />
          <Route path="gratitude" element={<GratitudePage />} />
          <Route path="todo"      element={<TodoPage />} />
        </Route>

        {/* Legacy short URLs — redirect logged-in users straight to app */}
        <Route path="/dashboard" element={<PrivateRoute><Navigate to="/app/dashboard" replace /></PrivateRoute>} />
        <Route path="/assess"    element={<PrivateRoute><Navigate to="/app/assess"    replace /></PrivateRoute>} />
        <Route path="/history"   element={<PrivateRoute><Navigate to="/app/history"   replace /></PrivateRoute>} />

        <Route path="*" element={<Navigate to="/" replace />} />
      </Routes>
    </AuthProvider>    </ThemeProvider>  )
}
