import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { App as AntApp } from 'antd';
import { Suspense, lazy } from 'react';
import { Spin } from 'antd';
import AppRoutes from './routes';
import AppLayout from './components/layout/AppLayout';
import ProtectedRoute from './components/auth/ProtectedRoute';
import CompanyGuard from './components/auth/CompanyGuard';

// Lazy load CompanySetupWizard
const CompanySetupWizard = lazy(() => import('./pages/CompanySetupWizard'));

// Loading fallback component
function PageLoader() {
  return (
    <Spin
      size="large"
      tip="Indlæser..."
      style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
      }}
    >
      <div style={{ minHeight: 200 }} />
    </Spin>
  );
}

function App() {
  return (
    <AntApp>
      <BrowserRouter>
        <Routes>
          {/* Wizard route OUTSIDE CompanyGuard to prevent navigation loop */}
          <Route
            path="/opret-virksomhed"
            element={
              <ProtectedRoute>
                <Suspense fallback={<PageLoader />}>
                  <CompanySetupWizard />
                </Suspense>
              </ProtectedRoute>
            }
          />

          {/* All other routes with full guard chain */}
          <Route
            path="/*"
            element={
              <ProtectedRoute>
                <CompanyGuard>
                  <AppLayout>
                    <AppRoutes />
                  </AppLayout>
                </CompanyGuard>
              </ProtectedRoute>
            }
          />
        </Routes>
      </BrowserRouter>
    </AntApp>
  );
}

export default App;
