import { lazy, Suspense, Component } from 'react';
import { BrowserRouter, Routes, Route, Navigate, useParams } from 'react-router-dom';
import { AuthProvider, useAuth } from './context/AuthContext';
import ProtectedRoute from './components/ProtectedRoute';
import PageLoader from './components/PageLoader';

class ChunkErrorBoundary extends Component {
  state = { error: null };
  static getDerivedStateFromError(error) { return { error }; }
  componentDidCatch(error) {
    const isChunkError = error?.name === 'ChunkLoadError'
      || error?.message?.includes('dynamically imported module')
      || error?.message?.includes('Failed to fetch');
    if (isChunkError) {
      const key = 'chunk_reload_attempted';
      if (!sessionStorage.getItem(key)) {
        sessionStorage.setItem(key, '1');
        window.location.reload();
        return;
      }
      sessionStorage.removeItem(key);
    }
  }
  render() {
    if (this.state.error) {
      return (
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '60vh', gap: 16 }}>
          <div style={{ fontSize: 14, color: 'var(--text-secondary)' }}>Page failed to load.</div>
          <button className="btn btn-primary" onClick={() => { sessionStorage.removeItem('chunk_reload_attempted'); this.setState({ error: null }); window.location.reload(); }}>
            Reload
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

import Login from './pages/Login';
import PayInvoice from './pages/PayInvoice';

const ProfilePage = lazy(() => import('./pages/Settings'));
const CompaniesPage = lazy(() => import('./pages/CompaniesPage'));
const CompanyDetail = lazy(() => import('./pages/CompanyDetail'));
const Invoices = lazy(() => import('./pages/team/Invoices'));
const RequestDetail = lazy(() => import('./pages/RequestDetail'));
const CreateInvoice = lazy(() => import('./pages/team/CreateInvoice'));
const CreateSubcontractorPO = lazy(() => import('./pages/team/CreateSubcontractorPO'));
const InvoiceDetail = lazy(() => import('./pages/team/InvoiceDetail'));
const SubcontractorPODetail = lazy(() => import('./pages/team/SubcontractorPODetail'));
const SubInvoiceDetail = lazy(() => import('./pages/team/SubInvoiceDetail'));
const SurveyMaker = lazy(() => import('./pages/SurveyMaker'));
const BrandBook = lazy(() => import('./pages/BrandBook'));
const Converters = lazy(() => import('./pages/Converters'));
const FileSharing = lazy(() => import('./pages/FileSharing'));
const FourgePasswords = lazy(() => import('./pages/team/FourgePasswords'));
const MyPurchaseOrders = lazy(() => import('./pages/external/MyPurchaseOrders'));
const ExternalMyInvoices = lazy(() => import('./pages/external/MyInvoices'));
const ExternalMyInvoiceDetail = lazy(() => import('./pages/external/MyInvoiceDetail'));
const ExternalMyInvoiceCreate = lazy(() => import('./pages/external/MyInvoiceCreate'));
const Projects = lazy(() => import('./pages/Projects'));
const ProjectDetailPage = lazy(() => import('./pages/ProjectDetailPage'));
const DashboardPage = lazy(() => import('./pages/DashboardPage'));
const TeamDashboard = lazy(() => import('./pages/team/TeamDashboard'));
const RequestsPage = lazy(() => import('./pages/RequestsPage'));
const TeamTasksPage = lazy(() => import('./pages/team/TeamTasksPage'));
const MyInvoices = lazy(() => import('./pages/client/MyInvoices'));
const NewRequest = lazy(() => import('./pages/client/NewRequest'));
const NewProject = lazy(() => import('./pages/client/NewProject'));

function RedirectProjectDetail() {
  const { id } = useParams();
  return <Navigate to={`/projects/${id}`} replace />;
}

function RedirectRequestDetail() {
  const { id } = useParams();
  return <Navigate to={`/requests/${id}`} replace />;
}

function NavigateCompanyDetail() {
  const { id } = useParams();
  return <Navigate to={`/company/${id}`} replace />;
}



export default function App() {
  return (
    <AuthProvider>
      <BrowserRouter>
        <ChunkErrorBoundary>
        <Suspense fallback={<PageLoader />}>
        <Routes>
          <Route path="/" element={<Login />} />

          <Route path="/dashboard" element={<ProtectedRoute role={['team', 'external', 'client']}><TeamDashboard /></ProtectedRoute>} />
          <Route path="/projects" element={<ProtectedRoute role={['team', 'external', 'client']}><Projects /></ProtectedRoute>} />
          <Route path="/projects/:id" element={<ProtectedRoute role={['team', 'external', 'client']}><ProjectDetailPage /></ProtectedRoute>} />
          <Route path="/tasks/:id" element={<RedirectRequestDetail />} />
          <Route path="/requests/:id" element={<ProtectedRoute role={['team', 'external', 'client']}><RequestDetail /></ProtectedRoute>} />
          <Route path="/company" element={<ProtectedRoute role={['team', 'client']}><CompaniesPage /></ProtectedRoute>} />
          <Route path="/company/:id" element={<ProtectedRoute role={['team', 'client']}><CompanyDetail /></ProtectedRoute>} />
          <Route path="/companies" element={<Navigate to="/company" replace />} />
          <Route path="/companies/:id" element={<NavigateCompanyDetail />} />
          <Route path="/team/tasks" element={<ProtectedRoute role="team"><TeamTasksPage /></ProtectedRoute>} />
          <Route path="/requests" element={<ProtectedRoute role={['external', 'client']}><RequestsPage /></ProtectedRoute>} />
          <Route path="/team-projects" element={<Navigate to="/projects" replace />} />
          <Route path="/invoices" element={<ProtectedRoute role="team"><Invoices /></ProtectedRoute>} />
          <Route path="/invoices/new" element={<ProtectedRoute role="team"><CreateInvoice /></ProtectedRoute>} />
          <Route path="/subcontractor-pos/new" element={<ProtectedRoute role="team"><CreateSubcontractorPO /></ProtectedRoute>} />
          <Route path="/invoices/:id" element={<ProtectedRoute role="team"><InvoiceDetail /></ProtectedRoute>} />
          <Route path="/subcontractor-pos/:id" element={<ProtectedRoute role="team"><SubcontractorPODetail /></ProtectedRoute>} />
          <Route path="/sub-invoices/:id" element={<ProtectedRoute role="team"><SubInvoiceDetail /></ProtectedRoute>} />
          <Route path="/survey-maker" element={<ProtectedRoute role={['team', 'external']}><SurveyMaker /></ProtectedRoute>} />
          <Route path="/brand-book" element={<ProtectedRoute role={['team', 'external']}><BrandBook /></ProtectedRoute>} />
          <Route path="/converters" element={<ProtectedRoute role={['team', 'external']}><Converters /></ProtectedRoute>} />
          <Route path="/file-sharing" element={<ProtectedRoute role={['team', 'external', 'client']}><FileSharing /></ProtectedRoute>} />
          <Route path="/file-uploads" element={<Navigate to="/file-sharing" replace />} />
          <Route path="/fourge-passwords" element={<ProtectedRoute role="team"><FourgePasswords /></ProtectedRoute>} />
          <Route path="/server-status" element={<Navigate to="/dashboard" replace />} />
          <Route path="/assigned-requests" element={<Navigate to="/requests" replace />} />
          <Route path="/my-purchase-orders" element={<ProtectedRoute role="external"><MyPurchaseOrders /></ProtectedRoute>} />
          <Route path="/my-projects-sub" element={<Navigate to="/projects" replace />} />
          <Route path="/my-invoices-sub" element={<ProtectedRoute role="external"><ExternalMyInvoices /></ProtectedRoute>} />
          <Route path="/my-invoices-sub/new" element={<ProtectedRoute role="external"><ExternalMyInvoiceCreate /></ProtectedRoute>} />
          <Route path="/my-invoices-sub/:id" element={<ProtectedRoute role="external"><ExternalMyInvoiceDetail /></ProtectedRoute>} />

          <Route path="/profile" element={<ProtectedRoute><ProfilePage /></ProtectedRoute>} />
          <Route path="/profile/:id" element={<ProtectedRoute><ProfilePage /></ProtectedRoute>} />
          <Route path="/settings" element={<Navigate to="/profile" replace />} />

          <Route path="/my-dashboard" element={<Navigate to="/dashboard" replace />} />
          <Route path="/my-company" element={<Navigate to="/company" replace />} />
          <Route path="/my-requests" element={<Navigate to="/requests" replace />} />
          <Route path="/my-requests/:id" element={<RedirectRequestDetail />} />
          <Route path="/my-projects" element={<Navigate to="/projects" replace />} />
          <Route path="/my-projects/:id" element={<RedirectProjectDetail />} />
          <Route path="/my-invoices" element={<ProtectedRoute role="client"><MyInvoices /></ProtectedRoute>} />
          <Route path="/new-request" element={<ProtectedRoute role="client"><NewRequest /></ProtectedRoute>} />
          <Route path="/new-project" element={<ProtectedRoute role="client"><NewProject /></ProtectedRoute>} />

          <Route path="/pay/:id" element={<PayInvoice />} />
          <Route path="*" element={<Navigate to="/" replace />} />
        </Routes>
        </Suspense>
        </ChunkErrorBoundary>
      </BrowserRouter>
    </AuthProvider>
  );
}
