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 { SoundProvider } from './context/SoundContext';
import { VisualEffectsProvider } from './context/VisualEffectsContext';
import { ForgeProvider } from './context/ForgeContext';
import { MatrixRainProvider } from './context/MatrixRainContext';
import SoundBridge from './components/Sound/SoundBridge';

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'));
const PathTracerPage = lazy(() => import('./pages/PathTracerPage'));

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>
      <SoundProvider>
      <VisualEffectsProvider>
      <SoundBridge />
      <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 />} />
            <Route path="/pathtracer" element={<PathTracerPage />} />
          </Routes>
        </Suspense>
      </Layout>
      </SessionGate>
      </MatrixRainProvider>
      </ForgeProvider>
      </VisualEffectsProvider>
      </SoundProvider>
    </WebSocketProvider>
  );
}

export default App;
