import { useContext, useMemo, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { StoreContext } from '../../context/StoreContext'; import '../../styles/components/StoreTabs.css'; const DEFAULT_LOCATION_NAME = "Default Location"; function getStoreKey(store) { return String(store?.household_store_id ?? store?.store_id ?? store?.id ?? ""); } function getStoreName(store) { return store?.name || store?.display_name || "Store"; } function getLocationName(store) { if (!store) return "Location"; const locationName = store.location_name || ""; if (!locationName || locationName === DEFAULT_LOCATION_NAME) { return "Default"; } return locationName; } function chooseStoreLocation(locations) { if (!locations || locations.length === 0) return null; return ( locations.find((store) => store.location_name === "Default Location" || store.display_name === store.name) || locations.find((store) => store.is_default) || locations[0] ); } function buildStoreOptions(stores) { const grouped = new Map(); for (const store of stores) { const key = getStoreKey(store); if (!grouped.has(key)) { grouped.set(key, { key, name: getStoreName(store), locations: [], }); } grouped.get(key).locations.push(store); } return Array.from(grouped.values()).map((group) => ({ ...group, store: chooseStoreLocation(group.locations), })); } export default function StoreTabs() { const { stores, activeStore, setActiveStore, loading } = useContext(StoreContext); const navigate = useNavigate(); const [activePicker, setActivePicker] = useState(null); const storeOptions = useMemo(() => buildStoreOptions(stores || []), [stores]); const activeStoreKey = getStoreKey(activeStore); const selectedStoreOption = storeOptions.find((option) => option.key === activeStoreKey) || storeOptions[0]; const selectedLocations = selectedStoreOption?.locations || []; const selectedLocation = selectedLocations.find((location) => String(location.id) === String(activeStore?.id)) || selectedStoreOption?.store; const canPickStore = storeOptions.length > 1 && !loading; const canPickLocation = selectedLocations.length > 1 && !loading; if (!stores || stores.length === 0 || storeOptions.length === 0) { return (