"use client"; import { useCallback } from "react"; import { createCheckoutService } from "@/lib/services/checkoutService"; interface UseShippingMethodSelectorOptions { checkoutId: string | null; onSelect: (methodId: string) => void; onRefresh: () => Promise; } interface UseShippingMethodSelectorResult { selectShippingMethod: (methodId: string) => Promise; selectShippingMethodWithApi: (methodId: string) => Promise; } /** * Hook to manage shipping method selection * Encapsulates both UI state update and API communication * Used for both manual selection (user click) and auto-selection (default method) */ export function useShippingMethodSelector( options: UseShippingMethodSelectorOptions ): UseShippingMethodSelectorResult { const { checkoutId, onSelect, onRefresh } = options; /** * Updates UI state only (for initial/pre-selection) */ const selectShippingMethod = useCallback( async (methodId: string) => { onSelect(methodId); }, [onSelect] ); /** * Updates UI state AND calls Saleor API * Use this when user manually selects OR when auto-selecting the default */ const selectShippingMethodWithApi = useCallback( async (methodId: string) => { if (!checkoutId) { console.warn("[selectShippingMethodWithApi] No checkoutId provided"); return; } // Update UI immediately for responsiveness onSelect(methodId); // Call API through CheckoutService const checkoutService = createCheckoutService(checkoutId); const result = await checkoutService.updateShippingMethod(methodId); if (result.success) { // Refresh checkout to get updated totals including shipping await onRefresh(); } else { console.error( "[selectShippingMethodWithApi] Failed to update shipping method:", result.error ); // Could add error handling/rollback here } }, [checkoutId, onSelect, onRefresh] ); return { selectShippingMethod, selectShippingMethodWithApi, }; }