import { useCallback } from 'react'; import dayjs from 'dayjs'; import { useCentralSlotStore } from '@/src/store/centralSlotStore'; export function useProductSlotIdentifier() { // Get slots data from central store const slots = useCentralSlotStore((state) => state.slots); const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap); // Memoised: a fresh function every render invalidates every memo that lists // it as a dependency (the home catalogue map included), so it never settles. const getQuickestSlot = useCallback((productId: number): number | null => { if (!slots?.length) return null; const now = dayjs(); const productInfo = productSlotsMap[productId]; if (!productInfo?.slots?.length) return null; // Find slots that contain this product and have future delivery time const availableSlots = productInfo.slots.filter((slot: any) => dayjs(slot.deliveryTime).isAfter(now) ); if (availableSlots.length === 0) return null; // Return earliest slot ID (sorted by delivery time) const earliestSlot = availableSlots.sort((a: any, b: any) => dayjs(a.deliveryTime).diff(dayjs(b.deliveryTime)) )[0]; return earliestSlot.id; }, [slots, productSlotsMap]); return { getQuickestSlot, productSlotsMap }; }