import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { AuthProvider, useAuth } from './context/AuthContext';
import { ThemeProvider } from './context/ThemeContext';
import Dashboard from './pages/Dashboard';
import AuthCallback from './pages/AuthCallback';
import PrivateRoute from './components/PrivateRoute';
import UploadMobile from './pages/UploadMobile';
import RoleSelector from './components/RoleSelector';
import Login from './pages/Login';

// ── Garde intermédiaire pour la sélection de rôle ─────
const AppRoutes = (): JSX.Element => {
    const { user, needsRoleSelection, selectRole, allRoles } = useAuth();

    if (user && needsRoleSelection) {
        return (
            <RoleSelector
                roles={allRoles}
                userName={user.name}
                onSelect={selectRole}
            />
        );
    }

    return (
        <Router>
            <Routes>
                <Route path="/" element={<Navigate to="/login" replace />} />
                <Route path="/login" element={<Login />} />
                <Route path="/auth/callback" element={<AuthCallback />} />
                <Route path="/dashboard" element={
                    <PrivateRoute>
                        <Dashboard />
                    </PrivateRoute>
                } />
                <Route path="/upload/:token" element={<UploadMobile />} />
            </Routes>
        </Router>
    );
};

function App(): JSX.Element {
    return (
        <ThemeProvider>
            <AuthProvider>
                <AppRoutes />
            </AuthProvider>
        </ThemeProvider>
    );
}

export default App;