import { Routes, Route, Navigate, Outlet } from 'react-router-dom';
import { Sidebar } from './components/Sidebar';
import { TopNav } from './components/TopNav';
import LibraryGrid from './components/LibraryGrid';
import { Login } from './components/Login';
import { GamesPage } from './components/GamesPage';
import { CollectionsPage } from './components/CollectionsPage';
import { Settings } from './components/Settings';
import { AuthProvider, useAuth } from './context/AuthContext';
import { useGamepad } from './hooks/useGamepad';

const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
  const { isAuthenticated } = useAuth();
  if (!isAuthenticated) {
    return <Navigate to="/login" replace />;
  }
  return <>{children}</>;
};

const MainLayout = () => {
  return (
    <div className="min-h-screen text-foreground selection:bg-[#2563eb]/30 overflow-hidden bg-[#10131f]">
      <Sidebar />
      <TopNav />
      <main className="ml-[16rem] pt-16 h-screen overflow-y-auto no-scrollbar">
        <Outlet />
      </main>
    </div>
  );
};

function App() {
  useGamepad();

  return (
    <AuthProvider>
      <Routes>
        <Route path="/login" element={<Login />} />
        <Route 
          path="/*" 
          element={
            <ProtectedRoute>
              <MainLayout />
            </ProtectedRoute>
          } 
        >
          <Route index element={<LibraryGrid />} />
          <Route path="games" element={<GamesPage />}>
            <Route path=":platformId" element={<GamesPage />}>
              <Route path=":romId" element={<GamesPage />} />
            </Route>
          </Route>
          <Route path="collections" element={<CollectionsPage />}>
            <Route path=":collectionId" element={<CollectionsPage />}>
              <Route path=":romId" element={<CollectionsPage />} />
            </Route>
          </Route>
          <Route path="settings" element={<Settings />} />
        </Route>
      </Routes>
    </AuthProvider>
  );
}

export default App;
