import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom'
import { AuthProvider } from './auth/AuthProvider'
import { LoginPage } from './screens/LoginPage'
import { ConsoleLayout } from './screens/ConsoleLayout'

import { DatasetItemsPage } from './screens/admin/DatasetItemsPage'
import { ProtectedRoute, getDefaultRoute } from './auth/ProtectedRoute'
import { useAuth } from './auth/context'

function RootRedirect() {
  const { roles, isAdmin } = useAuth();
  return <Navigate to={getDefaultRoute(roles, isAdmin)} replace />;
}

import { routeConfig } from './routesConfig'

function App() {
  return (
    <AuthProvider>
      <BrowserRouter basename="/krishna_sales">
        <Routes>
          <Route path="/login" element={<LoginPage />} />
          <Route element={<ConsoleLayout />}>
            {routeConfig.map((route, i) => {
              const path = route.path.startsWith('/') ? route.path.substring(1) : route.path;
              
              // Maintain nested route for Dataset items specifically
              if (path === 'admin/datasets') {
                return (
                  <Route 
                    key={i} 
                    path={path} 
                    element={<ProtectedRoute adminOnly={route.adminOnly} roles={route.roles}>{route.element}</ProtectedRoute>}
                  >
                    <Route path=":id" element={<DatasetItemsPage />} />
                  </Route>
                );
              }

              return (
                <Route 
                  key={i} 
                  path={path} 
                  element={<ProtectedRoute roles={route.roles} adminOnly={route.adminOnly}>{route.element}</ProtectedRoute>} 
                />
              );
            })}
            
            <Route path="*" element={<RootRedirect />} />
          </Route>
        </Routes>
      </BrowserRouter>
    </AuthProvider>
  )
}

export default App
