import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { AuthProvider, useAuth } from './contexts/AuthContext.jsx';
import { SocketProvider } from './contexts/SocketContext.jsx';
import { ToastProvider } from './contexts/ToastContext.jsx';
import Login from './pages/Login.jsx';
import Chat from './pages/Chat.jsx';
import ChangePassword from './pages/ChangePassword.jsx';

function ProtectedRoute({ children }) {
  const { user, loading, mustChangePassword } = useAuth();
  if (loading) return (
    <div style={{ height: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div className="spinner" style={{ width: 36, height: 36 }} />
    </div>
  );
  if (!user) return <Navigate to="/login" replace />;
  if (mustChangePassword) return <Navigate to="/change-password" replace />;
  return children;
}

function AuthRoute({ children }) {
  const { user, loading, mustChangePassword } = useAuth();
  document.documentElement.setAttribute('data-theme', 'light');
  if (loading) return null;
  if (user && !mustChangePassword) return <Navigate to="/" replace />;
  return children;
}

function RestoreTheme() {
  const saved = localStorage.getItem('jama-theme') || 'light';
  document.documentElement.setAttribute('data-theme', saved);
  return null;
}

export default function App() {
  return (
    <BrowserRouter>
      <ToastProvider>
        <Routes>
          {/* All routes go through jama auth */}
          <Route path="/*" element={
            <AuthProvider>
              <SocketProvider>
                <Routes>
                  <Route path="/login" element={<AuthRoute><Login /></AuthRoute>} />
                  <Route path="/change-password" element={<ChangePassword />} />
                  <Route path="/" element={<ProtectedRoute><RestoreTheme /><Chat /></ProtectedRoute>} />
                  <Route path="*" element={<Navigate to="/" replace />} />
                </Routes>
              </SocketProvider>
            </AuthProvider>
          } />
        </Routes>
      </ToastProvider>
    </BrowserRouter>
  );
}
