import { lazy, Suspense } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import SessionGate from './components/SessionGate';
import Layout from './components/Layout/Layout';
import { WebSocketProvider } from './context/WebSocketProvider';
import { ForgeProvider } from './context/ForgeContext';
import { MatrixRainProvider } from './context/MatrixRainContext';

const DashboardPage = lazy(() => import('./pages/DashboardPage'));
const AgentsPage = lazy(() => import('./pages/AgentsPage'));
const BuilderPage = lazy(() => import('./pages/BuilderPage'));
const BuildManagerPage = lazy(() => import('./pages/BuildManagerPage'));
const SettingsPage = lazy(() => import('./pages/SettingsPage'));
const GuidePage = lazy(() => import('./pages/GuidePage'));
const CruciblePage = lazy(() => import('./pages/CruciblePage'));

export function PageFallback() {
  return (
    <div className="session-gate" style={{ minHeight: '40vh' }}>
      <p className="font-tech">Loading…</p>
    </div>
  );
}

function App() {
  return (
    // WebSocketProvider mounts a single WS connection shared by all routes.
    // No page or component should call new WebSocket() directly — use useWebSocket().
    <WebSocketProvider>
      <ForgeProvider>
      <MatrixRainProvider>
      <SessionGate>
      <Layout>
        <Suspense fallback={<PageFallback />}>
          <Routes>
            <Route path="/" element={<Navigate to="/dashboard" replace />} />
            <Route path="/dashboard" element={<DashboardPage />} />
            <Route path="/agents" element={<AgentsPage />} />
            <Route path="/forge" element={<BuilderPage />} />
            <Route path="/builder" element={<Navigate to="/forge" replace />} />
            <Route path="/crucible" element={<CruciblePage />} />
            <Route path="/builds" element={<BuildManagerPage />} />
            <Route path="/guide" element={<GuidePage />} />
            <Route path="/settings" element={<SettingsPage />} />
          </Routes>
        </Suspense>
      </Layout>
      </SessionGate>
      </MatrixRainProvider>
      </ForgeProvider>
    </WebSocketProvider>
  );
}

export default App;
