import React, { lazy, Suspense } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import MobileLayout from './layout/MobileLayout';
import LoadingSpinner from '../components/common/LoadingSpinner';
import { useAuth } from '../contexts/AuthContext';

const MobileHome = lazy(() => import('./pages/MobileHome'));
const MobileCatalog = lazy(() => import('./pages/MobileCatalog'));
const MobileProfile = lazy(() => import('./pages/MobileProfile'));
const MobileRating = lazy(() => import('./pages/MobileRating'));
const MobileLogin = lazy(() => import('./pages/MobileLogin'));
const MobileRegister = lazy(() => import('./pages/MobileRegister'));
const MobileMediaOverviewPage = lazy(() => import('./pages/MobileMediaOverviewPage'));
const MobileMediaForm = lazy(() => import('./components/MobileMediaForm'));
const MobileNotFound = lazy(() => import('./pages/MobileNotFound'));

const LazyLoad = ({ children }) => (
  <Suspense fallback={<LoadingSpinner />}>{children}</Suspense>
);

const PrivateRoute = ({ children }) => {
  const { isAuthenticated } = useAuth();
  return isAuthenticated ? children : <Navigate to="/auth/login" />;
};

const MobileRoutes = () => {
  return (
    <Routes>
      {/* Страницы авторизации */}
      <Route path="/auth">
        <Route path="login" element={<LazyLoad><MobileLogin /></LazyLoad>} />
        <Route path="register" element={<LazyLoad><MobileRegister /></LazyLoad>} />
      </Route>

      {/* Все остальные страницы внутри MobileLayout */}
      <Route path="/" element={<MobileLayout />}>
        <Route index element={<LazyLoad><MobileHome /></LazyLoad>} />
        <Route path="catalog" element={<LazyLoad><MobileCatalog /></LazyLoad>} />
        <Route path="rating" element={<LazyLoad><MobileRating /></LazyLoad>} />
        <Route path="media/:path" element={<LazyLoad><MobileMediaOverviewPage /></LazyLoad>} />
        <Route path="profile" element={<PrivateRoute><LazyLoad><MobileProfile /></LazyLoad></PrivateRoute>} />
        <Route path="profile/:login" element={<LazyLoad><MobileProfile /></LazyLoad>} />
        <Route path="*" element={<LazyLoad><MobileNotFound /></LazyLoad>} />
      </Route>
      <Route
        path="/media/new"
        element={
          <PrivateRoute>
            <MobileMediaForm />
          </PrivateRoute>
        }
      />
    </Routes>
  );
};

export default MobileRoutes; 