import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import { QueryClientProvider } from '@tanstack/react-query';
import { Toaster } from '@/components/ui/toaster';
import { queryClientInstance } from '@/lib/query-client';
import ScrollToTop from '@/components/ScrollToTop';
import PageNotFound from '@/lib/PageNotFound';
import ScanForgeAgentWorkspace from '@/components/scanforge/ScanForgeAgentWorkspace';
import { ScannerProvider } from '@/context/ScannerContext';
import { ShireModuleProvider } from '@/context/ShireModuleContext';
import { appConfig } from '@/lib/appConfig';
import ScannerRoutes from '@/ScannerRoutes';

const StandaloneApp = lazy(() => import('@/StandaloneApp'));

function ShireModuleApp() {
  return (
    <ShireModuleProvider>
      <ScannerProvider>
        <Routes>
          <Route path={`${appConfig.scanforgeRoute}/*`} element={<ScanForgeAgentWorkspace />}>
            <Route path="*" element={<ScannerRoutes />} />
          </Route>
          <Route path="*" element={<PageNotFound />} />
        </Routes>
      </ScannerProvider>
    </ShireModuleProvider>
  );
}

export default function App() {
  return (
    <QueryClientProvider client={queryClientInstance}>
      <Router>
        <ScrollToTop />
        {appConfig.mode === 'SHIRE_MODULE' ? (
          <ShireModuleApp />
        ) : (
          <Suspense fallback={<div className="fixed inset-0 flex items-center justify-center text-zinc-400">Loading ScanForge…</div>}>
            <StandaloneApp />
          </Suspense>
        )}
      </Router>
      <Toaster />
    </QueryClientProvider>
  );
}
