import { useEffect } from 'react';
import { Routes, Route, Navigate, useLocation } from 'react-router-dom';
import { useAuth } from './contexts/AuthContext';
import { useLanguage } from './contexts/LanguageContext';
import { useBranding } from './contexts/BrandingContext';
import Layout from './components/Layout';
import ProtectedRoute from './components/ProtectedRoute';
import Home from './pages/Home';
import Login from './pages/Login';
import Register from './pages/Register';
import VerifyEmail from './pages/VerifyEmail';
import ForgotPassword from './pages/ForgotPassword';
import ResetPassword from './pages/ResetPassword';
import Dashboard from './pages/Dashboard';
import RoomDetail from './pages/RoomDetail';
import Settings from './pages/Settings';
import Admin from './pages/Admin';
import GuestJoin from './pages/GuestJoin';
import FederationInbox from './pages/FederationInbox';
import FederatedRoomDetail from './pages/FederatedRoomDetail';
import Calendar from './pages/Calendar';
import OAuthCallback from './pages/OAuthCallback';
import NotFound from './pages/NotFound';

export default function App() {
  const { user, loading } = useAuth();
  const { t, setLanguage } = useLanguage();
  const { appName } = useBranding();
  const location = useLocation();

  // Sync language from server when user loads
  useEffect(() => {
    if (user?.language) {
      setLanguage(user.language);
    }
  }, [user?.language, setLanguage]);

  // Unique, context-forward document title per page (SPA route changes
  // don't reload the document, so we update the title ourselves)
  useEffect(() => {
    const pageTitles = {
      '/dashboard': t('nav.dashboard'),
      '/calendar': t('nav.calendar'),
      '/settings': t('nav.settings'),
      '/admin': t('nav.admin'),
      '/federation': t('nav.federation'),
      '/login': t('auth.login'),
      '/register': t('auth.register'),
      '/forgot-password': t('auth.forgotPassword'),
    };
    const match = Object.entries(pageTitles).find(([path]) =>
      location.pathname === path || location.pathname.startsWith(`${path}/`)
    );
    document.title = match ? `${match[1]} | ${appName}` : `${appName} - BigBlueButton Frontend`;
  }, [location.pathname, appName, t]);

  if (loading) {
    return (
      <div className="min-h-screen bg-th-bg flex items-center justify-center" role="status" aria-label={t('common.loading')}>
        <div className="animate-spin rounded-full h-12 w-12 border-4 border-th-accent border-t-transparent" />
      </div>
    );
  }

  return (
    <Routes>
      {/* Public routes */}
      <Route path="/" element={user ? <Navigate to="/dashboard" /> : <Home />} />
      <Route path="/login" element={user ? <Navigate to="/dashboard" /> : <Login />} />
      <Route path="/register" element={user ? <Navigate to="/dashboard" /> : <Register />} />
      <Route path="/verify-email" element={<VerifyEmail />} />
      <Route path="/forgot-password" element={user ? <Navigate to="/dashboard" /> : <ForgotPassword />} />
      <Route path="/reset-password" element={<ResetPassword />} />
      <Route path="/oauth/callback" element={<OAuthCallback />} />
      <Route path="/join/:uid" element={<GuestJoin />} />

      {/* Protected routes */}
      <Route element={<ProtectedRoute><Layout /></ProtectedRoute>}>
        <Route path="/dashboard" element={<Dashboard />} />
        <Route path="/calendar" element={<Calendar />} />
        <Route path="/rooms/:uid" element={<RoomDetail />} />
        <Route path="/settings" element={<Settings />} />
        <Route path="/admin" element={<Admin />} />
        <Route path="/federation/inbox" element={<FederationInbox />} />
        <Route path="/federation/rooms/:id" element={<FederatedRoomDetail />} />
      </Route>

      {/* 404 */}
      <Route path="*" element={<NotFound />} />
    </Routes>
  );
}
