import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
import { AuthProvider, useAuth } from '@/auth/AuthProvider';
import { LoginPage } from '@/pages/LoginPage';
import { ProjectsPage } from '@/pages/ProjectsPage';
import { EditorPage } from '@/pages/EditorPage';
import { MembersPage } from '@/pages/MembersPage';
import { IntegrationPage } from '@/pages/IntegrationPage';
import { InvitationPage } from '@/pages/InvitationPage';
import { AdminPage } from '@/pages/AdminPage';
import { PlatformsPage } from '@/pages/PlatformsPage';
import './app.css';

const queryClient = new QueryClient({
    defaultOptions: {
        queries: {
            // Les données changent parce que d'AUTRES personnes travaillent
            // dessus. Un rafraîchissement au retour sur l'onglet est le bon
            // compromis entre fraîcheur et calme visuel.
            refetchOnWindowFocus: true,
            staleTime: 30_000,
            retry: (failureCount, error) =>
                failureCount < 2 && !(error instanceof Error && error.name === 'ApiError'),
        },
    },
});

function Protected({ children }: { children: React.ReactNode }) {
    const { user, loading } = useAuth();

    if (loading) {
        return (
            <div className="flex h-full items-center justify-center text-ink-400">
                <span className="text-sm">Chargement…</span>
            </div>
        );
    }

    return user ? <>{children}</> : <Navigate to="/login" replace />;
}

function App() {
    return (
        <Routes>
            <Route path="/login" element={<LoginPage />} />
            {/* Page publique : celui qui clique n'a pas encore de compte. */}
            <Route path="/invitation/:token" element={<InvitationPage />} />
            <Route
                path="/projects"
                element={
                    <Protected>
                        <ProjectsPage />
                    </Protected>
                }
            />
            <Route
                path="/admin"
                element={
                    <Protected>
                        <AdminPage />
                    </Protected>
                }
            />
            <Route
                path="/p/:projectUuid/editor"
                element={
                    <Protected>
                        <EditorPage />
                    </Protected>
                }
            />
            <Route
                path="/p/:projectUuid/members"
                element={
                    <Protected>
                        <MembersPage />
                    </Protected>
                }
            />
            <Route
                path="/p/:projectUuid/platforms"
                element={
                    <Protected>
                        <PlatformsPage />
                    </Protected>
                }
            />
            <Route
                path="/p/:projectUuid/integration"
                element={
                    <Protected>
                        <IntegrationPage />
                    </Protected>
                }
            />
            <Route path="*" element={<Navigate to="/projects" replace />} />
        </Routes>
    );
}

const root = document.getElementById('root');

if (root) {
    createRoot(root).render(
        <StrictMode>
            <QueryClientProvider client={queryClient}>
                <BrowserRouter>
                    <AuthProvider>
                        <App />
                    </AuthProvider>
                </BrowserRouter>
            </QueryClientProvider>
        </StrictMode>,
    );
}
