import { useState } from 'react';
import { Routes, Route, Navigate, useNavigate } from 'react-router-dom';
import { pb } from '@/services/pocketbase';

// Layout & Pages
import Login from '@/pages/Login';
import DashboardLayout from '@/layouts/DashboardLayout';
import TrustCenter from '@/pages/TrustCenter';
import ServiceDesk from '@/pages/ServiceDesk';
import DocumentVault from '@/pages/DocumentVault';
import AccountSettings from '@/pages/AccountSettings';
import { InfrastructureEvolution } from '@/pages/trustcenter/InfrastructureEvolution';
import Analytics from '@/pages/trustcenter/Analytics';
import Backups from '@/pages/trustcenter/Backups';
import NewTicket from '@/pages/servicedesk/NewTicket';
import TicketDetail from '@/pages/servicedesk/TicketDetail';
import UpdatePasswordPage from './pages/accountsettings/UpdatePasswordPage';

function App() {
  const [isAuthenticated, setIsAuthenticated] = useState(pb.authStore.isValid);
  const navigate = useNavigate();

  const handleLogout = () => {
    pb.authStore.clear();
    setIsAuthenticated(false);
    navigate('/', { replace: true });
  };

  // --- SAS DE SÉCURITÉ (Auth Guard) ---
  // Si non authentifié, on force l'affichage du composant Login peu importe l'URL demandée.
  if (!isAuthenticated) {
    return (
      <Routes>
        <Route
          path="*"
          element={
            <Login onLoginSuccess={() => {
              setIsAuthenticated(true);
              navigate('/dashboard', { replace: true });
            }} />
          }
        />
      </Routes>
    );
  }

  // --- APPLICATION SÉCURISÉE ---
  // Une fois connecté, le DashboardLayout enveloppe nos véritables routes (URLs)
  return (
    <DashboardLayout onLogout={handleLogout}>
      <Routes>
        {/* Redirection par défaut */}
        <Route path="/" element={<Navigate to="/dashboard" replace />} />

        {/* Pages du menu principal */}
        <Route path="/dashboard" element={<TrustCenter />} />
        <Route path="/support" element={<ServiceDesk />} />
        <Route path="/vault" element={<DocumentVault />} />
        <Route path="/account" element={<AccountSettings />} />

        {/* Pages stratégiques (anciennes modales) */}
        <Route path="/evolution-infrastructure" element={<InfrastructureEvolution />} />
        <Route path="/analytics" element={<Analytics />} />
        <Route path="/backups" element={<Backups />} />
        <Route path="/support/new" element={<NewTicket />} />
        <Route path="/support/tickets/:ticketId" element={<TicketDetail />} />
        <Route path="/settings/security/password" element={<UpdatePasswordPage />} />

        {/* Sécurité : Si l'URL n'existe pas, on redirige vers le dashboard */}
        <Route path="*" element={<Navigate to="/dashboard" replace />} />
      </Routes>
    </DashboardLayout>
  );
}

export default App;