import React from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { AuthProvider, useAuth } from './context/AuthContext';
import ProtectedRoute from './components/ProtectedRoute';

// Páginas
import Login from './pages/Login';
import AdminDashboard from './pages/AdminDashboard';
import WaiterPOS from './pages/WaiterPOS';
import CustomerMenu from './pages/CustomerMenu';
import KitchenView from './pages/KitchenView';

// Router base para redirigir dependiendo del rol al loguearse
function RootRedirect() {
  const { currentUser, userRole, loading } = useAuth();
  if (loading) return <div className="app-container" style={{justifyContent:'center', alignItems:'center'}}>Cargando...</div>;
  if (!currentUser) return <Navigate to="/login" replace />;
  if (userRole === 'admin') return <Navigate to="/admin" replace />;
  if (userRole === 'mesero') return <Navigate to="/pos" replace />;
  return <Navigate to="/login" replace />; // Default
}

function App() {
  return (
    <Router>
      <AuthProvider>
        <Routes>
          <Route path="/" element={<RootRedirect />} />
          <Route path="/login" element={<Login />} />
          <Route path="/menu" element={<CustomerMenu />} />

          {/* Rutas Privadas */}
          <Route 
            path="/admin/*" 
            element={
              <ProtectedRoute allowedRoles={['admin']}>
                <AdminDashboard />
              </ProtectedRoute>
            } 
          />
          <Route 
            path="/pos/*" 
            element={
              <ProtectedRoute allowedRoles={['admin', 'mesero']}>
                <WaiterPOS />
              </ProtectedRoute>
            } 
          />
          <Route 
            path="/kitchen" 
            element={
              <ProtectedRoute allowedRoles={['admin', 'mesero']}>
                <KitchenView />
              </ProtectedRoute>
            } 
          />

          {/* Fallback */}
          <Route path="*" element={<Navigate to="/" replace />} />
        </Routes>
      </AuthProvider>
    </Router>
  );
}

export default App;
