import React from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { AuthProvider, useAuth } from './contexts/AuthContext';
import { MessagingProvider } from './contexts/MessagingContext';
import MainLayout from './mockup/MainLayout';
import LandingPage from './mockup/pages/LandingPage';
import LoginPage from './mockup/pages/LoginPage';
import RegisterPage from './mockup/pages/RegisterPage';
import AboutPage from './mockup/pages/AboutPage';
import FeaturesPage from './mockup/pages/FeaturesPage';
import './index.css';
import './mockup/mockup.css';

/**
 * Protected route - requires authentication
 */
function ProtectedRoute({ children }) {
  const { isAuthenticated, loading } = useAuth();
  
  if (loading) {
    return (
      <div className="loading-screen">
        <div className="loading-spinner"></div>
        <span>Loading...</span>
      </div>
    );
  }
  
  return isAuthenticated ? children : <Navigate to="/login" replace />;
}

/**
 * Public route - redirects to app if logged in
 */
function PublicRoute({ children }) {
  const { isAuthenticated, loading } = useAuth();
  
  if (loading) {
    return (
      <div className="loading-screen">
        <div className="loading-spinner"></div>
        <span>Loading...</span>
      </div>
    );
  }
  
  return !isAuthenticated ? children : <Navigate to="/app" replace />;
}

/**
 * Main app with routing
 */
function AppRoutes() {
  const { login, register, logout } = useAuth();

  return (
    <Routes>
      {/* Marketing pages - public */}
      <Route path="/" element={<LandingPage />} />
      <Route path="/features" element={<FeaturesPage />} />
      <Route path="/about" element={<AboutPage />} />
      
      {/* Auth pages */}
      <Route path="/login" element={
        <PublicRoute>
          <LoginPage onLogin={login} />
        </PublicRoute>
      } />
      <Route path="/register" element={
        <PublicRoute>
          <RegisterPage onRegister={register} />
        </PublicRoute>
      } />
      
      {/* Connect App - protected */}
      <Route path="/app" element={
        <ProtectedRoute>
          <MessagingProvider>
            <MainLayout onLogout={logout} />
          </MessagingProvider>
        </ProtectedRoute>
      } />
      <Route path="/app/*" element={
        <ProtectedRoute>
          <MessagingProvider>
            <MainLayout onLogout={logout} />
          </MessagingProvider>
        </ProtectedRoute>
      } />
      
      {/* Catch all - redirect to home */}
      <Route path="*" element={<Navigate to="/" replace />} />
    </Routes>
  );
}

export default function App() {
  return (
    <BrowserRouter>
      <AuthProvider>
        <AppRoutes />
      </AuthProvider>
    </BrowserRouter>
  );
}
