'use client'; import { useState, useEffect, useCallback, Suspense, Component } from 'react'; import { useRouter } from 'next/navigation'; import dynamic from 'next/dynamic'; import { OrderItem } from '@/lib/types'; import { useAuth } from '@/components/AuthProvider'; import BottomNav from '@/components/BottomNav'; import { getMyAssignedItems, getMyAssignedStockItems, getPoolItems, getProblemItems, isAuthenticated } from '@/lib/pocketbase'; import { getCached, setCached } from '@/lib/itemsCache'; import { cn } from '@/lib/utils'; import { RefreshCw, MapPin, AlertCircle, Package, Inbox, AlertTriangle } from 'lucide-react'; // Sync the map's dataset with the list page's selected tab via // localStorage so a driver who flips to "Pool" on the list and then // taps Map sees the same pool stops, not just their assigned list. const MAP_TAB_KEY = '1driver_map_tab'; type MapTab = 'assigned' | 'collection_pool' | 'problem'; const CollectionMap = dynamic(() => import('@/components/CollectionMap'), { ssr: false, loading: () => (

Loading map...

), }); class MapErrorBoundary extends Component<{ children: React.ReactNode }, { hasError: boolean; error: string }> { constructor(props: { children: React.ReactNode }) { super(props); this.state = { hasError: false, error: '' }; } static getDerivedStateFromError(error: Error) { return { hasError: true, error: error.message }; } render() { if (this.state.hasError) { return (

Map failed to load.

); } return this.props.children; } } export default function MapPage() { const router = useRouter(); const { isLoggedIn, isLoading: authLoading } = useAuth(); // Seed from cache so bottom-nav → Map renders last-known stops // instantly. The re-fetch in the useEffect below updates the map // with fresh data when it lands, but the driver never sees an // empty map flash. const [items, setItems] = useState(() => { if (typeof window === 'undefined') return []; return getCached('assigned') ?? []; }); const [isLoading, setIsLoading] = useState(items.length === 0); const [isRefreshing, setIsRefreshing] = useState(false); const [error, setError] = useState(''); const [tab, setTab] = useState('assigned'); useEffect(() => { if (typeof window !== 'undefined') { const saved = window.localStorage.getItem(MAP_TAB_KEY); if (saved === 'assigned' || saved === 'collection_pool' || saved === 'problem') { setTab(saved); } } }, []); useEffect(() => { if (!authLoading && !isLoggedIn) router.push('/login/'); }, [isLoggedIn, authLoading, router]); const loadItems = useCallback(async (showLoading = true) => { if (!isAuthenticated()) return; // Only show the loading skeleton on the first-ever load. After // that the cache guarantees we have something on screen, so // the re-fetch is silent. if (showLoading && items.length === 0) setIsLoading(true); setError(''); try { let data: OrderItem[] = []; if (tab === 'assigned') { // Merge order_items + stock_purchase_items (the "My stops" // tab is the same scope as the Assigned list on page.tsx). const [orders, stock] = await Promise.all([ getMyAssignedItems(), getMyAssignedStockItems(), ]); data = [...orders, ...stock]; } else if (tab === 'collection_pool') { data = await getPoolItems(); } else { data = await getProblemItems(); } setItems(data); setCached(tab, data); } catch (err) { console.error('Failed to load collections:', err); setError('Failed to load collections'); } finally { setIsLoading(false); setIsRefreshing(false); } }, [tab, items.length]); useEffect(() => { if (typeof window !== 'undefined') window.localStorage.setItem(MAP_TAB_KEY, tab); // Seed from cache BEFORE the re-fetch lands — same pattern as // the list page, so tab/filter switches show last-known data // instantly instead of an empty map. const cached = getCached(tab); if (cached) setItems(cached); loadItems(); }, [tab, loadItems]); const handleTabChange = (next: MapTab) => { setTab(next); }; const handleNavigate = (lat: number, lng: number, name: string) => { const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent); const url = isIOS ? `maps://maps.apple.com/?q=${encodeURIComponent(name)}&ll=${lat},${lng}` : `https://www.google.com/maps/dir/?api=1&destination=${lat},${lng}`; window.open(url, '_blank'); }; if (authLoading) { return (

Loading...

); } if (!isLoggedIn) return null; return (
{isLoading ? (

Loading map...

) : error ? (

{error}

) : items.length === 0 ? (

No collections to show

All collections completed!

) : (
}>
)}
); }