import { useState, useEffect, lazy, Suspense } from 'react';
import { Truck, Loader2, LogOut } from 'lucide-react';
import { DeliveryForm } from './components/delivery/DeliveryForm';
import { LoginForm } from './components/auth/LoginForm';
import { ToastContainer } from './components/ui/Toast';
import { Button } from './components/ui/Button';
import { useDeliveryStore } from './stores/deliveryStore';
import { useAuthStore } from './stores/authStore';
// Lazy load pages for code splitting
const Dashboard = lazy(() => import('./pages/Dashboard'));
const DeliveryListPage = lazy(() => import('./pages/DeliveryListPage'));
// Fallback loading component
const PageLoader = () => (
);
function App() {
const [view, setView] = useState<'dashboard' | 'delivery-list'>('dashboard');
const [selectedDate, setSelectedDate] = useState('');
const [isFormOpen, setIsFormOpen] = useState(false);
const [formDate, setFormDate] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const { isAuthenticated, isAuthChecking, restoreAuth, logout } = useAuthStore();
const addDelivery = useDeliveryStore(state => state.addDelivery);
const fetchDeliveryCounts = useDeliveryStore(state => state.fetchDeliveryCounts);
// Restore auth on mount
useEffect(() => {
restoreAuth();
}, [restoreAuth]);
// Refresh counts when form closes (only when authenticated)
useEffect(() => {
if (isAuthenticated && !isFormOpen) {
fetchDeliveryCounts();
}
}, [isAuthenticated, isFormOpen, fetchDeliveryCounts]);
const handleDateSelect = (date: string) => {
setSelectedDate(date);
setView('delivery-list');
};
const handleBackToDashboard = () => {
setView('dashboard');
setSelectedDate('');
};
const handleAddDelivery = () => {
const today = new Date().toLocaleDateString('ru-RU').split('.').join('-');
setFormDate(today);
setIsFormOpen(true);
};
const handleFormSubmit = async (data: Parameters[0]) => {
setIsSubmitting(true);
try {
await addDelivery(data);
setIsFormOpen(false);
// If created for different date, navigate to that date
const today = new Date().toLocaleDateString('ru-RU').split('.').join('-');
if (data.date !== today) {
setSelectedDate(data.date);
setView('delivery-list');
}
} catch {
// Error is handled by store
} finally {
setIsSubmitting(false);
}
};
// Show loading while checking auth
if (isAuthChecking) {
return (
);
}
// Show login form if not authenticated
if (!isAuthenticated) {
return (
<>
>
);
}
return (
{view === 'dashboard' ? 'Панель управления' : `Доставки на ${selectedDate}`}
}>
{view === 'dashboard' ? (
) : (
)}
setIsFormOpen(false)}
onSubmit={handleFormSubmit}
defaultDate={formDate}
isSubmitting={isSubmitting}
/>
);
}
export default App;