@rebuy/rebuy-hydrogen 3.0.0-beta.18 → 3.0.0-beta.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/providers/RebuyHydrogenContextProvider.tsx", "../src/context/RebuyConfigContext.tsx", "../src/smart-cart/utils/debugLog.ts", "../src/utils/getRebuyConfig.ts", "../src/context/RebuyContext.tsx", "../src/smart-cart/context/SmartCartContext.tsx", "../src/smart-cart/store/tieredProgressBarStore.ts", "../src/smart-cart/components/TieredProgressBar/progressBarUtils.tsx", "../src/smart-cart/components/TieredProgressBar/Icons.tsx", "../src/smart-cart/constants.ts", "../src/smart-cart/utils/moneyUtils.ts", "../src/smart-cart/utils/cartItemUtils.ts", "../src/smart-cart/utils/safeJsonParse.ts", "../src/smart-cart/utils/mapHydrogenCartToStorefrontCartData.ts", "../src/utils/createContextParameters.ts", "../src/utils/getEncodedAttributes.ts", "../src/providers/RebuyHydrogenReactContextProvider.tsx", "../src/queries/cart.queries.ts", "../src/smart-cart/components/SmartCartContainer/SmartCartContainer.tsx", "../src/smart-cart/components/_Layouts/AnchorSlot.tsx", "../src/smart-cart/components/AnnouncementBar/AnnouncementBar.tsx", "../src/smart-cart/components/ScreenReaderText/ScreenReaderText.tsx", "../src/smart-cart/components/AnnouncementBar/AnnouncementBar.module.css", "../src/smart-cart/components/CartItem/CartItem.tsx", "../src/components/RebuyLink/RebuyLink.tsx", "../src/smart-cart/hooks/useCartItemFeatures.ts", "../src/smart-cart/utils/imageUtils.ts", "../src/smart-cart/components/CartItem/CartItem.module.css", "../src/smart-cart/components/EmptyCart/EmptyCart.module.css", "../src/smart-cart/components/EmptyCart/EmptyCart.tsx", "../src/smart-cart/components/CartItemList/CartItemList.module.css", "../src/smart-cart/components/CartItemList/CartItemList.tsx", "../src/smart-cart/components/CartNoteInput/CartNoteInput.tsx", "../src/smart-cart/components/CartNoteInput/CartNoteInput.module.css", "../src/smart-cart/components/CartSubtotal/CartSubtotal.tsx", "../src/smart-cart/components/CartSubtotal/CartSubtotal.module.css", "../src/smart-cart/components/CartTitleBar/CartTitleBar.tsx", "../src/smart-cart/components/CartTitleBar/CartTitleBar.module.css", "../src/smart-cart/components/CheckoutArea/CheckoutArea.tsx", "../src/smart-cart/components/CheckoutArea/CheckoutArea.module.css", "../src/widgets/RebuyWidget/RebuyWidget.tsx", "../src/assets/Close.tsx", "../src/hooks/useBreakpoint.ts", "../src/hooks/usePopupTrigger.tsx", "../src/types/widgets.ts", "../src/utils/filterContextUtils.ts", "../src/components/ProductCard/defaultSettings.ts", "../src/components/ProductCard/ProductCard.tsx", "../src/components/AddToCartBtn/HydrogenAddToCartBtn.tsx", "../src/components/AddToCartBtn/AddToCartBtn.module.css", "../src/components/AddToCartBtn/HydrogenReactAddToCartBtn.tsx", "../src/components/AddToCartBtn/AddToCartBtn.tsx", "../src/components/ProductPrice/ProductPrice.tsx", "../src/components/ProductPrice/ProductPrice.module.css", "../src/components/QuantityInput/QuantityInput.tsx", "../src/components/QuantityInput/QuantityInput.module.css", "../src/components/VariantSelect/VariantSelect.tsx", "../src/components/VariantSelect/VariantSelect.module.css", "../src/components/Title/Title.tsx", "../src/components/Title/Title.module.css", "../src/components/ProductCard/ProductCard.module.css", "../src/components/ProductCarousel/ProductCarousel.tsx", "../src/components/ProductCarousel/ProductCarousel.module.css", "../src/components/Timer/Timer.tsx", "../src/components/Timer/Timer.module.css", "../src/hooks/titleLevel.tsx", "../src/widgets/RebuyWidget/RebuyWidget.module.css", "../src/widgets/RebuyWidget/WidgetContent.tsx", "../src/smart-cart/components/CrossSell/CrossSell.tsx", "../src/smart-cart/components/CustomCode/CustomCodeBlock.tsx", "../src/utils/nonceManager.ts", "../src/smart-cart/utils/executeScriptsInContainer.ts", "../src/smart-cart/components/DiscountCodeInput/DiscountCodeInput.tsx", "../src/smart-cart/hooks/useDiscountManager.ts", "../src/smart-cart/components/DiscountCodeInput/DiscountCodeInput.module.css", "../src/smart-cart/components/LoginButton/LoginButton.tsx", "../src/smart-cart/components/LoginButton/LoginButton.module.css", "../src/smart-cart/components/SmartCartApp/SmartCartApp.tsx", "../src/smart-cart/hooks/useSmartCartApps.ts", "../src/smart-cart/types/smart-cart-app.ts", "../src/smart-cart/components/TieredProgressBar/TieredProgressBar.tsx", "../src/smart-cart/components/TieredProgressBar/TPBGiftItem.tsx", "../src/smart-cart/components/TieredProgressBar/TieredProgressBar.module.css", "../src/smart-cart/utils/debugStyles.ts", "../src/smart-cart/components/componentRegistry.tsx", "../src/smart-cart/components/_Layouts/DoubleColumnLayout.tsx", "../src/smart-cart/hooks/useIsScrolled.ts", "../src/smart-cart/components/_Layouts/LayoutStyles.module.css", "../src/smart-cart/components/_Layouts/SingleColumnLayout.tsx", "../src/smart-cart/components/SmartCartContainer/SmartCartContainer.module.css", "../src/smart-cart/RebuySmartCart.tsx", "../src/widgetContainer/RebuyWidgetContainer.tsx", "../src/context/RebuyWidgetContext.tsx", "../src/widgets/RebuyCompleteTheLook/RebuyCompleteTheLook.module.css", "../src/widgets/RebuyCompleteTheLook/RebuyCompleteTheLook.tsx", "../src/widgets/RebuyDynamicBundleProducts/RebuyDynamicBundleProducts.tsx", "../src/utils/convertToRebuyProduct.tsx", "../src/widgets/RebuyDynamicBundleProducts/BundleImages.tsx", "../src/widgets/RebuyDynamicBundleProducts/RebuyDynamicBundleProducts.module.css", "../src/widgets/RebuyDynamicBundleProducts/BundlePrice.tsx", "../src/widgets/RebuyDynamicBundleProducts/BundleSelection.tsx", "../src/widgets/RebuyDynamicBundleProducts/Select.tsx", "../src/widgets/RebuyProductAddOns/RebuyProductAddOns.tsx", "../src/widgets/RebuyProductAddOns/RebuyProductAddOnCard.tsx", "../src/widgets/RebuyProductAddOns/RebuyProductAddOns.module.css", "../src/widgets/RebuyProductRecommendations/RebuyProductRecommendations.module.css", "../src/widgets/RebuyProductRecommendations/RebuyProductRecommendations.tsx", "../src/widgets/RebuyProductViewed/RebuyProductViewed.tsx", "../src/zustandStores/productViewed.ts", "../src/widgets/RebuyRecentlyViewedProducts/RebuyRecentlyViewedProducts.tsx", "../src/widgets/RebuyRecentlyViewedProducts/RebuyRecentlyViewedProducts.module.css", "../src/constants/api.ts", "../src/utils/theme.ts"],
4
- "sourcesContent": ["import * as Utilities from '@rebuy/rebuy/utilities';\nimport type { Cart as HydrogenStorefrontApiCart } from '@shopify/hydrogen/storefront-api-types';\nimport { useMemo, useRef } from 'react';\nimport { Await, useLocation } from 'react-router';\nimport { RebuyConfigProvider, useRebuyConfig } from '~/context/RebuyConfigContext';\nimport { RebuyContext, type RebuyContextType } from '~/context/RebuyContext';\nimport type { RebuyHydrogenContextProps, RebuyHydrogenContextProviderProps } from '~/providers/types';\nimport { SmartCartProvider as RebuySmartCartProvider } from '~/smart-cart/context/SmartCartContext';\nimport { createContextParameters } from '~/utils/createContextParameters';\n\nconst RebuyHydrogenContext = ({\n children,\n enableSmartCart,\n publicStorefrontToken,\n shop,\n sourceHydrogenCart,\n}: RebuyHydrogenContextProps) => {\n const {\n apiKey,\n fetchError: configFetchError,\n loadingStatus: configLoadingStatus,\n rebuyConfig,\n shopDomain: configShopDomain,\n smartCartConfig,\n } = useRebuyConfig();\n\n const warningLogged = useRef(false);\n const location = useLocation();\n const queryObject = Utilities.queryStringToObject(location.search);\n const windowUrl = `${shop}${location.pathname}${location.search}`;\n\n // --- Context Parameters Memoization ---\n const contextParameters = useMemo(\n () =>\n createContextParameters({\n cacheKey: rebuyConfig?.shop?.cache_key,\n isHydrogenReact: false,\n queryObject,\n sourceHydrogenCart: sourceHydrogenCart as HydrogenStorefrontApiCart | null,\n windowUrl,\n }),\n [rebuyConfig?.shop?.cache_key, windowUrl, queryObject, sourceHydrogenCart]\n );\n\n const defaultContextValue = useMemo(() => null as unknown as RebuyContextType, []);\n const contextValue = useMemo(\n () => (configLoadingStatus === 'success' && rebuyConfig ? { contextParameters } : defaultContextValue),\n [configLoadingStatus, rebuyConfig, contextParameters, defaultContextValue]\n );\n\n // --- Smart Cart Prerequisites Calculation ---\n const cacheKey = rebuyConfig?.shop?.cache_key || '';\n const shopifyDomainForSmartCart = configShopDomain || rebuyConfig?.shop?.domain || '';\n const storefrontAccessToken = publicStorefrontToken || rebuyConfig?.shop?.storefront_access_token || '';\n\n const hasAllSmartCartPrerequisites =\n enableSmartCart &&\n configLoadingStatus === 'success' &&\n !!rebuyConfig &&\n !!(smartCartConfig && apiKey && shopifyDomainForSmartCart && storefrontAccessToken);\n\n return (\n <RebuyContext.Provider value={contextValue}>\n {configLoadingStatus === 'success' && rebuyConfig ? (\n enableSmartCart && hasAllSmartCartPrerequisites ? (\n <RebuySmartCartProvider\n apiKey={apiKey!}\n cacheKey={cacheKey}\n config={smartCartConfig!}\n hydrogenCart={sourceHydrogenCart as HydrogenStorefrontApiCart}\n shopifyDomain={shopifyDomainForSmartCart}\n storefrontAccessToken={storefrontAccessToken}\n >\n {children}\n </RebuySmartCartProvider>\n ) : (\n <>\n {enableSmartCart &&\n !hasAllSmartCartPrerequisites &&\n !warningLogged.current &&\n (() => {\n console.warn(\n `[RebuyHydrogenContextProvider] Rebuy config loaded, but Smart Cart prerequisites NOT met for ${configShopDomain}. Smart Cart UI won't render. Check Rebuy Admin/env vars. Missing:`,\n {\n apiKey: !!apiKey,\n shopifyDomain: !!shopifyDomainForSmartCart,\n smartCartConfig: !!smartCartConfig,\n storefrontAccessToken: !!storefrontAccessToken,\n }\n );\n warningLogged.current = true;\n\n return null;\n })()}\n {children}\n </>\n )\n ) : configLoadingStatus === 'error' ? (\n <>\n {(() => {\n console.error(\n `[RebuyHydrogenContextProvider] Failed to load Rebuy configuration for ${configShopDomain}. Rebuy Smart Cart features unavailable. Error:`,\n configFetchError instanceof Error ? configFetchError.message : configFetchError\n );\n\n return null;\n })()}\n {children}\n </>\n ) : null}\n </RebuyContext.Provider>\n );\n};\n\n// --- Outer Provider (RebuyHydrogenContextProvider) ---\nexport const RebuyHydrogenContextProvider = ({\n cart,\n children,\n enableSmartCart = false,\n overrideApiKey,\n publicStoreDomain,\n publicStorefrontToken,\n shop,\n}: RebuyHydrogenContextProviderProps) => {\n if (!publicStoreDomain || !shop) {\n console.warn('[Rebuy Provider Wrapper] Waiting for \"publicStoreDomain\" and \"shop\" props.');\n\n return <>{children}</>;\n }\n\n return (\n <Await resolve={cart}>\n {(resolvedCart) => {\n const hydrogenCartFromRemix = resolvedCart as HydrogenStorefrontApiCart | null;\n\n return (\n <RebuyConfigProvider initialShopDomain={publicStoreDomain} overrideApiKey={overrideApiKey}>\n <RebuyHydrogenContext\n enableSmartCart={enableSmartCart}\n publicStorefrontToken={publicStorefrontToken}\n shop={shop}\n sourceHydrogenCart={hydrogenCartFromRemix}\n >\n {children}\n </RebuyHydrogenContext>\n </RebuyConfigProvider>\n );\n }}\n </Await>\n );\n};\n", "import { createContext, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';\nimport { DebugKey } from '~/constants/debug';\nimport type { SmartCartConfig } from '~/smart-cart/types/smart-cart';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport type { RebuyConfig } from '~/types/rebuyCustom';\nimport { getRebuyConfig } from '~/utils/getRebuyConfig';\n\nexport type RebuyConfigLoadingStatus = 'idle' | 'loading' | 'success' | 'error';\n\nexport type RebuyConfigContextType = {\n apiKey: string | null;\n fetchError: Error | string | null;\n fetchRebuyConfig: (domain: string) => Promise<void>;\n loadingStatus: RebuyConfigLoadingStatus;\n rebuyConfig: RebuyConfig | null;\n shopDomain: string | null;\n smartCartConfig: SmartCartConfig | null;\n};\n\nconst RebuyConfigContext = createContext<RebuyConfigContextType | undefined>(undefined);\n\nexport type RebuyConfigProviderProps = {\n children: ReactNode;\n /** The Shopify store domain (e.g., example-brand.myshopify.com) used to fetch the config. */\n initialShopDomain?: string;\n /** Optional API key to override environment variable or config-derived one. */\n overrideApiKey?: string;\n};\n\nexport const RebuyConfigProvider = ({ children, initialShopDomain, overrideApiKey }: RebuyConfigProviderProps) => {\n const [rebuyConfig, setRebuyConfig] = useState<RebuyConfig | null>(null);\n const [smartCartConfig, setSmartCartConfig] = useState<SmartCartConfig | null>(null);\n const [apiKey, setApiKey] = useState<string | null>(overrideApiKey || null);\n const [loadingStatus, setLoadingStatus] = useState<RebuyConfigLoadingStatus>('idle');\n const [fetchError, setFetchError] = useState<Error | string | null>(null);\n const [currentShopDomain, setCurrentShopDomain] = useState<string | null>(initialShopDomain || null);\n const isMounted = useRef(true);\n\n const fetchRebuyConfig = async (domainToFetch: string) => {\n if (!domainToFetch) {\n console.warn('[RebuyConfigProvider] No shop domain provided to fetchRebuyConfig.');\n setLoadingStatus('error');\n setFetchError('Shop domain is required to fetch Rebuy config.');\n\n return;\n }\n\n rebuyDebugLog.log(\n DebugKey.REBUY_CONFIG_CONTEXT,\n '[RebuyConfigProvider] Attempting to fetch Rebuy config for domain:',\n domainToFetch\n );\n setCurrentShopDomain(domainToFetch);\n setLoadingStatus('loading');\n setFetchError(null);\n\n try {\n const config = await getRebuyConfig(domainToFetch);\n rebuyDebugLog.log(DebugKey.REBUY_CONFIG_CONTEXT, '[RebuyConfigProvider] Fetched Rebuy config:', config);\n\n if (isMounted.current) {\n setRebuyConfig(config);\n // Prioritize overrideApiKey, then env var, then config's api_key\n setApiKey(overrideApiKey || config?.shop?.api_key || null);\n setSmartCartConfig(config?.smart_cart);\n setLoadingStatus('success');\n }\n } catch (error: unknown) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n console.error('[RebuyConfigProvider] Error fetching Rebuy config:', errorMessage, error);\n\n if (isMounted.current) {\n setFetchError(error instanceof Error ? error : errorMessage);\n setLoadingStatus('error');\n setRebuyConfig(null); // Clear previous config on error\n // Do not clear apiKey if it was from override or env, it might still be valid for some uses\n // If apiKey was solely from a previous config, it might be stale.\n // Consider if apiKey should be reset here if not from override/env.\n // For now, let's keep it simple: only update from new config if successful.\n }\n }\n };\n\n useEffect(() => {\n isMounted.current = true;\n\n if (initialShopDomain && loadingStatus === 'idle') {\n // Fetch on mount if domain provided and not already fetching/fetched\n fetchRebuyConfig(initialShopDomain);\n }\n\n return () => {\n isMounted.current = false;\n };\n // Rerun if initialShopDomain changes and we haven't started fetching yet.\n }, [initialShopDomain]);\n\n const contextValue = useMemo(\n () => ({\n apiKey,\n fetchError,\n fetchRebuyConfig,\n loadingStatus,\n rebuyConfig,\n shopDomain: currentShopDomain,\n smartCartConfig,\n }),\n [rebuyConfig, apiKey, loadingStatus, fetchError, currentShopDomain, smartCartConfig]\n );\n\n return <RebuyConfigContext.Provider value={contextValue}>{children}</RebuyConfigContext.Provider>;\n};\n\nexport const useRebuyConfig = (): RebuyConfigContextType => {\n const context = useContext(RebuyConfigContext);\n\n if (context === undefined) {\n throw new Error('useRebuyConfig must be used within a RebuyConfigProvider');\n }\n\n return context;\n};\n", "// ~/smart-cart/utils/debugLog.ts\n\n// TODO: Move this to npm-rebuy as a shared utility\n\n// Ensure window.REBUY_DEBUG_MODE can be augmented\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Window {\n REBUY_DEBUG_MODE?: boolean | string | string[];\n }\n}\n\nconst REBUY_DEBUG_GLOBAL_PREFIX = '[Rebuy Debug]';\nconst REBUY_DEBUG_KEYS_SEPARATOR = ',';\nconst LOCAL_STORAGE_DEBUG_KEY = 'REBUY_DEBUG_MODE';\n\ntype DebugSettings = {\n enabledKeys: Set<string>;\n globalEnable: boolean;\n};\n\nconst getDebugSettings = (): DebugSettings => {\n let settingsValue: boolean | string | string[] | null | undefined = undefined;\n\n // Prioritize window flag if set, allows runtime override\n if (typeof window !== 'undefined' && typeof window.REBUY_DEBUG_MODE !== 'undefined') {\n settingsValue = window.REBUY_DEBUG_MODE;\n } else {\n // localStorage, only if window flag not present\n try {\n if (typeof window !== 'undefined' && typeof localStorage !== 'undefined') {\n settingsValue = localStorage.getItem(LOCAL_STORAGE_DEBUG_KEY);\n }\n } catch (e) {\n // localStorage might be unavailable (e.g., SSR, security restrictions).\n // Silently fail, settingsValue remains undefined, will fall to default disabled state.\n // console.warn(`${REBUY_DEBUG_GLOBAL_PREFIX} Could not access localStorage for debug settings.`, e);\n }\n }\n\n if (settingsValue === true || settingsValue === 'true') {\n return { enabledKeys: new Set(), globalEnable: true };\n }\n\n if (settingsValue === false || settingsValue === 'false') {\n return { enabledKeys: new Set(), globalEnable: false };\n }\n\n if (typeof settingsValue === 'string' && settingsValue.length > 0) {\n const keys = settingsValue\n .split(REBUY_DEBUG_KEYS_SEPARATOR)\n .map((k) => k.trim())\n .filter(Boolean);\n\n return { enabledKeys: new Set(keys), globalEnable: false };\n }\n\n if (Array.isArray(settingsValue)) {\n const keys = settingsValue.map((k) => String(k).trim()).filter(Boolean);\n\n return { enabledKeys: new Set(keys), globalEnable: false };\n }\n\n return { enabledKeys: new Set(), globalEnable: false }; // Default: disabled\n};\n\nconst _isFeatureDebugActive = (key: string): boolean => {\n const { enabledKeys, globalEnable } = getDebugSettings();\n\n if (globalEnable) return true;\n\n return enabledKeys.has(key);\n};\n\nconst _isAnyDebugActive = (): boolean => {\n const { enabledKeys, globalEnable } = getDebugSettings();\n\n return globalEnable || enabledKeys.size > 0;\n};\n\n// Helper to generate consistent log prefixes for labels\nconst makeLabelWithPrefix = (baseKeyPrefix: string, subContext?: unknown): string => {\n if (typeof subContext === 'string' && subContext.trim() !== '') {\n return `${baseKeyPrefix}: ${subContext.trim()}`;\n }\n\n return baseKeyPrefix; // Only base key prefix if subContext is not a useful string\n};\n\n// --- Logger method factories ---\n\n// For: log, warn, error, info, debug, dir, dirxml, trace\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst createKeyedLogger = (consoleMethod: (...args: any[]) => void) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (key: string, ...args: any[]): void => {\n if (_isFeatureDebugActive(key)) {\n const baseKeyPrefix = `${REBUY_DEBUG_GLOBAL_PREFIX} (${key})`;\n consoleMethod(baseKeyPrefix, ...args);\n }\n };\n};\n\n// For: table\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst createKeyedTableLogger = () => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (key: string, data: any, properties?: readonly string[]): void => {\n if (_isFeatureDebugActive(key)) {\n const baseKeyPrefix = `${REBUY_DEBUG_GLOBAL_PREFIX} (${key})`;\n console.groupCollapsed(makeLabelWithPrefix(baseKeyPrefix, 'Table'));\n console.table(data, properties);\n console.groupEnd();\n }\n };\n};\n\n// For: group, groupCollapsed\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst createKeyedGroupLogger = (consoleMethod: (label?: any, ...data: any[]) => void) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (key: string, groupLabelArg?: any, ...data: any[]): void => {\n if (_isFeatureDebugActive(key)) {\n const baseKeyPrefix = `${REBUY_DEBUG_GLOBAL_PREFIX} (${key})`;\n\n if (typeof groupLabelArg === 'string' || typeof groupLabelArg === 'undefined' || groupLabelArg === null) {\n const finalGroupLabel = makeLabelWithPrefix(baseKeyPrefix, groupLabelArg as string | undefined);\n consoleMethod(finalGroupLabel, ...data);\n } else {\n // groupLabelArg is not a string (e.g. an object), pass it as a subsequent argument\n consoleMethod(baseKeyPrefix, groupLabelArg, ...data);\n }\n }\n };\n};\n\n// For: groupEnd, clear\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst createParameterlessLogger = (consoleMethod: () => void) => {\n return (): void => {\n if (_isAnyDebugActive()) {\n consoleMethod();\n }\n };\n};\n\n// For: count, countReset, time, timeEnd\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst createKeyedLabelLogger = (consoleMethod: (label?: string) => void, baseMethodName: string) => {\n return (key: string, label?: string): void => {\n if (_isFeatureDebugActive(key)) {\n const baseKeyPrefix = `${REBUY_DEBUG_GLOBAL_PREFIX} (${key})`;\n const fullLabel = makeLabelWithPrefix(baseKeyPrefix, label || baseMethodName);\n consoleMethod(fullLabel);\n }\n };\n};\n\n// For: timeLog\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst createKeyedTimeLogLogger = (consoleMethod: (label: string, ...data: any[]) => void) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (key: string, timerName: string, ...data: any[]): void => {\n if (_isFeatureDebugActive(key)) {\n const baseKeyPrefix = `${REBUY_DEBUG_GLOBAL_PREFIX} (${key})`;\n const fullTimerName = makeLabelWithPrefix(baseKeyPrefix, timerName);\n consoleMethod(fullTimerName, ...data);\n }\n };\n};\n\n// For: assert\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst createKeyedAssertLogger = (consoleMethod: (assertion: boolean, ...data: any[]) => void) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (key: string, assertion: boolean, ...messageArgs: any[]): void => {\n if (_isFeatureDebugActive(key)) {\n const baseKeyPrefix = `${REBUY_DEBUG_GLOBAL_PREFIX} (${key})`;\n const assertionContextMessage = makeLabelWithPrefix(baseKeyPrefix, 'Assertion');\n consoleMethod(assertion, assertionContextMessage, ...messageArgs);\n }\n };\n};\n\n/**\n * The main Rebuy debug logger object.\n * Provides familiar console methods, but conditional on Rebuy debug settings and feature keys.\n *\n * How to enable debugging:\n * 1. Global: Set `window.REBUY_DEBUG_MODE = true` or in localStorage `REBUY_DEBUG_MODE` to `'true'`.\n * This enables all logs from `rebuyDebugLog` regardless of key.\n * 2. Key-specific: Set `window.REBUY_DEBUG_MODE = ['cart', 'api']` (array of strings) or\n * in localStorage `REBUY_DEBUG_MODE` to `'cart,api'` (comma-separated string).\n * This enables logs only for the specified keys (e.g., `rebuyDebugLog.log('cart', ...)`).\n *\n * To disable, set the corresponding value to `false` or remove the localStorage item.\n */\nexport const rebuyDebugLog = {\n assert: createKeyedAssertLogger(console.assert),\n clear: createParameterlessLogger(console.clear),\n count: createKeyedLabelLogger(console.count, 'count'),\n countReset: createKeyedLabelLogger(console.countReset, 'countReset'),\n debug: createKeyedLogger(console.debug),\n\n dir: createKeyedLogger(console.dir),\n dirxml: createKeyedLogger(console.dirxml),\n error: createKeyedLogger(console.error),\n\n /**\n * Retrieves the current parsed debug settings.\n *\n * @returns {DebugSettings} An object containing `globalEnable` (boolean) and `enabledKeys` (Set<string>).\n */\n\n getSettings: (): DebugSettings => getDebugSettings(),\n\n group: createKeyedGroupLogger(console.group),\n groupCollapsed: createKeyedGroupLogger(console.groupCollapsed),\n groupEnd: createParameterlessLogger(console.groupEnd),\n\n info: createKeyedLogger(console.info),\n\n /**\n * Checks if any Rebuy debugging (global or any key) is active.\n * Useful for controlling parameter-less debug actions or general checks.\n *\n * @returns {boolean} True if any form of Rebuy debugging is active.\n */\n\n isAnyActive: (): boolean => _isAnyDebugActive(),\n\n /**\n * Checks if debugging is active for a specific feature key.\n * Considers both global debug mode and key-specific settings.\n *\n * @param {string} key - The debug key for the feature.\n * @returns {boolean} True if debugging is active for this key.\n */\n isKeyActive: (key: string): boolean => _isFeatureDebugActive(key),\n\n log: createKeyedLogger(console.log),\n table: createKeyedTableLogger(),\n time: createKeyedLabelLogger(console.time, 'time'),\n\n timeEnd: createKeyedLabelLogger(console.timeEnd, 'timeEnd'),\n timeLog: createKeyedTimeLogLogger(console.timeLog),\n trace: createKeyedLogger(console.trace),\n warn: createKeyedLogger(console.warn),\n};\n\n/**\n * Returns true if Rebuy debug mode is active.\n *\n * @deprecated Prefer using `rebuyDebugLog.isKeyActive(key)`, `rebuyDebugLog.isAnyActive()`, or `rebuyDebugLog.getSettings().globalEnable`.\n * Checks if Rebuy debug mode is active.\n * - If a `key` is provided, checks if that key is enabled OR if global debug is on.\n * - If no `key` is provided, checks ONLY if global debug mode is on (to maintain some backward compatibility with original intent).\n * @param {string} [key] - Optional. The debug key for a specific feature.\n * @returns {boolean} True if debug mode is enabled for the context.\n */\nexport const isRebuyDebugMode = (key?: string): boolean => {\n const { enabledKeys, globalEnable } = getDebugSettings();\n\n if (globalEnable) {\n return true;\n }\n\n // If a key is provided, check if it's in the enabled set (globalEnable is false here)\n if (key && enabledKeys.has(key)) {\n return true;\n }\n\n // If no key is provided and global debug is not on, return false.\n // This makes `isRebuyDebugMode()` without arguments specific to the global flag.\n return false;\n};\n", "import { RebuyClient } from '@rebuy/rebuy';\nimport type { RebuyConfig, RebuyResponse } from '~/types/rebuyCustom';\n\nexport const getRebuyConfig = async (storeDomain: string): Promise<RebuyConfig> => {\n try {\n const request = {\n parameters: { shop: storeDomain },\n url: `/api/v1/user/config`,\n };\n\n const { data: rebuy, ...response } = (await new RebuyClient('', undefined, storeDomain).getShieldedAsset(\n request.url,\n request.parameters\n )) as RebuyResponse;\n\n if (!rebuy?.shop) {\n throw new Error('Rebuy configuration is not properly set up - missing shop', { cause: response });\n }\n\n return rebuy;\n } catch (error: unknown) {\n const err = error as Error;\n console.warn('Error fetching Rebuy shop config');\n console.error(err, err.cause);\n throw err;\n }\n};\n", "import { createContext } from 'react';\n\nimport { type ContextParameters } from '~/types/rebuyCustom';\n\nexport type RebuyContextType = {\n contextParameters: ContextParameters;\n};\n\nexport const RebuyContext = createContext<RebuyContextType | null>(null);\n", "// ~/smart-cart/context/SmartCartContext.tsx\nimport type {\n // Alias Storefront types to Hydrogen types from H-React for clarity where actions are concerned\n AttributeInput as HRAttributeInput,\n CartLineInput as HRCartLineInput,\n CartLineUpdateInput as HRCartLineUpdateInput,\n} from '@shopify/hydrogen-react/storefront-api-types';\n// eslint-disable-next-line import/order\nimport type { Cart as HydrogenStorefrontApiCart } from '@shopify/hydrogen/storefront-api-types';\nimport { isEqual } from 'lodash-es';\nimport { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';\nimport { useShallow } from 'zustand/react/shallow';\nimport { DebugKey } from '~/constants/debug';\n\nimport { RebuyContext } from '~/context/RebuyContext';\nimport { useTieredProgressBarStore, type TieredProgressBarStore } from '~/smart-cart/store/tieredProgressBarStore';\nimport type {\n StorefrontAttribute,\n StorefrontCartData,\n StorefrontCartItemInput,\n StorefrontCartLineUpdateInput,\n} from '~/smart-cart/types/rebuy-storefront-cart';\nimport type { SmartCartConfig } from '~/smart-cart/types/smart-cart';\nimport type { SmartCartComponentConfig, TieredProgressBarSettings } from '~/smart-cart/types/smart-cart-component';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport { mapHydrogenCartToStorefrontCartData } from '~/smart-cart/utils/mapHydrogenCartToStorefrontCartData';\nimport type { HydrogenReactCartActions } from '~/types/rebuyCustom';\n\n/*\n Considerations for Vanilla Hydrogen/Remix Path:\n\n - Fetcher Necessity: Since cart actions in Remix typically involve form submissions handled by action functions, components initiating these actions (CartItem, DiscountCodeInput, etc.) will likely need their own useFetcher() instance.\n - Context Actions Role: The context actions (addItem, updateItem, etc.) in the !isHydrogenReact path cannot directly perform the fetch. They serve mainly as placeholders or could potentially throw an error indicating a fetcher is required.\n - Shared Fetcher (Complex): Managing a single, shared fetcher within the SmartCartProvider is complex because multiple components might trigger actions concurrently or need different submission data/methods. This approach is generally discouraged.\n - UI State (isLoading, error): The UI should still react to isLoading and error from the context. In a Remix setup, the SmartCartProvider would need to get the fetcher.state and fetcher.data (for errors) from somewhere. This could involve:\n - Passing the fetcher down via context (possible but couples context tightly to Remix).\n - Having the RebuyProvider (consuming the root loader data and potentially a root fetcher) provide loading/error status to SmartCartProvider.\n - Recommendation: Prioritize the component-level useFetcher pattern for Remix actions. The SmartCartProvider would focus on providing cartData (from loader), config, and UI state (isVisible), while global isLoading/error might need to be sourced from a higher-level provider or context aware of the root layout's fetcher state.\n*/\n\n// --- Define the Combined Context Value Type ---\n// Note: Action return types are unions for potential Remix path flexibility,\n// but H-React implementations behave as void.\nexport type SmartCartContextValue = {\n addItem: (\n variantId: string,\n attributes?: StorefrontAttribute[],\n quantity?: number\n ) => void | Promise<StorefrontCartData | null>;\n addItems: (items: StorefrontCartItemInput[]) => void | Promise<StorefrontCartData | null>;\n apiKey: string;\n applyDiscountCodes: (codes: string[]) => void | Promise<StorefrontCartData | null>;\n cacheKey: string;\n cartData: StorefrontCartData | null;\n checkout: () => void;\n config: SmartCartConfig;\n /* Global Error State */\n error: string | null;\n getCartSubtotal: () => string;\n getComponentConfigById: (id: string) => SmartCartComponentConfig | undefined;\n getComponentConfigByType: <T extends SmartCartComponentConfig['type']>(\n type: T\n ) => Extract<SmartCartComponentConfig, { type: T }> | undefined;\n getItemCount: () => number;\n getTpbStore: () => TieredProgressBarStore;\n hideCart: () => void;\n hydrogenReactCartActions?: HydrogenReactCartActions;\n /** Indicates if the cart is busy (loading, updating, etc.) via H-React ops or TPB sync actions. */\n isCartBusy: boolean;\n /** Indicates if the cart is ready to be used initially. */\n isCartReady: boolean;\n isHydrogenReact: boolean;\n /** Global loading state */\n isLoading: boolean;\n isProgressBarLineItemMode: boolean;\n isVisible: boolean;\n removeItem: (lineId: string) => void | Promise<StorefrontCartData | null>;\n removeItems: (lineIds: string[]) => void | Promise<StorefrontCartData | null>;\n shopifyDomain: string;\n showCart: () => void;\n storefrontAccessToken: string;\n toggleCart: () => void;\n updateCartAttributes: (attributes: StorefrontAttribute[]) => void | Promise<StorefrontCartData | null>;\n updateCartNote: (note: string | null) => void | Promise<StorefrontCartData | null>;\n updateItem: (\n lineId: string,\n updates: Partial<Omit<StorefrontCartLineUpdateInput, 'id'> & { sellingPlanId?: string | null }>\n ) => void | Promise<StorefrontCartData | null>;\n updateItems: (\n updates: (StorefrontCartLineUpdateInput & { sellingPlanId?: string | null })[]\n ) => void | Promise<StorefrontCartData | null>;\n};\n\nconst SmartCartContext = createContext<SmartCartContextValue | null>(null);\n\nexport type SmartCartProviderProps = {\n apiKey: string;\n cacheKey: string;\n children?: ReactNode;\n config: SmartCartConfig;\n hydrogenCart: HydrogenStorefrontApiCart;\n shopifyDomain: string;\n storefrontAccessToken: string;\n};\n\n// Helper to map StorefrontAttribute[] to HRAttributeInput[]\nconst mapStorefrontAttributesToHRAttributes = (attributes?: StorefrontAttribute[] | null): HRAttributeInput[] => {\n if (!attributes) return [];\n\n return attributes\n .filter((attr): attr is { key: string; value: string } => typeof attr.key === 'string' && attr.value !== null) // Ensure key/value are strings (value can be empty string)\n .map((attr) => ({\n key: attr.key,\n value: attr.value, // Value is now confirmed string\n }));\n};\n\nexport const SmartCartProvider: React.FC<SmartCartProviderProps> = ({\n apiKey,\n cacheKey,\n children,\n config,\n hydrogenCart,\n shopifyDomain,\n storefrontAccessToken,\n}) => {\n const rebuyContext = useContext(RebuyContext);\n\n const [isVisible, setIsVisible] = useState(false);\n const showCart = useCallback(() => setIsVisible(true), []);\n const hideCart = useCallback(() => setIsVisible(false), []);\n const toggleCart = useCallback(() => setIsVisible((prev) => !prev), []);\n\n // --- Consume RebuyContext ---\n const { contextParameters, isHydrogenReact } = useMemo(() => {\n if (!rebuyContext) {\n return { contextParameters: null, isHydrogenReact: false };\n }\n\n return {\n contextParameters: rebuyContext.contextParameters,\n isHydrogenReact: rebuyContext.contextParameters.isHydrogenReact ?? false,\n };\n }, [rebuyContext]);\n\n const hReactActions = contextParameters?.hydrogenReactCartActions;\n const hReactStatus = contextParameters?.hydrogenReactCartStatus;\n const hReactError = contextParameters?.hydrogenReactCartError;\n\n // --- Reactive State Derivation ---\n const prevCartData = useRef<StorefrontCartData | null>(null);\n const mappedStorefrontCartData = useMemo(() => {\n const cartSource = hydrogenCart ?? contextParameters?.hydrogenCart;\n\n if (!cartSource) {\n rebuyDebugLog.log(\n DebugKey.SC_CTX,\n 'No cart source (direct prop or context.hydrogenCart) available for mapping.'\n );\n\n return null;\n }\n\n const cartData = mapHydrogenCartToStorefrontCartData(cartSource, contextParameters);\n\n if (!isEqual(prevCartData.current, cartData)) {\n rebuyDebugLog.groupCollapsed(\n DebugKey.SC_CTX,\n '%cCart data updated in SmartCartContext',\n 'color: white; background: purple'\n );\n rebuyDebugLog.log(DebugKey.SC_CTX, {\n newCartData: cartData,\n oldCartData: prevCartData.current,\n source: hydrogenCart ? 'direct_prop' : 'rebuy_context.hydrogenCart',\n });\n rebuyDebugLog.groupEnd();\n }\n\n prevCartData.current = cartData;\n\n return cartData;\n }, [hydrogenCart, contextParameters]);\n const isLoading = useMemo(() => {\n if (isHydrogenReact && hReactStatus) {\n // Hydrogen React provides status for ongoing operations\n return ['fetching', 'creating', 'updating'].includes(hReactStatus);\n }\n\n // Fallback: If context isn't ready, consider it loading\n return !rebuyContext || !contextParameters;\n }, [isHydrogenReact, hReactStatus, rebuyContext, contextParameters]);\n\n const error = useMemo(() => {\n if (isHydrogenReact && hReactError) {\n // Handle different error shapes from Hydrogen React\n if (typeof hReactError === 'string') return hReactError;\n\n if (hReactError instanceof Error) return hReactError.message;\n // Attempt to stringify other potential error objects/values\n try {\n return JSON.stringify(hReactError);\n } catch {\n return 'An unknown Hydrogen React cart error occurred.';\n }\n }\n\n // No error if not H-React or no error present\n return null;\n }, [isHydrogenReact, hReactError]);\n\n const isCartReady = useMemo(() => !!mappedStorefrontCartData, [mappedStorefrontCartData]);\n\n // --- Tiered Progress Bar Setup ---\n const tpbStoreInstance = useTieredProgressBarStore();\n const {\n activeBarConfig,\n cartData: tpbInternalCartData,\n cartSyncStatus,\n init: tpbInit,\n isCartReady: isTpbInternalCartReady,\n isManuallyDisabled,\n productFetchStatus,\n setCartData: tpbSetCartData,\n syncCartGifts: tpbSyncCartGifts,\n userActionStatus,\n } = tpbStoreInstance;\n\n // Subscribe to specific TPB states for isProcessingTPBGifts\n const { tpbCartSyncStatus, tpbUserActionStatus } = useTieredProgressBarStore(\n useShallow((state) => {\n // Log whenever this selector runs and what it sees\n rebuyDebugLog.log(DebugKey.SC_CTX_TPB_SELECTOR, 'SmartCartContext TPB Selector:', {\n cartSyncStatus: state.cartSyncStatus,\n userActionStatus: state.userActionStatus,\n });\n\n return {\n tpbCartSyncStatus: state.cartSyncStatus,\n tpbUserActionStatus: state.userActionStatus,\n };\n })\n );\n rebuyDebugLog.log(\n DebugKey.SC_CTX_TPB_SELECTOR,\n `tpbCartSyncStatus: ${tpbCartSyncStatus}, tpbUserActionStatus: ${tpbUserActionStatus}`\n );\n\n const isProcessingTPBGifts = useMemo(() => {\n return (\n tpbCartSyncStatus === 'syncing' ||\n tpbCartSyncStatus === 'awaiting_cart_update' ||\n tpbUserActionStatus === 'pending'\n );\n }, [tpbCartSyncStatus, tpbUserActionStatus]);\n\n const isCartBusy = useMemo(() => {\n return isLoading || isProcessingTPBGifts;\n }, [isLoading, isProcessingTPBGifts]);\n\n rebuyDebugLog.log(DebugKey.SC_CTX, 'isCartBusy state:', isCartBusy);\n\n const progressBarSettings = useMemo((): TieredProgressBarSettings | null => {\n const tpbComponentConfig = config?.components?.find((comp) => comp.type === 'tiered_progress_bar');\n\n return tpbComponentConfig?.settings ?? null;\n }, [config]);\n\n // TPB Init Effect\n useEffect(() => {\n if (progressBarSettings && isCartReady && shopifyDomain && storefrontAccessToken) {\n tpbInit(progressBarSettings, shopifyDomain, storefrontAccessToken);\n }\n }, [progressBarSettings, isCartReady, shopifyDomain, storefrontAccessToken, tpbInit]);\n\n // TPB Cart Data Sync Effect\n useEffect(() => {\n const currentTpbState = useTieredProgressBarStore.getState();\n const newTpbIsCartReady = isCartReady;\n\n if (\n !isEqual(currentTpbState.cartData, mappedStorefrontCartData) ||\n currentTpbState.isCartReady !== newTpbIsCartReady\n ) {\n rebuyDebugLog.log(DebugKey.SC_CTX, 'Updating TPB store with cart data:', {\n cartData: mappedStorefrontCartData,\n isCartReady: newTpbIsCartReady,\n });\n tpbSetCartData(mappedStorefrontCartData, newTpbIsCartReady);\n }\n }, [mappedStorefrontCartData, isCartReady, tpbSetCartData]);\n\n const isProgressBarLineItemMode = useTieredProgressBarStore(\n (state) => state.activeBarConfig?.use_line_item_mode ?? false\n );\n\n // --- Cart Actions Implementation (Refactored for Reactivity) ---\n const logRemixWarning = (actionName: string) => {\n rebuyDebugLog.warn(\n DebugKey.SC_CTX,\n `${actionName} called in non-Hydrogen React context. Requires component-level fetcher implementation.`\n );\n\n // Return a resolved promise to satisfy the union type, though behavior is warning only.\n return Promise.resolve(null);\n };\n\n // --- ACTION: addItems ---\n const addItems = useCallback(\n (items: StorefrontCartItemInput[]) => {\n if (isHydrogenReact && hReactActions?.linesAdd) {\n const linesToAdd: HRCartLineInput[] = items.map((item) => ({\n // Map attributes within the item before passing to H-React\n attributes: mapStorefrontAttributesToHRAttributes(item.attributes),\n merchandiseId: item.merchandiseId,\n quantity: item.quantity,\n }));\n rebuyDebugLog.log(DebugKey.SC_CTX_H_REACT, 'Dispatching H-React linesAdd:', linesToAdd);\n hReactActions.linesAdd(linesToAdd); // Fire-and-forget\n // VOID return for H-React path\n } else if (!isHydrogenReact) {\n // Needs fetcher in consuming component\n return logRemixWarning('addItems');\n }\n },\n [isHydrogenReact, hReactActions]\n );\n\n // --- ACTION: addItem ---\n const addItem = useCallback(\n (variantId: string, attributes?: StorefrontAttribute[], quantity = 1) => {\n // Map input attributes immediately\n const mappedAttributes = mapStorefrontAttributesToHRAttributes(attributes);\n\n // Create the item object using the correctly typed attributes\n const item: StorefrontCartItemInput = {\n attributes: mappedAttributes, // Use mapped attributes\n merchandiseId: variantId,\n quantity,\n };\n\n // Call the refactored addItems\n // The return type handling (void | Promise) is managed within addItems\n return addItems([item]);\n },\n [addItems] // Dependency is the refactored addItems\n );\n\n // --- ACTION: updateItems ---\n const updateItems = useCallback(\n (updates: (StorefrontCartLineUpdateInput & { sellingPlanId?: string | null })[]) => {\n if (isHydrogenReact && hReactActions?.linesUpdate) {\n const linesToUpdate: HRCartLineUpdateInput[] = updates.map((update) => ({\n attributes: mapStorefrontAttributesToHRAttributes(update.attributes),\n id: update.id,\n merchandiseId: update.merchandiseId,\n quantity: update.quantity,\n sellingPlanId: update.sellingPlanId,\n }));\n rebuyDebugLog.log(DebugKey.SC_CTX_H_REACT, 'Dispatching H-React linesUpdate:', linesToUpdate);\n hReactActions.linesUpdate(linesToUpdate); // Fire-and-forget\n // VOID return for H-React path\n } else if (!isHydrogenReact) {\n return logRemixWarning('updateItems');\n }\n },\n [isHydrogenReact, hReactActions]\n );\n\n // --- ACTION: updateItem ---\n const updateItem = useCallback(\n (\n lineId: string,\n updates: Partial<Omit<StorefrontCartLineUpdateInput, 'id'> & { sellingPlanId?: string | null }>\n ) => {\n const updatePayload: StorefrontCartLineUpdateInput & { sellingPlanId?: string | null } = {\n id: lineId,\n ...updates,\n };\n\n // Call the refactored updateItems\n return updateItems([updatePayload]);\n },\n [updateItems]\n );\n\n // --- ACTION: removeItems ---\n const removeItems = useCallback(\n (lineIds: string[]) => {\n if (isHydrogenReact && hReactActions?.linesRemove) {\n rebuyDebugLog.log(DebugKey.SC_CTX_H_REACT, 'Dispatching H-React linesRemove:', lineIds);\n hReactActions.linesRemove(lineIds); // Fire-and-forget\n // VOID return for H-React path\n } else if (!isHydrogenReact) {\n return logRemixWarning('removeItems');\n }\n },\n [isHydrogenReact, hReactActions]\n );\n\n // --- ACTION: removeItem ---\n const removeItem = useCallback((lineId: string) => removeItems([lineId]), [removeItems]);\n\n // --- ACTION: applyDiscountCodes ---\n const applyDiscountCodes = useCallback(\n (codes: string[]) => {\n if (isHydrogenReact && hReactActions?.discountCodesUpdate) {\n rebuyDebugLog.log(DebugKey.SC_CTX_H_REACT, 'Dispatching H-React discountCodesUpdate:', codes);\n hReactActions.discountCodesUpdate(codes); // Fire-and-forget\n // VOID return for H-React path\n } else if (!isHydrogenReact) {\n return logRemixWarning('applyDiscountCodes');\n }\n },\n [isHydrogenReact, hReactActions]\n );\n\n // --- ACTION: updateCartAttributes ---\n const updateCartAttributes = useCallback(\n (attributes: StorefrontAttribute[]) => {\n if (isHydrogenReact && hReactActions?.cartAttributesUpdate) {\n const attrsToUpdate: HRAttributeInput[] = mapStorefrontAttributesToHRAttributes(attributes);\n rebuyDebugLog.log(DebugKey.SC_CTX_H_REACT, 'Dispatching H-React cartAttributesUpdate:', attrsToUpdate);\n hReactActions.cartAttributesUpdate(attrsToUpdate); // Fire-and-forget\n // VOID return for H-React path\n } else if (!isHydrogenReact) {\n return logRemixWarning('updateCartAttributes');\n }\n },\n [isHydrogenReact, hReactActions]\n );\n\n // --- ACTION: updateCartNote ---\n const updateCartNote = useCallback(\n (note: string | null) => {\n if (isHydrogenReact && hReactActions?.noteUpdate) {\n const noteToUpdate = note ?? '';\n rebuyDebugLog.log(DebugKey.SC_CTX_H_REACT, 'Dispatching H-React noteUpdate:', noteToUpdate);\n hReactActions.noteUpdate(noteToUpdate); // Fire-and-forget\n // VOID return for H-React path\n } else if (!isHydrogenReact) {\n return logRemixWarning('updateCartNote');\n }\n },\n [isHydrogenReact, hReactActions]\n );\n\n // --- ACTION: checkout ---\n const checkout = useCallback(() => {\n const checkoutUrl = mappedStorefrontCartData?.checkoutUrl;\n\n if (checkoutUrl) {\n window.location.href = checkoutUrl;\n } else {\n rebuyDebugLog.error(\n DebugKey.SC_CTX,\n 'Checkout failed: Checkout URL not available.',\n mappedStorefrontCartData\n );\n }\n }, [mappedStorefrontCartData]);\n\n // --- TPB Gift Sync Effect ---\n useEffect(() => {\n const conditions = {\n activeBarConfigPresent: !!activeBarConfig,\n cartDataIsEqual: isEqual(tpbInternalCartData, mappedStorefrontCartData),\n cartSyncStatusIsIdle: cartSyncStatus === 'idle',\n isTpbInternalCartReady,\n notIsManuallyDisabled: !isManuallyDisabled,\n productFetchStatusIsSuccess: productFetchStatus === 'success',\n tpbInternalCartDataNotNull: tpbInternalCartData !== null,\n userActionStatusIsIdle: userActionStatus === 'idle',\n };\n const allConditionsMet = Object.values(conditions).every(Boolean);\n\n if (allConditionsMet) {\n rebuyDebugLog.log(\n DebugKey.SC_CTX_TPB_SYNC,\n 'syncCartGifts trigger: Conditions MET. Calling tpbSyncCartGifts(). Conditions:',\n conditions\n );\n tpbSyncCartGifts();\n } else {\n rebuyDebugLog.log(\n DebugKey.SC_CTX_TPB_SYNC,\n 'syncCartGifts trigger: SKIPPING. Conditions NOT MET. Conditions:',\n conditions\n );\n }\n }, [\n isTpbInternalCartReady,\n productFetchStatus,\n activeBarConfig,\n isManuallyDisabled,\n tpbInternalCartData,\n cartSyncStatus,\n userActionStatus,\n tpbSyncCartGifts,\n mappedStorefrontCartData,\n ]);\n // --- Helper Functions ---\n const getItemCount = useCallback(() => mappedStorefrontCartData?.totalQuantity ?? 0, [mappedStorefrontCartData]);\n const getCartSubtotal = useCallback(\n () => mappedStorefrontCartData?.cost?.subtotalAmount?.amount ?? '0.00',\n [mappedStorefrontCartData]\n );\n const getComponentConfigByType = useCallback(\n <T extends SmartCartComponentConfig['type']>(type: T) =>\n config?.components?.find((comp) => comp.type === type) as\n | Extract<SmartCartComponentConfig, { type: T }>\n | undefined,\n [config?.components]\n );\n const getComponentConfigById = useCallback(\n (id: string) => config?.components?.find((comp) => comp.component_id === id),\n [config?.components]\n );\n\n // --- Provide Combined Context Value ---\n const combinedValue = useMemo<SmartCartContextValue>(\n () => ({\n addItem,\n addItems,\n apiKey,\n applyDiscountCodes,\n cacheKey,\n cartData: mappedStorefrontCartData,\n checkout,\n config,\n error,\n getCartSubtotal,\n getComponentConfigById,\n getComponentConfigByType,\n getItemCount,\n getTpbStore: () => tpbStoreInstance,\n hideCart,\n hydrogenReactCartActions: hReactActions,\n isCartBusy,\n isCartReady,\n isHydrogenReact,\n isLoading,\n isProgressBarLineItemMode,\n isVisible,\n removeItem,\n removeItems,\n shopifyDomain,\n showCart,\n storefrontAccessToken,\n toggleCart,\n updateCartAttributes,\n updateCartNote,\n updateItem,\n updateItems,\n }),\n [\n addItem,\n addItems,\n apiKey,\n applyDiscountCodes,\n cacheKey,\n mappedStorefrontCartData,\n checkout,\n config,\n error,\n getCartSubtotal,\n getComponentConfigById,\n getComponentConfigByType,\n getItemCount,\n tpbStoreInstance,\n hideCart,\n hReactActions,\n isCartBusy,\n isCartReady,\n isHydrogenReact,\n isLoading,\n isProgressBarLineItemMode,\n isVisible,\n removeItem,\n removeItems,\n shopifyDomain,\n showCart,\n storefrontAccessToken,\n toggleCart,\n updateCartAttributes,\n updateCartNote,\n updateItem,\n updateItems,\n ]\n );\n\n return <SmartCartContext.Provider value={combinedValue}>{children}</SmartCartContext.Provider>;\n};\n\n// Keep track if warning was logged to avoid spamming console\nlet warningLogged = false;\n\n// --- The Combined Hook for Consumption ---\nexport const useSmartCart = (): SmartCartContextValue => {\n const context = useContext(SmartCartContext);\n\n // Check if the context value is the default/undefined value\n if (context === undefined || context === null) {\n if (!warningLogged) {\n console.warn(\n 'useSmartCart hook called, but the SmartCartProvider is not available in the component tree. ' +\n 'This might happen if \"enableSmartCart\" is set to false or if prerequisites were not met. ' +\n 'Smart Cart features will be disabled for this component.'\n );\n warningLogged = true; // Log only once\n }\n\n // Return a \"null\" or default version of the context shape\n // so components using the hook don't crash when destructuring\n const warn = () =>\n console.warn(\n 'SmartCart operation attempted, but no SmartCartProvider was found in the component hierarchy. ' +\n 'This may occur if \"enableSmartCart\" is disabled or if required configuration is missing. ' +\n 'Smart Cart functionality is unavailable for this component.'\n );\n\n return {\n addItem: () => warn(),\n addItems: () => warn(),\n apiKey: '',\n applyDiscountCodes: () => warn(),\n cacheKey: '',\n cartData: null,\n checkout: () => warn(),\n config: null,\n error: null,\n getCartSubtotal: () => '0.00',\n getComponentConfigById: () => undefined,\n getComponentConfigByType: () => undefined,\n getItemCount: () => 0,\n getTpbStore: () => null,\n hideCart: () => warn(),\n isCartBusy: false,\n isCartReady: false,\n isHydrogenReact: false,\n isLoading: false,\n isProgressBarLineItemMode: false,\n isVisible: false,\n removeItem: () => warn(),\n removeItems: () => warn(),\n shopifyDomain: '',\n showCart: () => warn(),\n storefrontAccessToken: '',\n toggleCart: () => warn(),\n updateCartAttributes: () => warn(),\n updateCartNote: () => warn(),\n updateItem: () => warn(),\n updateItems: () => warn(),\n } as unknown as SmartCartContextValue;\n }\n\n return context;\n};\n", "// ~/smart-cart/store/tieredProgressBarStore.ts\nimport { flattenConnection } from '@shopify/hydrogen';\nimport type { CartLineInput as HRCartLineInput } from '@shopify/hydrogen-react/storefront-api-types';\nimport type { CartLine } from '@shopify/hydrogen/storefront-api-types'; // eslint-disable-line import/order\nimport { isEqual } from 'lodash-es';\nimport { create } from 'zustand';\nimport { DebugKey } from '~/constants/debug';\n\nimport {\n calculateCurrentProgressBarSubtotal,\n checkHasFreeShippingOnSubscription,\n checkIsTierReached,\n getDeclineKey,\n getNumericIdFromGid,\n updateDeclinedCache,\n} from '~/smart-cart/components/TieredProgressBar/progressBarUtils';\nimport {\n TieredProgressBarGiftStatus as GiftStatus,\n type TieredProgressBar,\n type TieredProgressBarCachedGiftData,\n type TieredProgressBarFetchedProductData,\n type TieredProgressBarQualifiedGiftState,\n type TieredProgressBarSettings,\n TieredProgressBarTierType,\n} from '~/smart-cart/components/TieredProgressBar/types';\nimport { RebuyLineItemAttribution, SessionStorageKey } from '~/smart-cart/constants';\nimport type { StorefrontAttribute, StorefrontCartData } from '~/smart-cart/types/rebuy-storefront-cart';\nimport { isTieredProgressBarGiftItem } from '~/smart-cart/utils/cartItemUtils';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport { safeJsonParse } from '~/smart-cart/utils/safeJsonParse';\n\nexport type TieredProgressBarStoreState = {\n _addItemsImpl: ((items: HRCartLineInput[]) => void) | null;\n _lastFetchedBarId: string | null;\n _removeItemsImpl: ((lineIds: string[]) => void) | null;\n _shopifyDomain: string;\n _storefrontAccessToken: string;\n activeBarConfig: TieredProgressBar | null;\n cartData: StorefrontCartData | null;\n cartSyncError: string | null;\n cartSyncStatus: 'idle' | 'syncing' | 'success' | 'error' | 'awaiting_cart_update';\n currentSubtotal: number;\n declinedGiftMap: Record<string, boolean>;\n fetchedProductMap: Map<number, TieredProgressBarFetchedProductData>;\n giftStates: Map<string, TieredProgressBarQualifiedGiftState>;\n hasFreeShippingOnSubscription: boolean;\n initializationStatus: 'idle' | 'pending' | 'complete';\n isCartReady: boolean;\n isManuallyDisabled: boolean;\n lastErrorTimestamp: number;\n productFetchError: string | null;\n productFetchStatus: 'idle' | 'loading' | 'success' | 'error';\n settings: TieredProgressBarSettings | null;\n userActionError: { message: string; tierId: string } | null;\n /* Prevent fetching the same bar multiple times */\n userActionStatus: 'idle' | 'pending' | 'error';\n};\n\nexport type TieredProgressBarStoreActions = {\n /** Clears any active user action error. */\n clearUserActionError: () => void;\n /** Manually disables the progress bar. */\n disableBar: () => void;\n /** Manually enables the progress bar if it was disabled. */\n enableBar: () => void;\n /** Fetches product data for gift tiers from Shopify Storefront API. Caches results in session storage. */\n fetchProducts: () => Promise<void>;\n /**\n * Handles user action to add or re-add a gift (if previously declined).\n * For single-variant gifts, adds to cart. For multi-variant, undeclines and shows selector.\n */\n handleAddOrReAddGift: (tierId: string) => void;\n /**\n * Handles user action to remove a gift from the cart and mark it as declined for the current tier.\n */\n handleRemoveGift: (tierId: string) => void;\n /**\n * Handles user selection of a gift variant.\n * Adds the selected variant to the cart and removes any existing gift from the same tier.\n */\n handleSelectVariant: (tierId: string, variantGid: string) => void;\n /** Initializes the store with settings and Shopify connection details. */\n init: (settings: TieredProgressBarSettings, shopifyDomain: string, storefrontAccessToken: string) => Promise<void>;\n /**\n * Recalculates derived state based on current cart data, settings, and fetched products.\n * This includes subtotal, tier statuses, gift states, etc.\n * Typically called internally after cart updates or product fetches.\n */\n recalculateState: () => void;\n /** Sets the cart data and readiness state, usually called when the main cart context updates. */\n setCartData: (cartData: StorefrontCartData | null, isCartReady: boolean) => void;\n /** Sets the internal submit functions for cart actions. */\n setSubmitFunctions: (\n addItemsImpl: (items: HRCartLineInput[]) => void,\n removeItemsImpl: (lineIds: string[]) => void\n ) => void;\n /**\n * Synchronizes gifts in the cart with the calculated qualified gifts.\n * Automatically adds/removes gift items based on tier reachability and availability.\n */\n syncCartGifts: () => Promise<void>;\n};\n\nexport type TieredProgressBarStore = TieredProgressBarStoreState & TieredProgressBarStoreActions;\n\n// --- Initial State ---\nconst initialStoreState: TieredProgressBarStoreState = {\n _addItemsImpl: null,\n _lastFetchedBarId: null,\n _removeItemsImpl: null,\n _shopifyDomain: '',\n _storefrontAccessToken: '',\n activeBarConfig: null,\n cartData: null,\n cartSyncError: null,\n cartSyncStatus: 'idle',\n currentSubtotal: 0,\n declinedGiftMap: {},\n fetchedProductMap: new Map(),\n giftStates: new Map(),\n hasFreeShippingOnSubscription: false,\n initializationStatus: 'idle',\n isCartReady: false,\n isManuallyDisabled: false,\n lastErrorTimestamp: 0,\n productFetchError: null,\n productFetchStatus: 'idle',\n settings: null,\n userActionError: null,\n userActionStatus: 'idle',\n};\n\n// --- Store Creation ---\nexport const useTieredProgressBarStore = create<TieredProgressBarStore>((set, get) => ({\n ...initialStoreState,\n clearUserActionError: () => {\n const currentState = get();\n\n if (currentState.userActionError || currentState.userActionStatus !== 'idle') {\n set({ userActionError: null, userActionStatus: 'idle' });\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, 'User action error cleared.');\n }\n },\n\n disableBar: () => {\n const currentState = get();\n const updates: Partial<TieredProgressBarStoreState> = {};\n let hasChanges = false;\n\n if (!currentState.isManuallyDisabled) {\n updates.isManuallyDisabled = true;\n hasChanges = true;\n }\n\n if (currentState.giftStates.size > 0) {\n updates.giftStates = new Map();\n hasChanges = true;\n }\n\n if (currentState.currentSubtotal !== 0) {\n updates.currentSubtotal = 0;\n hasChanges = true;\n }\n\n if (hasChanges) {\n set(updates);\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[disableBar] Bar disabled. Relevant states cleared/reset.');\n } else {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n '[disableBar] Bar already effectively disabled or no state changes needed.'\n );\n }\n get().recalculateState();\n },\n\n enableBar: () => {\n if (get().isManuallyDisabled) {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[enableBar] Enabling bar.');\n set({ isManuallyDisabled: false });\n\n if (\n get().activeBarConfig &&\n get().productFetchStatus !== 'success' &&\n get()._lastFetchedBarId !== get().activeBarConfig?.id\n ) {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[enableBar] Triggering product fetch as bar is enabled.');\n get().fetchProducts();\n } else {\n get().recalculateState();\n }\n } else {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[enableBar] Bar already enabled.');\n }\n },\n\n fetchProducts: async () => {\n const { _lastFetchedBarId, _shopifyDomain, _storefrontAccessToken, activeBarConfig, isManuallyDisabled } =\n get();\n\n if (get().productFetchStatus === 'loading') {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[fetchProducts] Already loading. Skipping.');\n\n return;\n }\n\n if (!activeBarConfig || isManuallyDisabled || !_shopifyDomain || !_storefrontAccessToken) {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[fetchProducts] Preconditions not met. Skipping.');\n\n return;\n }\n\n if (_lastFetchedBarId === activeBarConfig.id && get().productFetchStatus === 'success') {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[fetchProducts] Products already fetched for bar ID: ${activeBarConfig.id}.`\n );\n\n if (get().isCartReady) get().recalculateState();\n\n return;\n }\n const giftTiers = activeBarConfig.tiers.filter((t) => t.type === TieredProgressBarTierType.PRODUCT);\n const neededLegacyIds = Array.from(\n new Set(giftTiers.flatMap((t) => t.products?.map((p) => p.product_id) ?? []))\n );\n\n if (neededLegacyIds.length === 0) {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[fetchProducts] No gift products to fetch for bar ID: ${activeBarConfig.id}.`\n );\n\n set({\n _lastFetchedBarId: activeBarConfig.id,\n declinedGiftMap: {},\n fetchedProductMap: new Map(),\n productFetchStatus: 'success',\n });\n\n if (get().isCartReady) get().recalculateState();\n\n return;\n }\n set({ productFetchError: null, productFetchStatus: 'loading' });\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[fetchProducts] Starting product fetch for Bar ID: ${activeBarConfig.id}, Product IDs:`,\n neededLegacyIds\n );\n let combinedProductData: TieredProgressBarFetchedProductData[] = [];\n let loadedDeclinedMap: Record<string, boolean> = {};\n let idsToFetch = [...neededLegacyIds];\n let fetchError: string | null = null;\n try {\n const CACHE_DURATION_MS = 15 * 60 * 1000;\n const cachedDataString = sessionStorage.getItem(SessionStorageKey.TIERED_PROGRESS_BAR_GIFT_DATA);\n const cachedStoreData: TieredProgressBarCachedGiftData | null = safeJsonParse(cachedDataString);\n const isCacheValid = cachedStoreData && Date.now() - cachedStoreData.timestamp < CACHE_DURATION_MS;\n\n if (isCacheValid && cachedStoreData) {\n const cachedMap = new Map(cachedStoreData.products.map((p) => [getNumericIdFromGid(p.id), p]));\n idsToFetch = neededLegacyIds.filter((id) => !cachedMap.has(id));\n combinedProductData = cachedStoreData.products.filter((p) =>\n neededLegacyIds.includes(getNumericIdFromGid(p.id))\n );\n loadedDeclinedMap = cachedStoreData.declined ?? {};\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[fetchProducts] Cache ${idsToFetch.length === 0 ? 'hit for all products.' : `hit for some products. Fetching remaining: ${idsToFetch.join(', ')}`}`\n );\n } else {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[fetchProducts] Cache invalid or empty. Fetching all: ${idsToFetch.join(', ')}`\n );\n }\n\n if (idsToFetch.length > 0) {\n const productGids = idsToFetch.map((id) => `gid://shopify/Product/${id}`);\n const graphqlQuery = `query getProductsByIds($ids: [ID!]!) { nodes(ids: $ids) { ... on Product { id title handle tags images(first: 1) { edges { node { url altText } } } variants(first: 30) { edges { node { id title sku availableForSale price { amount currencyCode } compareAtPrice { amount currencyCode } selectedOptions { name value } image { url altText } } } } } } }`;\n const response = await fetch(`https://${_shopifyDomain}/api/2025-01/graphql.json`, {\n body: JSON.stringify({ query: graphqlQuery, variables: { ids: productGids } }),\n headers: {\n 'Content-Type': 'application/json',\n 'X-Shopify-Storefront-Access-Token': _storefrontAccessToken,\n },\n method: 'POST',\n });\n\n if (!response.ok) throw new Error(`GraphQL fetch failed: ${response.status} ${response.statusText}`);\n const json = await response.json();\n\n if (json.errors) throw new Error(`GraphQL errors: ${JSON.stringify(json.errors)}`);\n const fetchedNodes = (json.data?.nodes ?? []).filter(Boolean) as TieredProgressBarFetchedProductData[];\n const fetchedMap = new Map(fetchedNodes.map((p) => [getNumericIdFromGid(p.id), p]));\n const existingMap = new Map(combinedProductData.map((p) => [getNumericIdFromGid(p.id), p]));\n fetchedMap.forEach((value, key) => existingMap.set(key, value));\n combinedProductData = Array.from(existingMap.values());\n }\n sessionStorage.setItem(\n SessionStorageKey.TIERED_PROGRESS_BAR_GIFT_DATA,\n JSON.stringify({ declined: loadedDeclinedMap, products: combinedProductData, timestamp: Date.now() })\n );\n } catch (err) {\n fetchError = err instanceof Error ? err.message : 'Unknown product fetch error.';\n }\n const currentStoreState = get();\n\n if (fetchError) {\n if (\n currentStoreState.productFetchStatus !== 'error' ||\n currentStoreState.productFetchError !== fetchError\n ) {\n set({ _lastFetchedBarId: null, productFetchError: fetchError, productFetchStatus: 'error' });\n }\n } else {\n const finalProductMapCandidate = new Map(combinedProductData.map((p) => [getNumericIdFromGid(p.id), p]));\n const mergedDeclinedMapCandidate = { ...loadedDeclinedMap, ...currentStoreState.declinedGiftMap };\n const updates: Partial<TieredProgressBarStoreState> = { productFetchStatus: 'success' };\n let hasChanges = currentStoreState.productFetchStatus !== 'success';\n\n if (!isEqual(currentStoreState.fetchedProductMap, finalProductMapCandidate)) {\n updates.fetchedProductMap = finalProductMapCandidate;\n hasChanges = true;\n }\n\n if (!isEqual(currentStoreState.declinedGiftMap, mergedDeclinedMapCandidate)) {\n updates.declinedGiftMap = mergedDeclinedMapCandidate;\n hasChanges = true;\n }\n\n if (currentStoreState._lastFetchedBarId !== activeBarConfig.id) {\n updates._lastFetchedBarId = activeBarConfig.id;\n hasChanges = true;\n }\n\n if (hasChanges) set(updates);\n\n if (get().isCartReady) get().recalculateState();\n }\n },\n\n handleAddOrReAddGift: (tierId) => {\n const state = get();\n const { _addItemsImpl, userActionStatus: initialUserActionStatus } = state;\n\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] BEGIN for tier ${tierId}. Initial userActionStatus: ${initialUserActionStatus}`\n );\n\n if (!_addItemsImpl) {\n rebuyDebugLog.error(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] _addItemsImpl not set. Cannot add gift for tier ${tierId}.`\n );\n\n return;\n }\n\n if (state.userActionStatus === 'pending' || state.productFetchStatus !== 'success') {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] Action blocked (userActionStatus: ${state.userActionStatus}, productFetchStatus: ${state.productFetchStatus}) for tier ${tierId}`\n );\n\n return;\n }\n const giftState = state.giftStates.get(tierId);\n\n if (!giftState || !giftState.isReached || giftState.availableChoices.length === 0) {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] Gift not available or tier not reached for ${tierId}. State:`,\n giftState\n );\n set({\n lastErrorTimestamp: Date.now(),\n userActionError: { message: 'Gift unavailable or tier not reached', tierId },\n userActionStatus: 'error',\n });\n\n return;\n }\n\n // Set to pending for all cases initially\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] BEFORE setting userActionStatus to 'pending'. Current: ${get().userActionStatus}`\n );\n set({ userActionError: null, userActionStatus: 'pending' });\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] AFTER setting userActionStatus to 'pending'. Current: ${get().userActionStatus}`\n );\n\n const declineKey = getDeclineKey(tierId, giftState.legacyProductId);\n const wasDeclined = state.declinedGiftMap[declineKey] ?? false;\n\n if (wasDeclined) {\n const nextDeclinedMap = { ...state.declinedGiftMap };\n delete nextDeclinedMap[declineKey];\n set({ declinedGiftMap: nextDeclinedMap }); // This set can be batched\n updateDeclinedCache(nextDeclinedMap);\n\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] Undeclined gift for tier ${tierId}. Current userActionStatus: ${get().userActionStatus}`\n );\n }\n\n // --- Multi-variant path ---\n if (giftState.availableChoices.length > 1) {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] Multi-variant gift for tier ${tierId}. Undeclined. Recalculating state to show select. Setting userActionStatus back to 'idle'.`\n );\n // For multi-variant, the \"action\" is just to undecline and show the selector.\n // No Shopify cart operation is dispatched yet.\n // So, we can reset userActionStatus to 'idle' here to allow selection.\n // recalculateState() will update the gift's displayStatus to NEEDS_SELECTION.\n get().recalculateState();\n set({ userActionStatus: 'idle' }); // Reset to idle as the immediate \"re-add\" action is complete (it was just an undecline)\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] Multi-variant gift flow complete. userActionStatus is now: ${get().userActionStatus}`\n );\n\n return;\n }\n\n // --- Single variant gift path ---\n // (If it wasn't declined, and it's single-variant, this implies it's a fresh add,\n // though syncCartGifts usually handles fresh adds. This path mostly covers re-adding a declined single-variant gift.)\n if (giftState.availableChoices.length === 1) {\n const variantToAdd = giftState.availableChoices[0];\n const itemToAdd: HRCartLineInput = {\n attributes: [\n { key: '_source', value: 'Rebuy' },\n { key: '_attribution', value: RebuyLineItemAttribution.TIERED_PROGRESS_BAR },\n { key: '_tier', value: tierId },\n ],\n merchandiseId: variantToAdd.id,\n quantity: 1,\n };\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] BEFORE _addItemsImpl for single-variant gift. Current userActionStatus: ${get().userActionStatus}`\n );\n _addItemsImpl([itemToAdd]); // Fire-and-forget H-React action\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] AFTER _addItemsImpl. Dispatched addItems. Current userActionStatus: ${get().userActionStatus}. Waiting for cart update to reset userActionStatus via setCartData.`\n );\n\n // userActionStatus remains 'pending' and will be reset by setCartData when the Shopify update arrives.\n return;\n }\n\n // Fallback: Should not be reached if availableChoices checks are correct\n // but if it does, reset status if nothing happened.\n rebuyDebugLog.warn(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] Reached end of function unexpectedly for tier ${tierId}. Resetting userActionStatus to 'idle'.`\n );\n set({ userActionStatus: 'idle' });\n },\n\n handleRemoveGift: (tierId) => {\n const state = get();\n const { _removeItemsImpl, userActionStatus: initialUserActionStatus } = state;\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleRemoveGift] BEGIN for tier ${tierId}. Initial userActionStatus: ${initialUserActionStatus}`\n );\n\n if (!_removeItemsImpl) {\n rebuyDebugLog.error(\n DebugKey.SC_TPB_STORE,\n `[handleRemoveGift] _removeItemsImpl not set. Cannot remove gift for tier ${tierId}.`\n );\n\n return;\n }\n\n if (state.userActionStatus === 'pending' || state.productFetchStatus !== 'success') {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleRemoveGift] Action blocked (userActionStatus: ${state.userActionStatus}, productFetchStatus: ${state.productFetchStatus}) for tier ${tierId}`\n );\n\n return;\n }\n\n const giftState = state.giftStates.get(tierId);\n\n if (!giftState?.legacyProductId) {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleRemoveGift] No gift state or legacyProductId for tier ${tierId}`\n );\n set({\n lastErrorTimestamp: Date.now(),\n userActionError: { message: 'Gift state invalid', tierId },\n userActionStatus: 'error',\n });\n\n return;\n }\n\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleRemoveGift] BEFORE setting userActionStatus to 'pending'. Current: ${get().userActionStatus}`\n );\n set({ userActionError: null, userActionStatus: 'pending' });\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleRemoveGift] AFTER setting userActionStatus to 'pending'. Current: ${get().userActionStatus}`\n );\n\n const declineKey = getDeclineKey(tierId, giftState.legacyProductId);\n\n if (!(state.declinedGiftMap[declineKey] ?? false)) {\n const nextDeclinedMap = { ...state.declinedGiftMap, [declineKey]: true };\n set({ declinedGiftMap: nextDeclinedMap });\n updateDeclinedCache(nextDeclinedMap);\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleRemoveGift] Declined gift for tier ${tierId}. Current userActionStatus: ${get().userActionStatus}`\n );\n }\n\n const cartLines = state.cartData?.lines ? flattenConnection(state.cartData.lines) : [];\n const lineToRemoveId = cartLines.find((line) =>\n line.attributes?.some((attr) => attr.key === '_tier' && attr.value === tierId)\n )?.id;\n\n if (lineToRemoveId) {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleRemoveGift] BEFORE _removeItemsImpl. Current userActionStatus: ${get().userActionStatus}`\n );\n _removeItemsImpl([lineToRemoveId]);\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleRemoveGift] AFTER _removeItemsImpl. Dispatched. Current userActionStatus: ${get().userActionStatus}. Waiting for cart update.`\n );\n } else {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleRemoveGift] No cart line to remove for tier ${tierId}. Gift declined (if not already). Recalculating. Current userActionStatus: ${get().userActionStatus}`\n );\n }\n get().recalculateState();\n },\n\n handleSelectVariant: (tierId, variantGid) => {\n const state = get();\n const { _addItemsImpl, _removeItemsImpl, userActionStatus: initialUserActionStatus } = state;\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleSelectVariant] BEGIN for tier ${tierId}, variant ${variantGid}. Initial userActionStatus: ${initialUserActionStatus}`\n );\n\n if (!_addItemsImpl || !_removeItemsImpl) {\n rebuyDebugLog.error(\n DebugKey.SC_TPB_STORE,\n `[handleSelectVariant] Submit functions not set. Cannot select variant for tier ${tierId}.`\n );\n\n return;\n }\n\n if (state.userActionStatus === 'pending' || state.productFetchStatus !== 'success') {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleSelectVariant] Action blocked (userActionStatus: ${state.userActionStatus}, productFetchStatus: ${state.productFetchStatus})`\n );\n\n return;\n }\n\n const giftState = state.giftStates.get(tierId);\n const selectedVariant = giftState?.availableChoices.find((v) => v.id === variantGid);\n\n if (!giftState || !selectedVariant) {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleSelectVariant] No gift state for tier ${tierId} or variant not available`\n );\n set({\n lastErrorTimestamp: Date.now(),\n userActionError: { message: 'Invalid gift state or variant selection', tierId },\n userActionStatus: 'error',\n });\n\n return;\n }\n\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleSelectVariant] BEFORE setting userActionStatus to 'pending'. Current: ${get().userActionStatus}`\n );\n set({ userActionError: null, userActionStatus: 'pending' });\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleSelectVariant] AFTER setting userActionStatus to 'pending'. Current: ${get().userActionStatus}`\n );\n\n const declineKey = getDeclineKey(tierId, giftState.legacyProductId);\n const wasDeclined = state.declinedGiftMap[declineKey] ?? false;\n\n if (wasDeclined) {\n const nextDeclinedMap = { ...state.declinedGiftMap };\n delete nextDeclinedMap[declineKey];\n set({ declinedGiftMap: nextDeclinedMap });\n updateDeclinedCache(nextDeclinedMap);\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, `[handleSelectVariant] Undeclined gift for tier ${tierId}`);\n }\n\n const cartLines = state.cartData?.lines ? flattenConnection(state.cartData.lines) : [];\n const lineToRemoveId = cartLines.find((line) =>\n line.attributes?.some((attr) => attr.key === '_tier' && attr.value === tierId)\n )?.id;\n\n if (lineToRemoveId) {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleSelectVariant] BEFORE _removeItemsImpl. Current userActionStatus: ${get().userActionStatus}`\n );\n _removeItemsImpl([lineToRemoveId]); // Fire-and-forget\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleSelectVariant] AFTER _removeItemsImpl. Current userActionStatus: ${get().userActionStatus}`\n );\n }\n\n const itemToAdd: HRCartLineInput = {\n attributes: [\n { key: '_source', value: 'Rebuy' },\n { key: '_attribution', value: RebuyLineItemAttribution.TIERED_PROGRESS_BAR },\n { key: '_tier', value: tierId },\n ],\n merchandiseId: variantGid,\n quantity: 1,\n };\n\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleSelectVariant] BEFORE _addItemsImpl for new variant. Current userActionStatus: ${get().userActionStatus}`\n );\n _addItemsImpl([itemToAdd]); // Fire-and-forget\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleSelectVariant] AFTER _addItemsImpl. Dispatched. Current userActionStatus: ${get().userActionStatus}. Waiting for cart update.`\n );\n },\n // --- ACTIONS ---\n // eslint-disable-next-line require-await\n init: async (newSettings, shopifyDomain, storefrontAccessToken) => {\n const currentState = get();\n set({ initializationStatus: 'pending' });\n let rawSelectedBar: TieredProgressBar | null = null;\n\n /**\n * TODO: Geolocation support\n * This will involve:\n * 1. Accepting userCountryCode as a parameter.\n * 2. Implementing the logic to iterate through newSettings.bars, check\n * bar.geolocation_enabled and bar.country_codes against userCountryCode.\n * 3. Selecting the bar based on priority (geo-match first, then first default).\n */\n if (newSettings && newSettings.bars && newSettings.bars.length > 0) {\n rawSelectedBar = newSettings.bars[0];\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, `Selecting first available bar: ${rawSelectedBar?.id ?? 'None'}`);\n } else {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[TPB Store Init] No bars in newSettings or newSettings is null.');\n }\n let finalActiveBarConfig: TieredProgressBar | null = null;\n\n if (rawSelectedBar) {\n finalActiveBarConfig = {\n ...rawSelectedBar,\n tiers: [...(rawSelectedBar.tiers ?? [])].sort((a, b) => a.minimum - b.minimum),\n };\n }\n const prevActiveBarId = currentState.activeBarConfig?.id;\n const newActiveBarId = finalActiveBarConfig?.id;\n const updates: Partial<TieredProgressBarStoreState> = {\n _shopifyDomain: shopifyDomain,\n _storefrontAccessToken: storefrontAccessToken,\n activeBarConfig: finalActiveBarConfig,\n initializationStatus: 'complete',\n settings: newSettings,\n };\n\n if (prevActiveBarId !== newActiveBarId) {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `Active bar changed from ${prevActiveBarId ?? 'None'} to ${newActiveBarId ?? 'None'}. Resetting product-related states.`\n );\n updates.fetchedProductMap = new Map();\n updates.giftStates = new Map();\n updates.productFetchStatus = 'idle';\n updates.productFetchError = null;\n updates.cartSyncStatus = 'idle';\n updates.cartSyncError = null;\n updates.userActionStatus = 'idle';\n updates.userActionError = null;\n updates._lastFetchedBarId = null;\n }\n set(updates);\n\n if (finalActiveBarConfig && !get().isManuallyDisabled) {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `Active bar \"${finalActiveBarConfig.id}\". Triggering product fetch.`\n );\n await get().fetchProducts();\n } else {\n if (!finalActiveBarConfig) {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n 'No active bar after selection. Products will not be fetched.'\n );\n } else if (get().isManuallyDisabled) {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, 'Bar is manually disabled. Products will not be fetched.');\n }\n }\n },\n\n recalculateState: () => {\n const state = get();\n rebuyDebugLog.groupCollapsed(DebugKey.SC_TPB_STORE, '[recalculateState] Execution Started.');\n\n const { activeBarConfig, cartData, giftStates: currentGiftStates, isCartReady, productFetchStatus } = state;\n\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n '[recalculateState] Input cart subtotal:',\n cartData?.cost?.subtotalAmount?.amount,\n 'Declined map:',\n state.declinedGiftMap\n );\n\n if (!activeBarConfig || !isCartReady || productFetchStatus !== 'success' || !cartData) {\n if (currentGiftStates.size > 0 || state.currentSubtotal !== 0) {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[recalculateState] Preconditions not met, resetting relevant states. Details:`,\n {\n activeBar: !!activeBarConfig,\n cartData: !!cartData,\n cartReady: isCartReady,\n productFetch: productFetchStatus,\n }\n );\n set({ currentSubtotal: 0, giftStates: new Map() });\n }\n rebuyDebugLog.groupEnd();\n\n return;\n }\n\n const actualCartLines = cartData.lines ? flattenConnection(cartData.lines) : [];\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[recalculateState] Starting. Cart lines count: ${actualCartLines.length}, Current subtotal (from state): ${state.currentSubtotal}`\n );\n\n const nextCurrentSubtotal = calculateCurrentProgressBarSubtotal(cartData, activeBarConfig);\n const nextHasFreeShippingOnSubscription = checkHasFreeShippingOnSubscription(cartData, activeBarConfig);\n\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n '[recalculateState] Next current subtotal:',\n nextCurrentSubtotal,\n 'Next has free shipping on subscription:',\n nextHasFreeShippingOnSubscription\n );\n\n const newGiftStatesCandidate = new Map<string, TieredProgressBarQualifiedGiftState>();\n\n const giftLinesInCart = actualCartLines.filter((line) => isTieredProgressBarGiftItem(line as CartLine));\n\n activeBarConfig.tiers.forEach((tier) => {\n if (tier.type !== TieredProgressBarTierType.PRODUCT || !tier.products?.[0]) return;\n\n const tierProductSettings = tier.products[0];\n const legacyProductId = tierProductSettings.product_id;\n const fetchedProduct = state.fetchedProductMap.get(legacyProductId);\n\n if (!fetchedProduct) return;\n\n const tierId = tier.id;\n const isReached = checkIsTierReached(tier, nextCurrentSubtotal, nextHasFreeShippingOnSubscription);\n const allVariants = fetchedProduct.variants.edges.map((e) => e.node);\n const allowedVariantLegacyIds = new Set(tierProductSettings.variant_ids ?? []);\n const filterOOS = tier.filter_oos_variants ?? false;\n\n const availableChoices = allVariants.filter((v) => {\n const legacyVariantId = getNumericIdFromGid(v.id);\n const isAllowed = allowedVariantLegacyIds.size === 0 || allowedVariantLegacyIds.has(legacyVariantId);\n const isInStock = !filterOOS || v.availableForSale;\n\n return isAllowed && isInStock;\n });\n\n const declineKey = getDeclineKey(tierId, legacyProductId);\n const isDeclined = state.declinedGiftMap[declineKey] ?? false;\n\n const cartLineForThisGift = giftLinesInCart.find((line) =>\n line.attributes?.some((attr) => attr.key === '_tier' && attr.value === tierId)\n );\n const isInCart = !!cartLineForThisGift;\n const variantInCart = isInCart\n ? (allVariants.find((v) => v.id === cartLineForThisGift?.merchandise.id) ?? null)\n : null;\n\n let currentError = null;\n const existingGiftState = currentGiftStates.get(tierId);\n\n if (existingGiftState?.error && Date.now() - state.lastErrorTimestamp < 7000) {\n currentError = existingGiftState.error;\n }\n\n if (\n state.userActionError &&\n state.userActionError.tierId === tierId &&\n Date.now() - state.lastErrorTimestamp < 7000\n ) {\n currentError = state.userActionError.message;\n }\n\n let displayStatus: GiftStatus;\n\n if (currentError) displayStatus = GiftStatus.ERROR;\n else if (!isReached) displayStatus = GiftStatus.IDLE;\n else if (availableChoices.length === 0) displayStatus = GiftStatus.UNAVAILABLE;\n else if (isInCart) displayStatus = GiftStatus.ADDED;\n else if (isDeclined) displayStatus = GiftStatus.DECLINED;\n else if (availableChoices.length > 1) displayStatus = GiftStatus.NEEDS_SELECTION;\n else displayStatus = GiftStatus.IDLE;\n\n const canReAdd = isReached && isDeclined && availableChoices.length > 0 && !currentError;\n\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[recalculateState] Tier ${tierId}: isReached=${isReached}, isInCart=${isInCart} (lineId: ${cartLineForThisGift?.id ?? 'N/A'}), isDeclined=${isDeclined}, choices=${availableChoices.length}, status=${displayStatus}`\n );\n\n const qualifiedGiftStateForThisTier: TieredProgressBarQualifiedGiftState = {\n allowedVariantIds: tierProductSettings.variant_ids ?? [],\n availableChoices,\n canReAdd,\n displayStatus,\n error: currentError,\n filterOOS,\n handle: fetchedProduct.handle,\n image: fetchedProduct.images?.edges[0]?.node\n ? {\n altText: fetchedProduct.images.edges[0].node.altText ?? '',\n src: fetchedProduct.images.edges[0].node.url,\n }\n : undefined,\n isDeclined,\n isInCart,\n isReached,\n legacyProductId,\n productId: fetchedProduct.id,\n tierId,\n title: fetchedProduct.title,\n variantInCart,\n variants: allVariants,\n };\n newGiftStatesCandidate.set(tierId, qualifiedGiftStateForThisTier);\n });\n\n const updates: Partial<TieredProgressBarStoreState> = {};\n let hasChanges = false;\n\n if (state.currentSubtotal !== nextCurrentSubtotal) {\n updates.currentSubtotal = nextCurrentSubtotal;\n hasChanges = true;\n }\n\n if (state.hasFreeShippingOnSubscription !== nextHasFreeShippingOnSubscription) {\n updates.hasFreeShippingOnSubscription = nextHasFreeShippingOnSubscription;\n hasChanges = true;\n }\n\n if (!isEqual(currentGiftStates, newGiftStatesCandidate)) {\n updates.giftStates = newGiftStatesCandidate;\n hasChanges = true;\n }\n\n const nextCartSyncError =\n state.cartSyncError && Date.now() - state.lastErrorTimestamp > 7000 ? null : state.cartSyncError;\n\n if (state.cartSyncError !== nextCartSyncError) {\n updates.cartSyncError = nextCartSyncError;\n hasChanges = true;\n }\n\n if (hasChanges) {\n set(updates);\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n '[recalculateState] Completed. Changes detected and applied. New giftStates:',\n JSON.parse(JSON.stringify(Array.from(get().giftStates.entries()))),\n 'New subtotal:',\n get().currentSubtotal\n );\n } else {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[recalculateState] Completed. No effective state changes.');\n }\n rebuyDebugLog.groupEnd();\n },\n\n setCartData: (newCartData, newIsCartReady) => {\n const currentState = get(); // Get state *before* any modifications by this call\n\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n '[setCartData] Called. Current userActionStatus:',\n currentState.userActionStatus,\n 'Current cartSyncStatus:',\n currentState.cartSyncStatus,\n 'New isCartReady:',\n newIsCartReady\n // 'New cartData:', newCartData // Can be verbose\n );\n\n const updates: Partial<TieredProgressBarStoreState> = {};\n let didCartDataContentChange = false;\n let didIsCartReadyChange = false;\n\n if (!isEqual(currentState.cartData, newCartData)) {\n updates.cartData = newCartData;\n didCartDataContentChange = true;\n }\n\n if (currentState.isCartReady !== newIsCartReady) {\n updates.isCartReady = newIsCartReady;\n didIsCartReadyChange = true;\n }\n\n if (didCartDataContentChange || didIsCartReadyChange) {\n set(updates); // Apply basic cartData and isCartReady updates first\n }\n\n const stateAfterCartDataUpdate = get(); // Get state after potential cartData/isCartReady update\n\n // Recalculate internal gift states, subtotal etc. based on the (potentially) new cartData\n if (\n stateAfterCartDataUpdate.isCartReady &&\n (stateAfterCartDataUpdate.productFetchStatus === 'success' || !stateAfterCartDataUpdate.activeBarConfig)\n ) {\n stateAfterCartDataUpdate.recalculateState();\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[setCartData] recalculateState() was called.');\n } else {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[setCartData] recalculateState() was SKIPPED.', {\n /* ... conditions ... */\n });\n }\n\n // Now, manage status transitions based on the fresh state from recalculateState\n const statusUpdates: Partial<TieredProgressBarStoreState> = {};\n let statusesChanged = false;\n\n // If a user action was pending, the arrival and processing of new cart data means\n // we can consider that direct user interaction phase completed.\n if (get().userActionStatus === 'pending') {\n statusUpdates.userActionStatus = 'idle';\n statusesChanged = true;\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[setCartData] Transitioned userActionStatus from 'pending' to 'idle'.`\n );\n }\n\n // If the cart was awaiting an update from a syncCartGifts operation, it has now arrived and been processed.\n if (get().cartSyncStatus === 'awaiting_cart_update') {\n statusUpdates.cartSyncStatus = 'idle';\n statusesChanged = true;\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[setCartData] Transitioned cartSyncStatus from 'awaiting_cart_update' to 'idle'.`\n );\n } else {\n // If cartSyncStatus was not 'awaiting_cart_update', no transition needed for it here.\n // The syncCartGifts useEffect in SmartCartContext will evaluate if a new sync is needed\n // now that userActionStatus might be 'idle' and cartData is updated.\n }\n\n if (statusesChanged) {\n set(statusUpdates);\n }\n },\n\n setSubmitFunctions: (addItemsImpl, removeItemsImpl) => {\n set({ _addItemsImpl: addItemsImpl, _removeItemsImpl: removeItemsImpl });\n },\n\n syncCartGifts: async () => {\n rebuyDebugLog.groupCollapsed(\n DebugKey.SC_TPB_STORE,\n '[syncCartGifts] Execution Started. Current cartSyncStatus:',\n get().cartSyncStatus\n );\n\n const state = get();\n\n if (state.cartSyncStatus === 'syncing') {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[syncCartGifts] Already syncing, exiting early');\n rebuyDebugLog.groupEnd();\n\n return;\n }\n\n const { _addItemsImpl, _removeItemsImpl } = state;\n\n if (!_addItemsImpl || !_removeItemsImpl) {\n rebuyDebugLog.error(DebugKey.SC_TPB_STORE, '[syncCartGifts] Submit functions not set. Cannot sync gifts.');\n rebuyDebugLog.groupEnd();\n\n return;\n }\n\n if (\n !state.isCartReady ||\n state.productFetchStatus !== 'success' ||\n !state.activeBarConfig ||\n state.isManuallyDisabled ||\n !state.cartData\n ) {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[syncCartGifts] Required conditions not met:', {\n hasActiveBarConfig: !!state.activeBarConfig,\n hasCartData: !!state.cartData,\n isCartReady: state.isCartReady,\n isManuallyDisabled: state.isManuallyDisabled,\n productFetchStatus: state.productFetchStatus,\n });\n rebuyDebugLog.groupEnd();\n\n return;\n }\n\n const itemsToAddPayload: { attributes: StorefrontAttribute[]; merchandiseId: string; quantity: number }[] = [];\n const lineIdsToRemove: string[] = [];\n\n const actualCartLinesForSync = state.cartData.lines ? flattenConnection(state.cartData.lines) : [];\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[syncCartGifts] Cart lines count:', actualCartLinesForSync.length);\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n '[syncCartGifts] Using giftStates:',\n JSON.parse(JSON.stringify(Array.from(state.giftStates.entries())))\n );\n\n state.activeBarConfig.tiers.forEach((tier) => {\n if (tier.type !== TieredProgressBarTierType.PRODUCT || !tier.products?.[0]) return;\n const giftState = state.giftStates.get(tier.id);\n\n if (!giftState) return;\n\n const { availableChoices, isDeclined, isInCart, isReached, tierId } = giftState;\n const cartLineForThisTier = actualCartLinesForSync.find((line) =>\n line.attributes?.some((attr) => attr.key === '_tier' && attr.value === tierId)\n );\n\n if (isReached && availableChoices.length === 1 && !isDeclined && !isInCart) {\n itemsToAddPayload.push({\n attributes: [\n { key: '_source', value: 'Rebuy' },\n { key: '_attribution', value: RebuyLineItemAttribution.TIERED_PROGRESS_BAR },\n { key: '_tier', value: tierId },\n ],\n merchandiseId: availableChoices[0].id,\n quantity: 1,\n });\n }\n\n if (cartLineForThisTier) {\n let shouldRemove = false;\n\n if (!isReached) shouldRemove = true;\n else if (availableChoices.length === 0) shouldRemove = true;\n else if (!availableChoices.some((v) => v.id === cartLineForThisTier.merchandise.id))\n shouldRemove = true;\n\n if (shouldRemove && !lineIdsToRemove.includes(cartLineForThisTier.id)) {\n lineIdsToRemove.push(cartLineForThisTier.id);\n }\n }\n });\n\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[syncCartGifts] Calculated actions:', {\n itemsToAddPayload,\n lineIdsToRemove,\n });\n\n if (itemsToAddPayload.length === 0 && lineIdsToRemove.length === 0) {\n const statusUpdates: Partial<TieredProgressBarStoreState> = {};\n let changed = false;\n\n if (get().cartSyncStatus !== 'idle') {\n statusUpdates.cartSyncStatus = 'idle';\n changed = true;\n }\n\n if (get().userActionStatus === 'pending') {\n statusUpdates.userActionStatus = 'idle';\n changed = true;\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n \"[syncCartGifts] No Shopify actions needed. UserActionStatus was 'pending', resetting to 'idle'.\"\n );\n }\n\n if (changed) {\n set(statusUpdates);\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n '[syncCartGifts] No Shopify actions needed by sync. Applied status updates:',\n statusUpdates\n );\n } else {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n '[syncCartGifts] No Shopify actions needed by sync. Statuses were already appropriate.'\n );\n }\n rebuyDebugLog.groupEnd();\n\n return;\n }\n\n set({ cartSyncError: null, cartSyncStatus: 'syncing' });\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n \"[syncCartGifts] Set cartSyncStatus to 'syncing'. Current userActionStatus:\",\n get().userActionStatus\n );\n\n try {\n if (lineIdsToRemove.length > 0) {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[syncCartGifts] Removing lines:', lineIdsToRemove);\n await _removeItemsImpl(lineIdsToRemove);\n }\n\n if (itemsToAddPayload.length > 0) {\n if (lineIdsToRemove.length > 0) {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[syncCartGifts] Waiting 300ms before adding items');\n await new Promise((res) => setTimeout(res, 300));\n }\n\n const itemsForAddImpl = itemsToAddPayload.map((item) => ({\n ...item,\n attributes: item.attributes.map((attr) => ({ key: attr.key, value: attr.value || '' })),\n }));\n\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[syncCartGifts] Adding items:', itemsForAddImpl);\n await _addItemsImpl(itemsForAddImpl as HRCartLineInput[]);\n }\n\n set({ cartSyncStatus: 'awaiting_cart_update' });\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n \"[syncCartGifts] Sync successful (dispatched actions). Set cartSyncStatus to 'awaiting_cart_update'. userActionStatus remains:\",\n get().userActionStatus\n );\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Failed to sync gifts.';\n\n if (get().userActionStatus === 'pending') {\n set({\n cartSyncError: message,\n cartSyncStatus: 'error',\n lastErrorTimestamp: Date.now(),\n userActionStatus: 'error',\n });\n } else {\n set({\n cartSyncError: message,\n cartSyncStatus: 'error',\n lastErrorTimestamp: Date.now(),\n });\n }\n rebuyDebugLog.error(DebugKey.SC_TPB_STORE, '[syncCartGifts] Sync error:', message);\n }\n\n rebuyDebugLog.groupEnd();\n },\n}));\n\nexport type SelectedTieredProgressBarStore = Pick<\n TieredProgressBarStoreState,\n | 'activeBarConfig'\n | 'currentSubtotal'\n | 'giftStates'\n | 'isCartReady'\n | 'productFetchStatus'\n | 'cartSyncStatus'\n | 'userActionStatus'\n | 'productFetchError'\n | 'cartSyncError'\n | 'userActionError'\n | 'isManuallyDisabled'\n | 'hasFreeShippingOnSubscription'\n | 'declinedGiftMap'\n | 'initializationStatus'\n | '_lastFetchedBarId'\n | 'fetchedProductMap'\n>;\n", "// ~/smart-cart/components/TieredProgressBar/progressBarUtils.tsx\n\nimport { flattenConnection } from '@shopify/hydrogen';\nimport type { CartLine } from '@shopify/hydrogen/storefront-api-types';\nimport type React from 'react';\nimport { DebugKey } from '~/constants/debug';\nimport { CheckIcon, DiscountIcon, GiftIcon, ShippingIcon } from '~/smart-cart/components/TieredProgressBar/Icons';\nimport {\n type TieredProgressBarFetchedProductData as FetchedProductData,\n type TieredProgressBar,\n type TieredProgressBarCachedGiftData,\n type TieredProgressBarExcludedProduct,\n type TieredProgressBarTier,\n type TieredProgressBarTierProduct,\n TieredProgressBarTierType,\n type TieredProgressBarVariantNode,\n} from '~/smart-cart/components/TieredProgressBar/types';\nimport { CartExclusionProductTag, SessionStorageKey } from '~/smart-cart/constants';\nimport type { StorefrontCartData } from '~/smart-cart/types/rebuy-storefront-cart';\nimport { isSubscriptionItem, isTieredProgressBarGiftItem } from '~/smart-cart/utils/cartItemUtils';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport { formatMoney } from '~/smart-cart/utils/moneyUtils';\nimport { safeJsonParse } from '~/smart-cart/utils/safeJsonParse';\n\n// Type for the map itself (use FetchedProductData alias)\ntype FetchedProductMap = Map<number, FetchedProductData>;\n\n/**\n * Helper to get numeric ID from a Shopify GID string.\n * e.g., \"gid://shopify/Product/12345\" -> 12345\n *\n * @param {string} gid The Shopify GID string.\n *\n * @returns {number} The numeric ID.\n */\nexport const getNumericIdFromGid = (gid: string): number => {\n return parseInt(gid.split('/').pop() ?? '0', 10);\n};\n\n/**\n * Helper to generate a unique key for storing declined gift states.\n * Uses a combination of tier ID and legacy product ID.\n *\n * @param {string} tierId The ID of the tier.\n * @param {number|string} legacyProductId The legacy numeric ID of the product associated with the tier.\n *\n * @returns {string} A string key for the declined gift.\n */\nexport const getDeclineKey = (tierId: string, legacyProductId: number | string): string => {\n return `${tierId}:${legacyProductId}`;\n};\n\n/**\n * Generates the replacement string for discount tier feedback text (e.g., \"$10 Off\" or \"15%\").\n *\n * @param {TieredProgressBarTier} tier The discount tier configuration.\n *\n * @returns {string} The formatted discount string.\n */\nconst getDiscountTierTextReplacementString = (tier: TieredProgressBarTier): string => {\n if (!tier || tier.type !== TieredProgressBarTierType.DISCOUNT) return '';\n\n return tier.discount_type === 'fixedAmount'\n ? formatMoney(Number(tier.discount_amount_from_total ?? 0))\n : `${tier.discount_amount_from_total ?? 0}%`;\n};\n\n/**\n * Gets the display label for a tier marker.\n *\n * @param {TieredProgressBarTier} tier The tier configuration.\n * @param {FetchedProductMap} fetchedProductMap Optional: A map of fetched product data, used to look up product titles for product tiers.\n *\n * @returns {string} The label string for the tier.\n */\nexport const getTierLabel = (tier: TieredProgressBarTier, fetchedProductMap?: FetchedProductMap): string => {\n if ((tier.custom_tier_label || tier.type === TieredProgressBarTierType.DECORATIVE) && tier.custom_tier_label_text) {\n return tier.custom_tier_label_text;\n }\n\n switch (tier.type) {\n case TieredProgressBarTierType.SHIPPING:\n return 'Free Shipping'; // TODO: Wire up to language settings\n case TieredProgressBarTierType.DISCOUNT:\n return tier.discount_type === 'fixedAmount'\n ? `${formatMoney(Number(tier.discount_amount_from_total ?? 0))} Off`\n : `${tier.discount_amount_from_total ?? 0}% Discount`;\n case TieredProgressBarTierType.DECORATIVE:\n return tier.custom_tier_label_text ?? 'Decorative';\n case TieredProgressBarTierType.PRODUCT:\n if (fetchedProductMap && tier.products?.[0]?.product_id) {\n const productData = fetchedProductMap.get(tier.products[0].product_id);\n\n if (productData?.title) {\n return productData.title;\n }\n }\n\n return 'Free Gift';\n default:\n return 'Tier';\n }\n};\n\n/**\n * Generates the main feedback text displayed below the progress bar.\n * This text guides the user on how much more they need to spend for the next tier or confirms rewards.\n * It respects boolean flags on the tier settings (e.g., `product_amount_reached_label`) to determine\n * if a specific label text should be used.\n *\n * @param {TieredProgressBar|null} barConfig The active progress bar configuration.\n * @param {TieredProgressBarTier|null} currentTier The next tier the user is progressing towards, or null if all tiers are reached.\n * @param {TieredProgressBarTier|null} lastReachedTier The most recent tier the user has successfully reached, or null if no tiers are reached.\n * @param {number} amountToNextTier The monetary amount remaining to reach the `currentTier`.\n * @param {FetchedProductMap} fetchedProductMap A map of fetched product data, used to look up product titles for product tiers.\n *\n * @returns {string} The formatted feedback string, or an empty string if no label should be shown.\n */\nexport const getTierFeedbackText = (\n barConfig: TieredProgressBar | null,\n currentTier: TieredProgressBarTier | null,\n lastReachedTier: TieredProgressBarTier | null,\n amountToNextTier: number,\n fetchedProductMap: FetchedProductMap\n): string => {\n if (!barConfig) return '';\n\n const language = barConfig.language;\n const validAmountToNextTier = typeof amountToNextTier === 'number' ? amountToNextTier : 0;\n const remainingAmountReplacement = formatMoney(validAmountToNextTier);\n const remainingAmountRegex = /\\{\\{remaining_amount\\}\\}/g;\n const productRegex = /\\{\\{product_title\\}\\}/g;\n const discountRegex = /\\{\\{discount_amount\\}\\}/g;\n\n // Case 1: All tiers reached (lastReachedTier is the one to display info for)\n if (!currentTier && lastReachedTier) {\n const finalTier = lastReachedTier;\n let text = '';\n\n switch (finalTier.type) {\n case TieredProgressBarTierType.PRODUCT:\n if (finalTier.product_amount_reached_label && finalTier.product_amount_reached_label_text) {\n const tierProductInfo: TieredProgressBarTierProduct | undefined = finalTier.products?.[0];\n const productTitle = tierProductInfo?.product_id\n ? (fetchedProductMap.get(tierProductInfo.product_id)?.title ?? 'your free gift')\n : 'your free gift';\n text = finalTier.product_amount_reached_label_text\n .replace(remainingAmountRegex, remainingAmountReplacement)\n .replace(productRegex, productTitle);\n }\n break;\n case TieredProgressBarTierType.SHIPPING:\n // Shipping tiers don't have explicit boolean flags in the provided Tier type for reached/remaining.\n if (language?.free_shipping_reached) {\n text = language.free_shipping_reached.replace(remainingAmountRegex, remainingAmountReplacement);\n }\n break;\n case TieredProgressBarTierType.DISCOUNT:\n if (finalTier.discount_amount_reached_label && finalTier.discount_amount_reached_label_text) {\n const discountTextReplacement = getDiscountTierTextReplacementString(finalTier);\n text = finalTier.discount_amount_reached_label_text\n .replace(remainingAmountRegex, remainingAmountReplacement)\n .replace(discountRegex, discountTextReplacement);\n }\n break;\n case TieredProgressBarTierType.DECORATIVE:\n if (finalTier.decorative_amount_reached_label && finalTier.decorative_amount_reached_label_text) {\n text = finalTier.decorative_amount_reached_label_text.replace(\n remainingAmountRegex,\n remainingAmountReplacement\n );\n }\n break;\n default:\n break;\n }\n\n return text;\n }\n\n // Case 2: Progressing towards the 'currentTier'\n if (currentTier) {\n let text = '';\n switch (currentTier.type) {\n case TieredProgressBarTierType.PRODUCT:\n if (currentTier.product_amount_remaining_label && currentTier.product_amount_remaining_label_text) {\n const tierProductInfo: TieredProgressBarTierProduct | undefined = currentTier.products?.[0];\n const productTitle = tierProductInfo?.product_id\n ? (fetchedProductMap.get(tierProductInfo.product_id)?.title ?? 'a free gift')\n : 'a free gift';\n text = currentTier.product_amount_remaining_label_text\n .replace(remainingAmountRegex, remainingAmountReplacement)\n .replace(productRegex, productTitle);\n }\n break;\n case TieredProgressBarTierType.SHIPPING:\n // Shipping tiers don't have explicit boolean flags for reached/remaining.\n if (language?.free_shipping_remaining) {\n text = language.free_shipping_remaining.replace(remainingAmountRegex, remainingAmountReplacement);\n }\n break;\n case TieredProgressBarTierType.DISCOUNT:\n if (currentTier.discount_amount_remaining_label && currentTier.discount_amount_remaining_label_text) {\n const discountTextReplacement = getDiscountTierTextReplacementString(currentTier);\n text = currentTier.discount_amount_remaining_label_text\n .replace(remainingAmountRegex, remainingAmountReplacement)\n .replace(discountRegex, discountTextReplacement);\n }\n break;\n case TieredProgressBarTierType.DECORATIVE:\n if (\n currentTier.decorative_amount_remaining_label &&\n currentTier.decorative_amount_remaining_label_text\n ) {\n text = currentTier.decorative_amount_remaining_label_text.replace(\n remainingAmountRegex,\n remainingAmountReplacement\n );\n }\n break;\n default:\n break;\n }\n\n return text;\n }\n\n // Fallback case: No current tier, no last reached tier (e.g., bar with no tiers, or initial state)\n return '';\n};\n\n/**\n * Minimal image object type for tier icons.\n * Represents an image with an optional alt text and type.\n *\n * @property {string} alt - The alternative text for the image.\n * @property {string} src - The source URL of the image.\n * @property {string} type - The type of the icon (always 'image').\n */\nexport type TierIconImage = { alt: string; src: string; type: 'image' };\n\n/**\n * Determines the icon component to display for a tier marker.\n *\n * @param {TieredProgressBarTier} tier The tier configuration.\n * @param {boolean} isReached Whether the tier has been reached.\n * @param {FetchedProductMap} fetchedProductMap A map of fetched product data, used for product tier image checks.\n *\n * @returns {TierIconReturnType} A React element or image object representing the icon.\n */\nexport type TierIconReturnType = React.ReactElement | TierIconImage;\n\nexport const getTierIconComponent = (\n tier: TieredProgressBarTier,\n isReached: boolean,\n fetchedProductMap: FetchedProductMap\n): TierIconReturnType => {\n if (isReached) {\n return <CheckIcon />;\n }\n\n switch (tier.type) {\n case TieredProgressBarTierType.SHIPPING:\n return <ShippingIcon />;\n case TieredProgressBarTierType.DISCOUNT:\n return <DiscountIcon />;\n case TieredProgressBarTierType.PRODUCT: {\n const tierProductInfo: TieredProgressBarTierProduct | undefined = tier.products?.[0];\n const productData = tierProductInfo?.product_id\n ? fetchedProductMap.get(tierProductInfo.product_id)\n : undefined;\n const imageUrl = productData?.images?.edges?.[0]?.node?.url;\n\n if (tier.product_tier_image && imageUrl && productData) {\n return {\n alt: productData.title || 'Gift product',\n src: imageUrl,\n type: 'image',\n };\n }\n\n return <GiftIcon />;\n }\n case TieredProgressBarTierType.DECORATIVE:\n return <GiftIcon />;\n default:\n console.warn(`Unknown tier type for icon: ${tier.type}`);\n\n return <GiftIcon />;\n }\n};\n\n/**\n * Gets the minimum spend required to reach a specific tier.\n *\n * @param {TieredProgressBarTier} tier The tier configuration.\n *\n * @returns {number} The minimum amount, or Infinity if tier is invalid.\n */\nexport const getTierMinimum = (tier: TieredProgressBarTier): number => {\n if (!tier) return Infinity;\n\n return tier.minimum ?? Infinity;\n};\n\n/**\n * Gets a user-friendly display title for a selected gift variant.\n *\n * @param {TieredProgressBarVariantNode|null} variant The variant node.\n *\n * @returns {string} The display title string.\n */\nexport const getFreeVariantTitle = (variant: TieredProgressBarVariantNode | null): string => {\n if (!variant) return '';\n\n if (variant.title && variant.title.toLowerCase() !== 'default title') {\n return variant.title;\n }\n\n const meaningfulOptions = variant.selectedOptions?.filter((opt) => opt.value.toLowerCase() !== 'default title');\n\n if (meaningfulOptions && meaningfulOptions.length > 0) {\n return meaningfulOptions.map((opt) => opt.value).join(' / ');\n }\n\n return '';\n};\n\n/**\n * Determines if the main gift area container should be rendered.\n * Renders if there's an active bar configuration and items to display within the gift area.\n *\n * @param {TieredProgressBar|null} barConfig The active progress bar configuration.\n * @param {boolean} hasRenderableItems A boolean indicating if there are any gift items to be rendered.\n *\n * @returns {boolean} True if the gift area should be rendered, false otherwise.\n */\nexport const shouldRenderGiftArea = (barConfig: TieredProgressBar | null, hasRenderableItems: boolean): boolean => {\n if (!barConfig || !hasRenderableItems) return false;\n\n return true;\n};\n\n/**\n * Determines if the title for the gift area should be shown.\n *\n * @param {TieredProgressBar|null} barConfig The active progress bar configuration.\n *\n * @returns {boolean} True if the gift area title should be rendered, false otherwise.\n */\nexport const shouldRenderGiftAreaTitle = (barConfig: TieredProgressBar | null): boolean => {\n return !!barConfig?.language?.gift_area_title?.trim();\n};\n\n/**\n * Gets the title text for the gift area.\n *\n * @param {TieredProgressBar|null} barConfig The active progress bar configuration.\n *\n * @returns {string} The gift area title string, or a default if not configured.\n */\nexport const getGiftAreaTitle = (barConfig: TieredProgressBar | null): string => {\n return barConfig?.language?.gift_area_title ?? 'FREE GIFTS';\n};\n\n/**\n * Calculates the current subtotal relevant for the progress bar.\n * It starts with zero and adds the cost of each included cart item.\n *\n * Excluded items are:\n * 1. Tiered Progress Bar gift items.\n * 2. Items tagged with the specific exclusion tag.\n * 3. If `bar.discounted_by === 'functions'`, items listed in `bar.excluded_products`.\n *\n * @param {StorefrontCartData|null} cart The current storefront cart data.\n * @param {TieredProgressBar|null} bar The active progress bar configuration.\n *\n * @returns {number} The calculated subtotal for the progress bar.\n */\nexport const calculateCurrentProgressBarSubtotal = (\n cart: StorefrontCartData | null,\n bar: TieredProgressBar | null\n): number => {\n const logCollector: string[] = [];\n\n if (!cart || !bar || !cart.cost || !cart.lines) {\n logCollector.push(\n '[TPB SubtotalCalc] Aborted: Essential data missing (cart, bar config, cart cost, or cart lines object).'\n );\n logCollector.push('[TPB SubtotalCalc] Resulting Subtotal: 0');\n rebuyDebugLog.log(DebugKey.SC_TPB_SUBTOTAL_CALC, logCollector.join('\\n'));\n\n return 0;\n }\n let actualCartLineNodes: Readonly<CartLine>[] = [];\n\n try {\n actualCartLineNodes = flattenConnection(cart.lines) as Readonly<CartLine>[];\n } catch (error) {\n logCollector.push(\n '[TPB SubtotalCalc] Aborted: Failed to flatten cart.lines connection.',\n `Error: ${error instanceof Error ? error.message : String(error)}`\n );\n logCollector.push('[TPB SubtotalCalc] Resulting Subtotal: 0');\n rebuyDebugLog.log(DebugKey.SC_TPB_SUBTOTAL_CALC, logCollector.join('\\n'));\n\n return 0;\n }\n\n if (!actualCartLineNodes.length) {\n logCollector.push('[TPB SubtotalCalc] No cart lines found after flattening connection.');\n }\n\n let progressiveSubtotal = 0;\n\n const isFunctionsMode = bar.discounted_by === 'functions';\n const barExcludedProductsConfig: TieredProgressBarExcludedProduct[] = bar.excluded_products ?? [];\n\n const lineItemLogEntries: LineItemLogEntry[] = [];\n const includedItemsForExpression: string[] = [];\n\n actualCartLineNodes.forEach((lineNode, index: number) => {\n const line = lineNode as CartLine;\n const lineIdentifier = line.merchandise?.product?.title || line.merchandise?.title || `Line ${line.id}`;\n const lineAmount = parseFloat(line.cost.totalAmount.amount);\n const lineAmountStr = isNaN(lineAmount) ? `\"${line.cost.totalAmount.amount}\"` : lineAmount.toFixed(2);\n\n const entry: Partial<LineItemLogEntry> = {\n '#': index + 1,\n Item: lineIdentifier,\n 'Original Amount': lineAmountStr,\n };\n\n if (isNaN(lineAmount)) {\n entry.Status = 'SKIPPED';\n entry.Contribution = '0.00';\n entry['Reasons (if Excluded/Skipped)'] = 'Invalid line item amount';\n lineItemLogEntries.push(entry as LineItemLogEntry);\n\n return;\n }\n\n let isExcluded = false;\n const currentLineExclusionReasons: string[] = [];\n\n if (isTieredProgressBarGiftItem(line)) {\n isExcluded = true;\n currentLineExclusionReasons.push('TPB Gift');\n }\n\n const tags = line.merchandise?.product?.tags?.map((t: string) => t.toLowerCase()) ?? [];\n const exclusionTagToCheck = CartExclusionProductTag.EXCLUDE_FROM_PROGRESS_BAR_SUBTOTAL.toLowerCase();\n\n if (tags.some((tag: string) => tag === exclusionTagToCheck)) {\n isExcluded = true;\n currentLineExclusionReasons.push(`Tag: ${exclusionTagToCheck}`);\n }\n\n if (isFunctionsMode && barExcludedProductsConfig.length > 0) {\n const lineProductIdNumeric = line.merchandise?.product?.id\n ? getNumericIdFromGid(line.merchandise.product.id)\n : null;\n const lineVariantIdNumeric = line.merchandise?.id ? getNumericIdFromGid(line.merchandise.id) : null;\n\n if (lineProductIdNumeric !== null) {\n const isExcludedByBarRule = barExcludedProductsConfig.some((excludedProductSetting) => {\n if (excludedProductSetting.product_id === lineProductIdNumeric) {\n const variantsToExclude = excludedProductSetting.variant_ids;\n\n if (!Array.isArray(variantsToExclude) || variantsToExclude.length === 0) return true;\n\n if (lineVariantIdNumeric !== null && variantsToExclude.includes(lineVariantIdNumeric))\n return true;\n }\n\n return false;\n });\n\n if (isExcludedByBarRule) {\n isExcluded = true;\n currentLineExclusionReasons.push('Bar Setting');\n }\n }\n }\n\n if (isExcluded) {\n entry.Status = 'EXCLUDED';\n entry.Contribution = '0.00';\n entry['Reasons (if Excluded/Skipped)'] = currentLineExclusionReasons.join(', ');\n } else {\n progressiveSubtotal += lineAmount; // ONLY ADD IF NOT EXCLUDED\n entry.Status = 'INCLUDED';\n entry.Contribution = lineAmount.toFixed(2);\n entry['Reasons (if Excluded/Skipped)'] = '-';\n includedItemsForExpression.push(`(\"${lineIdentifier}\" - ${lineAmount.toFixed(2)})`);\n }\n lineItemLogEntries.push(entry as LineItemLogEntry);\n });\n\n const finalSubtotal = Math.max(0, progressiveSubtotal);\n logCollector.push(`[TPB SubtotalCalc] Tiered Progress Bar Subtotal Calculation Summary:`);\n\n let contributingItemsExpression = 'No items contributed to subtotal';\n\n if (includedItemsForExpression.length > 0) {\n contributingItemsExpression = includedItemsForExpression.join(' + ');\n } else if (actualCartLineNodes.length > 0) {\n contributingItemsExpression = 'All items were excluded, skipped, or had zero value';\n }\n\n logCollector.push(` Contribution Expression: ${contributingItemsExpression} = ${finalSubtotal.toFixed(2)}`);\n logCollector.push(` Final Tiered Progress Bar Subtotal: ${finalSubtotal.toFixed(2)}`);\n\n logCollector.push(`\\n Relevant Bar Configuration:`);\n logCollector.push(` - Discounted By: ${bar.discounted_by} (Functions Mode: ${isFunctionsMode})`);\n logCollector.push(` - Bar Excluded Products Rules: ${barExcludedProductsConfig.length}`);\n\n logCollector.push(`\\n Line Item Breakdown:`);\n\n const tableLines = formatLogEntriesAsTextTable(lineItemLogEntries);\n logCollector.push(...tableLines);\n rebuyDebugLog.log(DebugKey.SC_TPB_SUBTOTAL_CALC, logCollector.join('\\n'));\n\n return finalSubtotal;\n};\n\n/**\n * Interface for line item log entries used in detailed debugging output.\n */\ntype LineItemLogEntry = {\n '#': number;\n Contribution: string;\n Item: string;\n 'Original Amount': string;\n 'Reasons (if Excluded/Skipped)': string;\n Status: 'INCLUDED' | 'EXCLUDED' | 'SKIPPED';\n};\n\n/**\n * Helper function to format an array of objects as a text table for debugging output.\n *\n * @param {LineItemLogEntry[]} data The array of line item log entries to format.\n *\n * @returns {string[]} An array of formatted text lines representing the table.\n */\nconst formatLogEntriesAsTextTable = (data: LineItemLogEntry[]): string[] => {\n if (data.length === 0) return [' No line items processed.'];\n\n const headers: Record<keyof LineItemLogEntry, string> = {\n '#': '#',\n Contribution: 'Contribution',\n Item: 'Item',\n 'Original Amount': 'Original Amount',\n 'Reasons (if Excluded/Skipped)': 'Reasons (if Excluded/Skipped)',\n Status: 'Status',\n };\n\n const keys = Object.keys(headers) as (keyof LineItemLogEntry)[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const columnWidths: Record<keyof LineItemLogEntry, number> = {} as any;\n\n keys.forEach((key) => {\n columnWidths[key] = headers[key].length;\n });\n\n data.forEach((row) => {\n keys.forEach((key) => {\n const valueStr = String(row[key]);\n columnWidths[key] = Math.max(columnWidths[key], valueStr.length);\n });\n });\n\n const pad = (str: string, width: number) => String(str).padEnd(width);\n\n const headerRowParts = keys.map((key) => pad(headers[key], columnWidths[key]));\n const headerRow = ` | ${headerRowParts.join(' | ')} |`;\n\n const separatorRowParts = keys.map((key) => '-'.repeat(columnWidths[key]));\n const separatorRow = ` +-${separatorRowParts.join('-+-')}-+`;\n\n const tableOutput: string[] = [headerRow, separatorRow];\n\n data.forEach((row) => {\n const rowParts = keys.map((key) => pad(String(row[key]), columnWidths[key]));\n tableOutput.push(` | ${rowParts.join(' | ')} |`);\n });\n\n return tableOutput;\n};\n\n/**\n * Checks if the cart qualifies for free shipping due to subscription items,\n * based on the progress bar's settings.\n *\n * @param {StorefrontCartData|null} cart The current storefront cart data.\n * @param {TieredProgressBar|null} bar The active progress bar configuration.\n *\n * @returns {boolean} True if free shipping on subscription is active, false otherwise.\n */\nexport const checkHasFreeShippingOnSubscription = (\n cart: StorefrontCartData | null,\n bar: TieredProgressBar | null\n): boolean => {\n if (!bar?.free_shipping_on_subscription || !cart?.lines) {\n return false;\n }\n\n const hasShippingTier = bar.tiers.some((tier) => tier.type === TieredProgressBarTierType.SHIPPING);\n\n if (!hasShippingTier) {\n return false;\n }\n\n let actualCartLineNodes: Readonly<CartLine>[] = [];\n\n try {\n actualCartLineNodes = flattenConnection(cart.lines) as Readonly<CartLine>[];\n } catch (error) {\n rebuyDebugLog.warn('checkHasFreeShippingOnSubscription: Failed to flatten cart.lines connection.', error);\n }\n\n return actualCartLineNodes.some((lineNode) => {\n const line = lineNode as CartLine;\n\n return !isTieredProgressBarGiftItem(line) && isSubscriptionItem(line);\n });\n};\n\n/**\n * Checks if a specific tier has been reached based on the current subtotal\n * and free shipping on subscription status.\n *\n * @param {TieredProgressBarTier} tier The tier configuration.\n * @param {number} currentSubtotal The current progress bar subtotal.\n * @param {boolean} hasFreeShippingOnSubscription Whether free shipping on subscription is active.\n *\n * @returns {boolean} True if the tier is reached, false otherwise.\n */\nexport const checkIsTierReached = (\n tier: TieredProgressBarTier,\n currentSubtotal: number,\n hasFreeShippingOnSubscription: boolean\n): boolean => {\n if (!tier) return false;\n\n const minimum = getTierMinimum(tier);\n\n if (tier.type === TieredProgressBarTierType.SHIPPING && hasFreeShippingOnSubscription) return true;\n\n return currentSubtotal >= minimum;\n};\n\n/**\n * Updates the session storage cache for declined gifts.\n * This cache helps persist user choices across page loads within the same session.\n *\n * @param {Record<string, boolean>} newDeclinedMap A record object where keys are decline keys (from `getDeclineKey`)\n * and values are booleans indicating if the gift is declined.\n *\n * @returns {void}\n */\nexport const updateDeclinedCache = (newDeclinedMap: Record<string, boolean>): void => {\n try {\n const cachedDataString = sessionStorage.getItem(SessionStorageKey.TIERED_PROGRESS_BAR_GIFT_DATA);\n const cachedData: TieredProgressBarCachedGiftData | null = safeJsonParse(cachedDataString);\n\n const newCache: TieredProgressBarCachedGiftData = {\n ...(cachedData ?? { products: [], timestamp: 0 }),\n declined: newDeclinedMap,\n timestamp: cachedData?.timestamp ?? Date.now(),\n };\n sessionStorage.setItem(SessionStorageKey.TIERED_PROGRESS_BAR_GIFT_DATA, JSON.stringify(newCache));\n } catch (error) {\n console.error('[progressBarUtils] Failed to update declined cache:', error);\n }\n};\n\n/**\n * Calculates the visual progress bar percentage based on legacy logic for visual alignment.\n * This logic often involves adjusting segment calculations (e.g., dividing by 2)\n * to better align the visual progress with tier markers.\n *\n * @param {TieredProgressBar|null} barConfig The active progress bar configuration.\n * @param {number} subtotal The current subtotal for progress calculation.\n * @param {boolean} hasFreeShippingOnSubscription Whether free shipping is achieved via subscription.\n *\n * @returns {number} The calculated visual percentage (0-100).\n */\nexport const calculateVisualProgressBarPercentage = (\n barConfig: TieredProgressBar | null,\n subtotal: number,\n hasFreeShippingOnSubscription: boolean\n): number => {\n if (!barConfig || !barConfig.tiers || barConfig.tiers.length === 0) {\n return 0;\n }\n\n const allTiers = barConfig.tiers;\n\n if (subtotal <= 0) {\n return 0;\n }\n\n // Check if the very last tier in the definition is met.\n // `checkIsTierReached` handles FSoS for shipping tiers.\n const lastOverallTier = allTiers[allTiers.length - 1];\n\n if (checkIsTierReached(lastOverallTier, subtotal, hasFreeShippingOnSubscription)) {\n // If the last tier is $0 minimum, it's reached if subtotal > 0.\n // If its minimum is > $0, checkIsTierReached already confirms subtotal meets it.\n if (getTierMinimum(lastOverallTier) <= 0 && subtotal > 0) return 100;\n\n if (getTierMinimum(lastOverallTier) > 0) return 100;\n }\n\n let percentage = 0;\n const firstTier = allTiers[0];\n const firstTierMinimum = getTierMinimum(firstTier);\n\n // Logic for single tier (matches legacy specific handling for 1 tier)\n if (allTiers.length === 1) {\n if (firstTierMinimum > 0) {\n percentage = (subtotal / firstTierMinimum) * 100;\n } else {\n // Tier minimum is $0 or less\n percentage = subtotal > 0 ? 100 : 0; // Reached if any subtotal\n }\n }\n // Logic for multiple tiers (incorporates the \"dividing by 2\" visual adjustment)\n else {\n const tierPercentageSize = 100 / allTiers.length;\n const completedTiers = allTiers.filter((tier) =>\n checkIsTierReached(tier, subtotal, hasFreeShippingOnSubscription)\n );\n\n if (completedTiers.length === 0) {\n if (firstTierMinimum > 0) {\n percentage = (subtotal / firstTierMinimum) * (tierPercentageSize / 2);\n } else {\n // First tier is $0, but not considered \"completed\" if subtotal is $0.\n // If subtotal > 0 and firstTierMinimum is $0, completedTiers would not be 0.\n percentage = 0;\n }\n } else {\n // At least one tier completed\n percentage = completedTiers.length * tierPercentageSize - tierPercentageSize / 2;\n\n const lastCompletedTier = completedTiers[completedTiers.length - 1];\n const lastCompletedTierMinimum = getTierMinimum(lastCompletedTier);\n\n // Find the next tier that is not yet completed\n let nextIncompleteTier: TieredProgressBarTier | undefined = undefined;\n const lastCompletedTierIndex = allTiers.findIndex((t) => t.id === lastCompletedTier.id);\n\n if (lastCompletedTierIndex !== -1 && lastCompletedTierIndex < allTiers.length - 1) {\n for (let i = lastCompletedTierIndex + 1; i < allTiers.length; i++) {\n if (!checkIsTierReached(allTiers[i], subtotal, hasFreeShippingOnSubscription)) {\n nextIncompleteTier = allTiers[i];\n break;\n }\n }\n }\n\n if (nextIncompleteTier) {\n const spendSinceLastTier = subtotal - lastCompletedTierMinimum;\n // Monetary distance of the current progress segment (from last completed to next incomplete)\n const segmentMonetaryLength = getTierMinimum(nextIncompleteTier) - lastCompletedTierMinimum;\n\n if (segmentMonetaryLength > 0) {\n percentage += (spendSinceLastTier / segmentMonetaryLength) * tierPercentageSize;\n } else if (spendSinceLastTier > 0 && segmentMonetaryLength <= 0) {\n // Edge case: next tier min is <= last completed min. If spent more, count full segment.\n percentage += tierPercentageSize;\n }\n }\n // If no nextIncompleteTier, all tiers are complete. The top 100% check should handle this.\n }\n }\n\n return Math.min(Math.max(0, percentage), 100);\n};\n", "// ~/smart-cart/components/TieredProgressBar/Icons.tsx\n\n// eslint-disable-next-line no-restricted-imports\n\n// TODO: Use an icon library, maybe?\n\nexport const CheckIcon = () => (\n <svg fill=\"none\" height=\"8\" viewBox=\"0 0 9 8\" width=\"9\" xmlns=\"http://www.w3.org/2000/svg\">\n <path\n d=\"M2.82415 6.15237L0.726419 4.05464L0.012085 4.76395L2.82415 7.57601L8.86078 1.53938L8.15147 0.830078L2.82415 6.15237Z\"\n fill=\"currentColor\"\n />\n </svg>\n);\n\nexport const ShippingIcon = () => (\n <svg\n fill=\"none\"\n height=\"16\"\n viewBox=\"0 0 21 16\"\n width=\"21\"\n xmlns=\"http://www.w3.org/2000/svg\" /* style={{ transform: 'scale(0.8)', transformOrigin: 'center' }} */\n >\n <path\n d=\"M17.6392 4.49332H14.9621V0.923828H2.46883C1.48722 0.923828 0.684082 1.72696 0.684082 2.70857V12.5247H2.46883C2.46883 14.006 3.66461 15.2018 5.14595 15.2018C6.62729 15.2018 7.82307 14.006 7.82307 12.5247H13.1773C13.1773 14.006 14.3731 15.2018 15.8544 15.2018C17.3358 15.2018 18.5315 14.006 18.5315 12.5247H20.3163V8.06281L17.6392 4.49332ZM17.193 5.83188L18.942 8.06281H14.9621V5.83188H17.193ZM5.14595 13.4171C4.65514 13.4171 4.25357 13.0155 4.25357 12.5247C4.25357 12.0339 4.65514 11.6323 5.14595 11.6323C5.63675 11.6323 6.03832 12.0339 6.03832 12.5247C6.03832 13.0155 5.63675 13.4171 5.14595 13.4171ZM7.12702 10.7399C6.63621 10.1956 5.94016 9.84756 5.14595 9.84756C4.35174 9.84756 3.65568 10.1956 3.16488 10.7399H2.46883V2.70857H13.1773V10.7399H7.12702ZM15.8544 13.4171C15.3636 13.4171 14.9621 13.0155 14.9621 12.5247C14.9621 12.0339 15.3636 11.6323 15.8544 11.6323C16.3452 11.6323 16.7468 12.0339 16.7468 12.5247C16.7468 13.0155 16.3452 13.4171 15.8544 13.4171Z\"\n fill=\"currentColor\"\n />\n </svg>\n);\n\nexport const DiscountIcon = () => (\n <svg\n fill=\"none\"\n height=\"24\"\n style={{ transform: 'scale(0.75)', transformOrigin: 'center' }}\n viewBox=\"0 0 24 24\"\n width=\"24\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n d=\"M21.408 11.4124L12.578 2.58244C12.208 2.21244 11.698 2.00244 11.168 2.00244H3.99805C2.89805 2.00244 1.99805 2.90244 1.99805 4.00244V11.1724C1.99805 11.7024 2.20805 12.2124 2.58805 12.5824L11.418 21.4124C12.198 22.1924 13.468 22.1924 14.248 21.4124L21.418 14.2424C22.198 13.4624 22.198 12.2024 21.408 11.4124ZM12.828 20.0024L3.99805 11.1724V4.00244H11.168L19.998 12.8324L12.828 20.0024Z\"\n fill=\"currentColor\"\n />\n <path\n d=\"M6.49805 8.00244C7.32647 8.00244 7.99805 7.33087 7.99805 6.50244C7.99805 5.67401 7.32647 5.00244 6.49805 5.00244C5.66962 5.00244 4.99805 5.67401 4.99805 6.50244C4.99805 7.33087 5.66962 8.00244 6.49805 8.00244Z\"\n fill=\"currentColor\"\n />\n </svg>\n);\n\nexport const GiftIcon = () => (\n <svg\n fill=\"none\"\n height=\"18\"\n style={{ transform: 'scale(0.9)', transformOrigin: 'center' }}\n viewBox=\"0 0 15 18\"\n width=\"15\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n d=\"M12.7808 3.71012H10.9961C10.9961 1.73797 9.39873 0.140625 7.42658 0.140625C5.45444 0.140625 3.85709 1.73797 3.85709 3.71012H2.07234C1.09073 3.71012 0.287598 4.51325 0.287598 5.49486V16.2033C0.287598 17.185 1.09073 17.9881 2.07234 17.9881H12.7808C13.7624 17.9881 14.5656 17.185 14.5656 16.2033V5.49486C14.5656 4.51325 13.7624 3.71012 12.7808 3.71012ZM7.42658 1.92537C8.40819 1.92537 9.21133 2.72851 9.21133 3.71012H5.64184C5.64184 2.72851 6.44497 1.92537 7.42658 1.92537ZM12.7808 16.2033H2.07234V5.49486H3.85709V7.27961C3.85709 7.77042 4.25866 8.17198 4.74946 8.17198C5.24027 8.17198 5.64184 7.77042 5.64184 7.27961V5.49486H9.21133V7.27961C9.21133 7.77042 9.6129 8.17198 10.1037 8.17198C10.5945 8.17198 10.9961 7.77042 10.9961 7.27961V5.49486H12.7808V16.2033Z\"\n fill=\"currentColor\"\n />\n </svg>\n);\n", "// ~/smart-cart/constants.ts\n\n/**\n * Rebuy-specific attribution of the item (ie. key: '_attribution', value: 'Rebuy Buy More Save More')\n */\nexport enum RebuyLineItemAttribution {\n BUY_MORE_SAVE_MORE = 'Rebuy Buy More Save More',\n SWITCH_TO_ONE_TIME = 'Rebuy Switch to One-Time',\n SWITCH_TO_SUBSCRIPTION = 'Rebuy Switch to Subscription',\n TIERED_PROGRESS_BAR = 'Rebuy Tiered Progress Bar',\n}\n\n/**\n * Line Item Attribute Keys (for attribution, tracking, safeguarding discounts, etc.)\n */\nexport enum LineItemAttributeKey {\n /**\n * Rebuy-specific attribution of the item\n */\n ATTRIBUTION = '_attribution',\n /**\n * Quantity before BMSM (not currently used - just an idea if we want to calculate more accurate RGR)\n */\n BMSM_QTY_BEFORE = '_bmsm_qty_before',\n /**\n * Hide quantity selector (ie. for Gift with Purchase items)\n */\n HIDE_QUANTITY_SELECTOR_GWP_ITEM = '_r_gwp_hide_qty',\n\n /**\n * Source of the item (ie. 'Rebuy')\n */\n SOURCE = '_source',\n}\n\nexport enum CartExclusionProductTag {\n /**\n * Exclude items with this tag from cart subtotal used to calculate final display price\n */\n EXCLUDE_FROM_CART_SUBTOTAL = 'smart-cart-subtotal-excluded',\n /**\n * Exclude items with this tag from progress bar subtotal used to calculate thresholds\n */\n EXCLUDE_FROM_PROGRESS_BAR_SUBTOTAL = 'smart-cart-shipping-excluded',\n /**\n * Hide bundle options in cart\n */\n HIDE_BUNDLE_OPTIONS_IN_CART = 'smart-cart-hide-bundle-options',\n /**\n * Hide cart items in the cart display\n */\n HIDE_FROM_CART_ITEMS = 'smart-cart-hidden',\n /**\n * Hide quantity selector in cart\n */\n HIDE_QUANTITY_SELECTOR_IN_CART = 'smart-cart-hide-qty',\n}\n\nexport enum SessionStorageKey {\n TIERED_PROGRESS_BAR_GIFT_DATA = '_r_progress_bar_gift_data',\n}\n\nexport const NO_IMAGE_SHOPIFY_PLACEHOLDER =\n '//cdn.shopify.com/s/files/1/0533/2089/files/placeholder-images-image_large.png?format=webp&v=1530129081';\n", "// ~/smart-cart/utils/moneyUtils.ts\n\n// TODO: REMOVE THIS AND USE npm-rebuy utils instead\nimport type { StorefrontMoney } from '~/smart-cart/types/rebuy-storefront-cart';\n\n/**\n * Formats a numeric amount as a currency string.\n * Uses Intl.NumberFormat for locale-aware formatting when a valid currencyCode is provided.\n * Falls back to simple symbol + fixed decimal formatting otherwise.\n *\n * @param {string|number|undefined|null} amount - The amount as a string or number. Can be null or undefined.\n * @param {string} currencyCodeOrSymbol - The ISO currency code (e.g., 'USD', 'CAD') OR a currency symbol (e.g., '$'). Defaults to '$'.\n * @param {string} locale - Optional locale string (e.g., 'en-US', 'en-CA', 'fr-FR'). Defaults to 'en-US'. Used only with Intl.NumberFormat.\n *\n * @returns {string} Formatted currency string.\n */\nexport const formatMoney = (\n amount: string | number | undefined | null,\n currencyCodeOrSymbol: string = '$', // Default to symbol for simple calls\n locale: string = 'en-US'\n): string => {\n const isCurrencyCode = /^[A-Z]{3}$/.test(currencyCodeOrSymbol); // Simple check for 3 uppercase letters\n\n // --- Handle null/undefined/NaN input ---\n let numericAmount: number;\n\n if (amount === null || amount === undefined) {\n numericAmount = 0;\n } else {\n numericAmount = typeof amount === 'string' ? parseFloat(amount) : amount;\n\n if (isNaN(numericAmount)) {\n console.warn(`formatMoney received non-numeric amount: ${amount}`);\n numericAmount = 0;\n }\n }\n\n // --- Use Intl.NumberFormat if a valid currency code is provided ---\n if (isCurrencyCode) {\n try {\n return new Intl.NumberFormat(locale, {\n currency: currencyCodeOrSymbol, // Use the code\n currencyDisplay: 'symbol',\n style: 'currency',\n }).format(numericAmount);\n } catch (error) {\n console.error(\n `Error formatting money with Intl (Amount: ${amount}, Code: ${currencyCodeOrSymbol}, Locale: ${locale}):`,\n error\n );\n\n // Fallback to simple formatting if Intl fails (e.g., invalid code/locale combo)\n // Use the code as a symbol in this specific error case\n return `${currencyCodeOrSymbol}${numericAmount.toFixed(2)}`;\n }\n }\n\n // --- Fallback to simple formatting (Symbol + Fixed Decimals) ---\n // This handles cases where only amount is passed, or a symbol is passed.\n const symbol = currencyCodeOrSymbol; // Assume it's a symbol if not a code\n\n return `${symbol}${numericAmount.toFixed(2)}`;\n};\n\n/**\n * Gets the maximum amount between a compare-at price and regular price\n *\n * @param {StorefrontMoney} compareAtPrice The compare-at price object with amount string\n * @param {StorefrontMoney} price The regular price object with amount string\n *\n * @returns {number} The higher of the two amounts within each money object\n */\nexport const getMaxAmount = (compareAtPrice: StorefrontMoney | null, price: StorefrontMoney) => {\n if (!compareAtPrice) return parseFloat(price?.amount || '0');\n\n return Math.max(parseFloat(compareAtPrice?.amount || '0'), parseFloat(price?.amount || '0'));\n};\n", "import type { CartLine } from '@shopify/hydrogen/storefront-api-types';\nimport {\n CartExclusionProductTag,\n LineItemAttributeKey,\n NO_IMAGE_SHOPIFY_PLACEHOLDER,\n RebuyLineItemAttribution,\n} from '~/smart-cart/constants';\nimport type {\n AnyCartLine,\n StorefrontAttribute,\n StorefrontAutomaticDiscountAllocation,\n StorefrontCartLine,\n StorefrontCodeDiscountAllocation,\n StorefrontCustomDiscountAllocation,\n StorefrontSellingPlanPriceAdjustment,\n StorefrontTypedDiscountAllocation,\n} from '~/smart-cart/types/rebuy-storefront-cart';\nimport type { BuyMoreSaveMoreTier, SmartCartConfig, SwitchToSubscriptionLanguage } from '~/smart-cart/types/smart-cart';\nimport { formatMoney } from '~/smart-cart/utils/moneyUtils';\n\n// *== General Helpers ==*\n\n/**\n * Checks standard hide conditions (tags, specific attributes like _type=child)\n * Does NOT check for TPB gifts based on mode - that's handled in CartItemList filter.\n *\n * @param {AnyCartLine} line - The line item to check\n *\n * @returns {boolean} true if the line item is hidden by standard logic, false otherwise\n */\nexport const isCartItemHiddenByStandardLogic = (line: AnyCartLine): boolean => {\n // Legacy: Hide items with _type === 'child', potentially from an old bundle feature?\n if (line.attributes?.some((attr) => attr.key === '_type' && attr.value === 'child')) {\n return true;\n }\n\n // Check for specific product tag to hide from cart items\n const tags = line.merchandise?.product?.tags ?? [];\n\n if (tags.includes(CartExclusionProductTag.HIDE_FROM_CART_ITEMS)) {\n return true;\n }\n\n // Check for specific line item property (attribute) if needed\n if (line.attributes?.some((attr) => attr.key === LineItemAttributeKey.HIDE_QUANTITY_SELECTOR_GWP_ITEM)) {\n return true;\n }\n\n return false;\n};\n\n/**\n * Identifies if a line item is a subscription item based on Storefront API structure\n *\n * @param {StorefrontCartLine} line - The line item to check\n *\n * @returns {boolean} true if the line item is a subscription item, false otherwise\n */\nexport const isSubscriptionItem = (line: StorefrontCartLine): boolean => {\n return !!line?.sellingPlanAllocation;\n};\n\n// *== General Attribute Helpers ==*\n\n/**\n * Merges new/updated attributes into existing, overwriting duplicates.\n *\n * @param {StorefrontAttribute[] | undefined | null} existing - The existing attribute list.\n * @param {StorefrontAttribute[]} newOrUpdated - The new or updated attribute list.\n *\n * @returns {StorefrontAttribute[]} - The merged attribute list.\n */\nexport const mergeAttributes = (\n existing: StorefrontAttribute[] | undefined | null,\n newOrUpdated: StorefrontAttribute[]\n): StorefrontAttribute[] => {\n const map = new Map<string, string | null>();\n (existing ?? []).forEach((attr) => map.set(attr.key, attr.value ?? null));\n newOrUpdated.forEach((attr) => map.set(attr.key, attr.value ?? null));\n\n return Array.from(map, ([key, value]) => ({ key, value }));\n};\n\n/**\n * Removes specified keys from an attribute list.\n *\n * @param {StorefrontAttribute[] | undefined | null} existing - The existing attribute list.\n * @param {string[]} keysToRemove - The keys to remove from the attribute list.\n *\n * @returns {StorefrontAttribute[]} - The filtered attribute list.\n */\nexport const removeAttributes = (\n existing: StorefrontAttribute[] | undefined | null,\n keysToRemove: string[]\n): StorefrontAttribute[] => {\n if (!existing) return [];\n\n return existing.filter((attr) => !keysToRemove.includes(attr.key));\n};\n\n// *== Meta Helpers ==*\n\n/**\n * Generates an alt text for the item image.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {string} The alt text string.\n */\nexport const getItemImageAlt = (line: StorefrontCartLine): string => {\n return line.merchandise.image?.altText || `Image of ${line.merchandise.product.title}`;\n};\n\n/**\n * Generates the URL for a product based on its handle.\n * Assumes standard '/products/' path.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {string} The product URL string.\n */\nexport const getItemURL = (line: StorefrontCartLine): string => {\n return `/products/${line.merchandise.product.handle}`;\n};\n\n/**\n * Generates an ARIA label for the item link.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {string} The ARIA label string.\n */\nexport const getItemLinkLabel = (line: StorefrontCartLine): string => {\n return `View product: ${line.merchandise.product.title}`;\n};\n\n// *== CSS Class Helpers ==*\n\n/**\n * Sanitizes a string for use in CSS class names.\n *\n * @param {string | undefined | null} str - The string to sanitize.\n *\n * @returns {string} The sanitized string.\n */\nconst sanitizeForClass = (str: string | undefined | null): string => {\n if (typeof str !== 'string' || !str) return '';\n\n return str\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '');\n};\n\n/**\n * Generates CSS class names based on product tags.\n * Prefixes tags with 'tag-'.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {string} A string of space-separated class names.\n */\nexport const getItemProductTagsClasses = (line: StorefrontCartLine): string => {\n const tags = line.merchandise.product.tags ?? [];\n\n return tags.map((tag) => `tag-${sanitizeForClass(tag)}`).join(' ');\n};\n\n/**\n * Generates CSS class names based on line item attributes (properties).\n * Creates classes like 'property-key-{key}' and 'property-value-{value}'.\n * Sanitizes key and value for CSS class usage.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {string} A string of space-separated class names.\n */\nexport const getItemAttributeClasses = (line: StorefrontCartLine): string => {\n return (line.attributes || [])\n .map((attr) => `property-key-${sanitizeForClass(attr.key)} property-value-${sanitizeForClass(attr.value)}`)\n .join(' ');\n};\n\n/**\n * Generates a specific class name for a property key.\n * Handles potentially null/undefined values.\n *\n * @param {StorefrontAttribute} property - The attribute object.\n *\n * @returns {string} A CSS class name string.\n */\nexport const getItemPropertyKeyClass = (property: StorefrontAttribute): string => {\n // Ensure key is a string before sanitizing\n const key = typeof property.key === 'string' ? property.key : '';\n\n return `property-key-${sanitizeForClass(key)}`;\n};\n\n/**\n * Generates a specific class name for a property value.\n * Handles potentially null/undefined values.\n *\n * @param {StorefrontAttribute} property - The attribute object.\n *\n * @returns {string} A CSS class name string.\n */\nexport const getItemPropertyValueClass = (property: StorefrontAttribute): string => {\n // Provide default empty string if value is null/undefined\n const value = property.value ?? '';\n\n return `property-value-${sanitizeForClass(value)}`;\n};\n\n// *== Pricing Helpers ==*\n\ntype CalculatedPricing = {\n compareAtDisplayPrice: string | null;\n displayPrice: string;\n hasDiscount: boolean;\n};\n\n/**\n * Calculates display price, compare-at price, and discount status for a line item.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {CalculatedPricing} The calculated pricing data.\n */\nexport const calculatePricingData = (line: StorefrontCartLine): CalculatedPricing => {\n const hasAppliedDiscount = line.discountAllocations && line.discountAllocations.length > 0;\n const totalAmount = parseFloat(line.cost.totalAmount.amount);\n const quantity = line.quantity;\n const amountPerQuantity = parseFloat(line.cost.amountPerQuantity.amount);\n const compareAtAmountPerQuantity = line.cost.compareAtAmountPerQuantity?.amount\n ? parseFloat(line.cost.compareAtAmountPerQuantity.amount)\n : null;\n\n let calculatedDisplayPrice = amountPerQuantity;\n let calculatedCompareAtPrice = compareAtAmountPerQuantity;\n\n if (hasAppliedDiscount && quantity > 0) {\n calculatedDisplayPrice = totalAmount / quantity;\n calculatedCompareAtPrice =\n compareAtAmountPerQuantity && compareAtAmountPerQuantity > amountPerQuantity\n ? compareAtAmountPerQuantity\n : amountPerQuantity;\n } else if (compareAtAmountPerQuantity && compareAtAmountPerQuantity > amountPerQuantity) {\n calculatedDisplayPrice = amountPerQuantity;\n calculatedCompareAtPrice = compareAtAmountPerQuantity;\n } else {\n calculatedDisplayPrice = amountPerQuantity;\n calculatedCompareAtPrice = null;\n }\n\n const displayPriceStr = formatMoney(calculatedDisplayPrice.toString());\n const compareAtDisplayPriceStr = calculatedCompareAtPrice ? formatMoney(calculatedCompareAtPrice.toString()) : null;\n const hasDiscount = !!(\n compareAtDisplayPriceStr &&\n calculatedCompareAtPrice &&\n calculatedCompareAtPrice > calculatedDisplayPrice\n );\n\n return {\n compareAtDisplayPrice: compareAtDisplayPriceStr,\n displayPrice: displayPriceStr,\n hasDiscount: hasDiscount,\n };\n};\n\n// *== Property Helpers ==*\n\n/**\n * Filters and returns visible item properties (attributes), excluding internal ones (_*).\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {StorefrontAttribute[]} The visible properties.\n */\nexport const getVisibleItemProperties = (line: StorefrontCartLine): StorefrontAttribute[] => {\n return (line.attributes || []).filter((attr) => !attr.key.startsWith('_'));\n};\n\n/**\n * Extracts discount allocation messages as properties.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {StorefrontAttribute[]} The discount properties.\n */\nexport const getDiscountProperties = (line: StorefrontCartLine): StorefrontAttribute[] => {\n const allocations = line.discountAllocations ?? [];\n const messages: StorefrontAttribute[] = [];\n\n allocations.forEach((alloc: StorefrontTypedDiscountAllocation) => {\n let discountMessage: string | null = null;\n\n // Use type guards or __typename to determine the correct property\n switch (alloc.__typename) {\n case 'CartAutomaticDiscountAllocation':\n case 'CartCustomDiscountAllocation':\n // These types have 'title'\n // Need to cast to access the title property safely\n discountMessage = (alloc as StorefrontAutomaticDiscountAllocation | StorefrontCustomDiscountAllocation)\n .title;\n break;\n case 'CartCodeDiscountAllocation': {\n // This type has 'code'\n // Need to cast to access the code property safely\n const code = (alloc as StorefrontCodeDiscountAllocation).code; // Declaration is now safe inside the block scope\n // Optionally add prefix/suffix for codes\n discountMessage = code ? `Code: ${code}` : null; // Example: Prefix with \"Code: \"\n break;\n }\n default: {\n // Handle unexpected allocation types (unlikely)\n const unknownAlloc = alloc as { __typename?: string };\n console.warn('[cartItemUtils] Unknown discount allocation type:', unknownAlloc.__typename);\n break;\n }\n }\n\n if (discountMessage) {\n messages.push({\n key: '_Discount', // Consistent key for styling\n value: discountMessage,\n });\n }\n });\n\n return messages;\n};\n\n/**\n * Extracts the delivery frequency string if item is a subscription.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {string | null} The delivery frequency string, or null if not a subscription.\n */\nexport const getItemDeliveryFrequency = (line: StorefrontCartLine): string | null => {\n // Primarily relies on selling plan allocation name\n if (line.sellingPlanAllocation) {\n return line.sellingPlanAllocation.sellingPlan.name;\n }\n\n // Add fallback logic for properties if necessary (legacy support?)\n return null;\n};\n\n// *== Buy More Save More (BMSM) Utilities ==*\n\n/**\n * Checks if Buy More Save More is enabled in the configuration.\n *\n * @param {SmartCartConfig | null} config The smart cart configuration.\n *\n * @returns {boolean} True if BMSM is enabled.\n */\nexport const isBMSMEnabled = (config: SmartCartConfig | null): boolean => {\n return config?.buy_more_save_more_enabled ?? false;\n};\n\n/**\n * Checks if a specific item is eligible for the Buy More Save More promotion.\n * Compares the item's product/variant ID against the configured list.\n * NOTE: Assumes config.buy_more_save_more.discount_products structure based on legacy code.\n * You might need to adjust based on the actual structure in your `SmartCartConfig`.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n * @param {SmartCartConfig|null} config - The cart configuration.\n *\n * @returns {boolean} True if the item is eligible for BMSM, false otherwise.\n */\nexport const itemHasBMSM = (line: StorefrontCartLine, config: SmartCartConfig | null): boolean => {\n if (!isBMSMEnabled(config)) return false;\n\n // Check if product/variant is eligible\n const bmsmSettings = config?.buy_more_save_more;\n const eligibleItems = bmsmSettings?.discount_products ?? [];\n\n // Extract necessary IDs from the line item\n // Storefront API uses GIDs like \"gid://shopify/Product/12345\"\n // Legacy config likely uses numeric IDs. We need to extract the numeric part.\n const getNumericId = (gid: string | undefined): number | null => {\n if (!gid) return null;\n\n const match = gid.match(/\\/(\\d+)$/);\n\n return match ? parseInt(match[1], 10) : null;\n };\n\n const numericProductId = getNumericId(line.merchandise.product.id);\n const numericVariantId = getNumericId(line.merchandise.id);\n\n if (!numericProductId || !numericVariantId) {\n console.warn('[SmartCartReact] Could not extract numeric ID for BMSM check:', line);\n\n return false; // Cannot check eligibility without numeric IDs matching config\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const foundEligibleItem = eligibleItems.find((product: any) => {\n // TODO: update product type\n // Use 'any' temporarily if config type isn't precise\n // If specific variants have been selected in config\n if (product.variant_ids && product.variant_ids.length > 0) {\n return product.variant_ids.some((configVariantId: number) => configVariantId === numericVariantId);\n }\n\n // If no specific variants, check product ID\n return product.product_id === numericProductId;\n });\n\n // TODO: Consider adding the _rebuyCartId cart attribute update logic here or elsewhere\n // if BMSM + Shopify Functions integration is needed. See legacy code.\n // This usually involves calling Cart.updateItem({ attributes: { _rebuyCartId: ... } })\n // which is a *cart* update, not a line item update. Needs careful placement.\n\n return !!foundEligibleItem; // Return true if an eligible configuration was found\n};\n\n/**\n * Gets the configured BMSM tiers from config, ensuring quantity and discount are numbers.\n *\n * @param {SmartCartConfig | null} config - The cart configuration.\n *\n * @returns {Array<BuyMoreSaveMoreTier>} Array of tier objects with numeric quantity/discount.\n */\nexport const getBMSMTiers = (config: SmartCartConfig | null): BuyMoreSaveMoreTier[] => {\n const tiers = config?.buy_more_save_more?.tiers ?? [];\n\n // Ensure quantity and discount are numbers, provide defaults if missing/invalid\n return tiers\n .map((tier) => ({\n discount: typeof tier.discount === 'number' ? tier.discount : 0,\n quantity: typeof tier.quantity === 'number' ? tier.quantity : 0,\n }))\n .filter((tier) => tier.quantity > 0); // Only include tiers with a quantity\n};\n\n/**\n * Checks if the final BMSM tier has been reached for this item.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n * @param {SmartCartConfig|null} config - The cart configuration.\n *\n * @returns {boolean} True if the final tier has not been reached, false otherwise.\n */\nexport const bMSMFinalTierNotReached = (line: StorefrontCartLine, config: SmartCartConfig | null): boolean => {\n const tiers = getBMSMTiers(config);\n\n if (!tiers.length) return false; // No tiers means no BMSM applies or final tier is irrelevant\n\n const maxTierQuantity = Math.max(...tiers.map((t) => t.quantity ?? 0));\n\n return line.quantity < maxTierQuantity;\n};\n\n/**\n * Checks if BMSM should be displayed as buttons based on config.\n *\n * @param {SmartCartConfig|null} config - The cart configuration.\n *\n * @returns {boolean} True if BMSM should be displayed as buttons, false otherwise.\n */\nexport const hasBMSMButtons = (config: SmartCartConfig | null): boolean => {\n return config?.buy_more_save_more?.display_type === 'buttons';\n};\n\n/**\n * Generates the text for a BMSM tier button based on language settings.\n * Handles placeholders for {{quantity}} and {{discount}}.\n *\n * @param {BuyMoreSaveMoreTier} tier - The tier object.\n * @param {SmartCartConfig|null} config - The cart configuration.\n *\n * @returns {string} The button text.\n */\nexport const getBMSMButtonText = (tier: BuyMoreSaveMoreTier, config: SmartCartConfig | null): string => {\n const bmsmSettings = config?.buy_more_save_more;\n const language = bmsmSettings?.language;\n const discountType = bmsmSettings?.discount_type;\n\n // Default template if not found in config\n const template = language?.bmsm_discount_message || 'Buy {{quantity}}, save {{discount}}%';\n\n const discountValue = tier.discount;\n const discountText =\n discountType === 'percentage'\n ? `${discountValue}%`\n : // Assume fixed amount needs formatting (requires currency info)\n // For now, just display the number if not percentage. Refine if needed.\n formatMoney(discountValue?.toString() ?? ''); // Assuming formatMoney handles fixed amounts\n\n // Basic replacement\n let buttonText = template.replace(/\\{\\{\\s*quantity\\s*\\}\\}/gi, tier.quantity?.toString() ?? '');\n buttonText = buttonText.replace(/\\{\\{\\s*discount\\s*\\}\\}/gi, discountText);\n\n // Support legacy {{difference}} placeholder for buttons as well if needed\n // buttonText = buttonText.replace(/\\{\\{\\s*difference\\s*\\}\\}/gi, tier.quantity.toString());\n\n return buttonText;\n};\n\n/**\n * Generates the dynamic text message for BMSM (when not using buttons).\n * Finds the next applicable tier and formats the message.\n * Handles placeholders for {{quantity}}, {{difference}}, and {{discount}}.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n * @param {SmartCartConfig|null} config - The cart configuration.\n *\n * @returns {string} The dynamic text message, or empty string if no next tier.\n */\nexport const buyMoreSaveMoreDynamicText = (line: StorefrontCartLine, config: SmartCartConfig | null): string => {\n const tiers = getBMSMTiers(config);\n const bmsmSettings = config?.buy_more_save_more;\n const language = bmsmSettings?.language;\n const discountType = bmsmSettings?.discount_type;\n\n // Default template if not found in config\n const template = language?.bmsm_discount_message || 'Buy {{difference}} more to save {{discount}}%';\n\n // Find the *next* tier quantity greater than the current item quantity\n const nextTier = tiers\n .filter((tier) => tier.quantity && tier.quantity > line.quantity)\n .sort((a, b) => (a.quantity ?? 0) - (b.quantity ?? 0))[0]; // Get the lowest tier above current quantity\n\n if (!nextTier) {\n return ''; // No next tier available or already at max tier\n }\n\n const quantityDifference = (nextTier.quantity ?? 0) - (line.quantity ?? 0);\n const discountValue = nextTier.discount;\n const discountText =\n discountType === 'percentage' ? `${discountValue}%` : formatMoney(discountValue?.toString() ?? ''); // Assuming formatMoney handles fixed amounts\n\n // Replace placeholders\n let dynamicText = template.replace(/\\{\\{\\s*difference(_next_quantity)?\\s*\\}\\}/gi, quantityDifference.toString()); // Support legacy 'difference_next_quantity'\n dynamicText = dynamicText.replace(/\\{\\{\\s*quantity\\s*\\}\\}/gi, quantityDifference.toString()); // Also support 'quantity' for difference\n dynamicText = dynamicText.replace(/\\{\\{\\s*discount\\s*\\}\\}/gi, discountText);\n\n return dynamicText;\n};\n\n// *== Subscription Utilities ==*\n\n/**\n * Extracts available selling plans from the cart line's product data.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {Array<{id: string, name: string, adjustments: StorefrontSellingPlanPriceAdjustment[] | null}>} - Array of selling plan details.\n */\nexport const getAvailableSellingPlans = (\n line: StorefrontCartLine\n): {\n adjustments: StorefrontSellingPlanPriceAdjustment[] | null;\n id: string;\n name: string;\n}[] => {\n const groups = line.merchandise.product.sellingPlanGroups?.edges ?? [];\n\n return groups.flatMap((groupEdge) => {\n const planEdge = groupEdge?.node?.sellingPlans?.edges?.[0];\n const planNode = planEdge?.node;\n\n if (planNode) {\n return [\n {\n adjustments: planNode.priceAdjustments ?? null,\n id: planNode.id,\n name: planNode.name,\n },\n ];\n }\n\n return [];\n });\n};\n\n/**\n * Calculates the discount percentage for the first selling plan.\n *\n * @param {Array<{adjustments: StorefrontSellingPlanPriceAdjustment[] | null}>} sellingPlans - Array of selling plan details.\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {number} - The calculated discount percentage.\n */\nexport const calculateDefaultSellingPlanDiscount = (\n sellingPlans: {\n adjustments: StorefrontSellingPlanPriceAdjustment[] | null;\n }[],\n line: StorefrontCartLine\n): number => {\n if (sellingPlans.length === 0) return 0;\n\n const defaultPlan = sellingPlans[0];\n const adjustments = defaultPlan.adjustments;\n const basePrice = parseFloat(line.merchandise.price.amount);\n\n if (!adjustments || adjustments.length === 0 || basePrice <= 0) return 0;\n\n const firstAdjustment = adjustments[0];\n\n if (!firstAdjustment?.adjustmentValue) return 0;\n\n const adjustmentValue = firstAdjustment.adjustmentValue;\n\n // Check for percentage adjustment\n if ('adjustmentPercentage' in adjustmentValue) {\n return Math.max(0, adjustmentValue.adjustmentPercentage);\n }\n\n // If we have an amount adjustment\n if ('adjustmentAmount' in adjustmentValue) {\n const discountAmount = parseFloat(adjustmentValue.adjustmentAmount.amount);\n\n if (discountAmount > 0) {\n // Calculate percentage and round to integer\n return Math.round((discountAmount / basePrice) * 100);\n }\n }\n\n return 0;\n};\n\n/**\n * Gets STS language string, replacing discount placeholder if applicable.\n *\n * @param {keyof SwitchToSubscriptionLanguage} key - The language key.\n * @param {SmartCartConfig | null} config - The cart configuration.\n * @param {number} discountPercent - The discount percentage.\n * @param {string} fallback - The fallback language string.\n *\n * @returns {string} - The formatted language string.\n */\nexport const getSwitchToSubscriptionLabelWithDiscount = (\n key: keyof SwitchToSubscriptionLanguage,\n config: SmartCartConfig | null,\n discountPercent: number,\n fallback?: string\n): string => {\n const language = config?.switch_to_subscription?.language;\n const labelTemplate = language?.[key] ?? fallback ?? key.toString();\n\n if ((key === 'upgrade_to_subscription_label' || key === 'subscription_option_group_label') && discountPercent > 0) {\n return labelTemplate.replace('{{subscription_discount}}', discountPercent.toString());\n }\n\n return labelTemplate;\n};\n\n// *== Bundle Product (Shopify Bundles) Utility Placeholders ==*\n\n// ! Note: Bundles will not be supported on release of this feature.\n// ! This code is provided as a reference for future implementation.\n\n/**\n * Placeholder: Checks if an item represents a bundle.\n * Implement this based on how bundles are identified (e.g., product type, tags, properties).\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {boolean} True if the item is a bundle, false otherwise.\n */\nexport const itemIsBundle = (line: StorefrontCartLine): boolean => {\n // Example: return line.merchandise.product.productType === 'Bundle';\n // Example: return line.merchandise.product.tags.includes('bundle');\n return false; // Placeholder\n};\n\n/**\n * Placeholder: Checks if bundle options should be hidden for this item.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {boolean} True if bundle options should be hidden, false otherwise.\n */\nexport const hideBundleOptions = (line: StorefrontCartLine): boolean => {\n return false; // Placeholder\n};\n\n/**\n * Placeholder: Gets the number of items within a bundle.\n * Requires specific logic based on bundle representation.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {number} The number of items in the bundle.\n */\nexport const getItemBundleLength = (line: StorefrontCartLine): number => {\n // Example: Check a property like '_bundle_items_count'\n return 0; // Placeholder\n};\n\n/**\n * Placeholder: Gets the image URL for a specific option within a bundle.\n * Requires specific logic based on bundle representation and product data.\n *\n * @param {unknown} product - The product object.\n * @param {unknown} option - The bundle option object.\n * @param {number} index - The index of the option.\n *\n * @returns {string} The image URL.\n */\nexport const getBundleOptionImage = (product: unknown, option: unknown, index: number): string => {\n // Needs implementation based on how bundle option images are stored/linked\n return NO_IMAGE_SHOPIFY_PLACEHOLDER; // Placeholder\n};\n\n/**\n * Placeholder: Gets the title for a child item/option within a bundle.\n *\n * @param {any} option - The bundle option object.\n *\n * @returns {string} The title of the child bundle item.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const getChildBundleTitle = (option: any): string => {\n // Needs implementation based on bundle option data structure\n return option?.name || 'Bundle Item'; // Placeholder\n};\n\n// * == Tiered Progress Bar ==*\n\n/**\n * Identifies if a line item is a gift from the tiered progress bar\n *\n * @param {CartLine} line - The line item to check\n *\n * @returns {boolean} true if the line item is a gift from the tiered progress bar, false otherwise\n */\nexport const isTieredProgressBarGiftItem = (line: CartLine): boolean => {\n return line?.attributes?.some(\n (attr: StorefrontAttribute) =>\n attr.key === '_attribution' && attr.value === RebuyLineItemAttribution.TIERED_PROGRESS_BAR\n );\n};\n", "// TODO: REMOVE THIS AND USE npm-rebuy utils instead\n\nexport const safeJsonParse = <T>(jsonString: string | null | undefined): T | null => {\n if (!jsonString) return null;\n try {\n return JSON.parse(jsonString) as T;\n } catch (e) {\n console.error('[safeJsonParse] Failed to parse JSON string:', e, jsonString);\n\n return null;\n }\n};\n", "import type { Cart as HydrogenStorefrontApiCart } from '@shopify/hydrogen/storefront-api-types';\nimport { DebugKey } from '~/constants/debug';\nimport type {\n StorefrontAttribute,\n StorefrontBuyerIdentity,\n StorefrontCartData,\n StorefrontCartLine,\n StorefrontDiscountCode,\n StorefrontTypedDiscountAllocation,\n} from '~/smart-cart/types/rebuy-storefront-cart';\n\nimport type { ContextParameters, RawCartLine } from '~/types/rebuyCustom';\nimport { rebuyDebugLog } from './debugLog';\n\n/**\n * Maps the cart data structure from RebuyContext.contextParameters\n * (derived from Hydrogen/Hydrogen React cart) to the StorefrontCartData shape.\n * Since StorefrontCartData now aliases HydrogenCart, this is a simplified pass-through.\n *\n * @param {HydrogenStorefrontApiCart | Partial<HydrogenStorefrontApiCart> | null | undefined} cartSource - The primary cart data object.\n * @param {ContextParameters | null | undefined} contextParameters - Additional context parameters, used for fallback or supplementary data.\n * @returns {StorefrontCartData | null} - The cart data, or null if essential data is missing.\n */\nexport const mapHydrogenCartToStorefrontCartData = (\n cartSource: HydrogenStorefrontApiCart | Partial<HydrogenStorefrontApiCart> | null | undefined,\n contextParameters: ContextParameters | null | undefined\n): StorefrontCartData | null => {\n // If a direct cartSource is provided and it's valid, use it\n if (cartSource && typeof cartSource === 'object' && cartSource.id) {\n rebuyDebugLog.log(DebugKey.CART_MAPPER, 'Using provided cartSource for mapping.');\n\n return { ...cartSource } as StorefrontCartData;\n }\n\n // Fallback: If no direct cartSource, try getting hydrogenCart from contextParameters\n if (contextParameters?.hydrogenCart) {\n rebuyDebugLog.log(DebugKey.CART_MAPPER, 'Using direct hydrogenCart from contextParameters.');\n\n return { ...contextParameters.hydrogenCart } as StorefrontCartData;\n }\n\n // Fall back to legacy approach using other fields from contextParameters\n if (!contextParameters?.cartId || !contextParameters.cartCost) {\n rebuyDebugLog.warn(\n DebugKey.CART_MAPPER,\n 'Cannot map cart: No valid cartSource provided, and missing contextParameters.cartId or contextParameters.cartCost for legacy mapping.'\n );\n\n return null;\n }\n\n rebuyDebugLog.log(\n DebugKey.CART_MAPPER,\n 'No direct cart object available. Falling back to legacy mapping approach using contextParameters fields.'\n );\n\n const sourceCartId = contextParameters.cartId;\n const sourceCartLines = contextParameters.cartLines ?? [];\n const sourceCartAttributes = contextParameters.cartAttributes ?? [];\n const sourceCartNote = contextParameters.cartNote ?? null;\n const sourceCheckoutUrl = contextParameters.checkoutUrl ?? '';\n const sourceDiscounts = contextParameters.discountCodes ?? [];\n const sourceCartCost = contextParameters.cartCost;\n\n try {\n // --- Map Lines ---\n const mappedLinesEdges = sourceCartLines.map((line: RawCartLine) => {\n const lineNode: StorefrontCartLine = {\n __typename: 'CartLine',\n attributes: (line.attributes ?? []).map((attr) => ({ key: attr.key, value: String(attr.value ?? '') })),\n cost: line.cost,\n discountAllocations: (line.discountAllocations ?? []).map((da) => ({ ...da })),\n estimatedCost: line.estimatedCost ?? null,\n id: line.id,\n merchandise: line.merchandise,\n quantity: line.quantity,\n sellingPlanAllocation: line.sellingPlanAllocation ?? null,\n };\n\n return { cursor: '', node: lineNode };\n });\n\n // --- Map Cart Attributes ---\n const mappedAttributes: StorefrontAttribute[] = sourceCartAttributes.map((attr) => ({\n key: attr.key,\n value: String(attr.value ?? ''),\n }));\n\n // --- Map Buyer Identity ---\n const mappedBuyerIdentity: StorefrontBuyerIdentity = {\n __typename: 'CartBuyerIdentity',\n countryCode: null,\n customer: null,\n deliveryAddressPreferences: [],\n email: null,\n phone: null,\n };\n\n // --- Map Discount Codes ---\n const mappedDiscountCodes: StorefrontDiscountCode[] = sourceDiscounts.map((dc) => ({\n __typename: 'CartDiscountCode',\n applicable: dc.applicable,\n code: dc.code,\n }));\n\n // --- Assemble Final Mapped Cart ---\n const mappedCart: Partial<StorefrontCartData> = {\n __typename: 'Cart',\n appliedGiftCards: [],\n attributes: mappedAttributes,\n buyerIdentity: mappedBuyerIdentity,\n checkoutUrl: sourceCheckoutUrl,\n cost: {\n __typename: 'CartCost',\n subtotalAmount: sourceCartCost.subtotalAmount,\n totalAmount: sourceCartCost.totalAmount,\n } as StorefrontCartData['cost'],\n createdAt: new Date().toISOString(),\n delivery: {\n __typename: 'CartDelivery',\n addresses: [],\n },\n deliveryGroups: {\n __typename: 'CartDeliveryGroupConnection',\n edges: [],\n nodes: [],\n pageInfo: {\n endCursor: null,\n hasNextPage: false,\n hasPreviousPage: false,\n startCursor: null,\n },\n },\n discountAllocations: [] as StorefrontTypedDiscountAllocation[],\n discountCodes: mappedDiscountCodes,\n estimatedCost: {\n __typename: 'CartEstimatedCost',\n checkoutChargeAmount: {\n __typename: 'MoneyV2',\n amount: '0',\n currencyCode: 'USD',\n },\n subtotalAmount: {\n __typename: 'MoneyV2',\n amount: '0',\n currencyCode: 'USD',\n },\n totalAmount: {\n __typename: 'MoneyV2',\n amount: '0',\n currencyCode: 'USD',\n },\n },\n id: sourceCartId,\n lines: {\n __typename: 'BaseCartLineConnection',\n edges: mappedLinesEdges,\n nodes: mappedLinesEdges.map((edge) => edge.node),\n pageInfo: {\n endCursor: null,\n hasNextPage: false,\n hasPreviousPage: false,\n startCursor: null,\n },\n },\n metafields: [],\n note: sourceCartNote,\n totalQuantity: sourceCartLines.reduce((sum, line) => sum + line.quantity, 0),\n updatedAt: new Date().toISOString(),\n };\n\n rebuyDebugLog.log(DebugKey.CART_MAPPER, 'Legacy mapping successful:', mappedCart);\n\n return mappedCart as StorefrontCartData;\n } catch (error) {\n rebuyDebugLog.error(DebugKey.CART_MAPPER, 'Error during legacy cart mapping:', error);\n\n return null;\n }\n};\n", "import * as Utilities from '@rebuy/rebuy/utilities';\nimport type {\n Attribute,\n BaseCartLineConnection,\n CartAutomaticDiscountAllocation,\n CartCodeDiscountAllocation,\n CartCustomDiscountAllocation,\n CartDeliveryGroupConnection,\n CartDiscountCode,\n CartLine,\n ComponentizableCartLine,\n CurrencyCode,\n CartBuyerIdentity as HydrogenCartBuyerIdentity,\n CartCost as HydrogenCartCost,\n MoneyV2 as HydrogenMoneyV2,\n PageInfo as HydrogenPageInfo,\n Cart as HydrogenStorefrontApiCart,\n Metafield,\n} from '@shopify/hydrogen/storefront-api-types';\nimport type { CartContext, CartItem, ContextParameters, RebuyContextProps } from '~/types/rebuyCustom';\nimport { getEncodedAttributes } from '~/utils/getEncodedAttributes';\n\n/* Helper to create a default MoneyV2 object */\nconst defaultMoney = (currencyCode: CurrencyCode = 'USD' as CurrencyCode): HydrogenMoneyV2 => ({\n __typename: 'MoneyV2',\n amount: '0.0',\n currencyCode,\n});\n\n/* Helper to create default PageInfo */\nconst defaultPageInfo = (): HydrogenPageInfo => ({\n __typename: 'PageInfo',\n endCursor: null,\n hasNextPage: false,\n hasPreviousPage: false,\n startCursor: null,\n});\n\n/* Helper for default BuyerIdentity */\nconst defaultBuyerIdentity = (): HydrogenCartBuyerIdentity => ({\n __typename: 'CartBuyerIdentity',\n countryCode: null,\n customer: null,\n deliveryAddressPreferences: [],\n email: null,\n phone: null,\n // preferences and purchasingCompany are not on the official type\n});\n\nexport const createContextParameters = ({\n cacheKey,\n cartAttributes: legacyCartAttributes,\n cartCost: legacyCartCost,\n cartId: legacyCartId,\n cartLines: legacyCartLines,\n cartLinesLength: legacyCartLinesLength,\n cartNote: legacyCartNote,\n cartSubtotal: legacyCartSubtotal,\n cartTotalQuantity: legacyCartTotalQuantity,\n checkoutUrl: legacyCheckoutUrl,\n discountCodes: legacyDiscountCodes,\n hydrogenReactCartActions,\n hydrogenReactCartError,\n hydrogenReactCartStatus,\n isHydrogenReact,\n /* H-React specific */\n queryObject,\n sourceHydrogenCart,\n windowUrl,\n}: RebuyContextProps): ContextParameters => {\n let solidifiedHydrogenCart: HydrogenStorefrontApiCart | null = null;\n const sourceCartCurrency = (sourceHydrogenCart?.cost?.totalAmount?.currencyCode ?? 'USD') as CurrencyCode;\n\n if (sourceHydrogenCart && sourceHydrogenCart.id) {\n const builtCart: Partial<HydrogenStorefrontApiCart> = {\n __typename: 'Cart',\n appliedGiftCards: sourceHydrogenCart.appliedGiftCards ?? [],\n attributes: sourceHydrogenCart.attributes ?? [],\n buyerIdentity: (sourceHydrogenCart.buyerIdentity as HydrogenCartBuyerIdentity) ?? defaultBuyerIdentity(),\n checkoutUrl: sourceHydrogenCart.checkoutUrl ?? '',\n cost: (sourceHydrogenCart.cost as HydrogenCartCost) ?? {\n __typename: 'CartCost',\n checkoutChargeAmount: defaultMoney(sourceCartCurrency),\n subtotalAmount: defaultMoney(sourceCartCurrency),\n subtotalAmountEstimated: false,\n totalAmount: defaultMoney(sourceCartCurrency),\n totalAmountEstimated: false,\n totalDutyAmount: null,\n totalDutyAmountEstimated: false,\n totalTaxAmount: null,\n totalTaxAmountEstimated: false,\n },\n createdAt: sourceHydrogenCart.createdAt ?? new Date().toISOString(),\n deliveryGroups: (sourceHydrogenCart.deliveryGroups as CartDeliveryGroupConnection) ?? {\n __typename: 'CartDeliveryGroupConnection',\n edges: [],\n nodes: [],\n pageInfo: defaultPageInfo(),\n },\n discountAllocations: (sourceHydrogenCart.discountAllocations ?? []) as (\n | CartAutomaticDiscountAllocation\n | CartCodeDiscountAllocation\n | CartCustomDiscountAllocation\n )[],\n discountCodes: (sourceHydrogenCart.discountCodes as CartDiscountCode[]) ?? [],\n id: sourceHydrogenCart.id,\n lines: (sourceHydrogenCart.lines as BaseCartLineConnection) ?? {\n __typename: 'BaseCartLineConnection',\n edges: [],\n nodes: [],\n pageInfo: defaultPageInfo(),\n },\n metafields: (sourceHydrogenCart.metafields ?? []) as Metafield[],\n note: sourceHydrogenCart.note ?? null,\n totalQuantity: sourceHydrogenCart.totalQuantity ?? 0,\n updatedAt: sourceHydrogenCart.updatedAt ?? new Date().toISOString(),\n };\n solidifiedHydrogenCart = builtCart as HydrogenStorefrontApiCart;\n }\n\n let numericCartToken: string | null = null;\n let cartSubtotalInCents: number = 0;\n let linesForCounts: (CartLine | ComponentizableCartLine)[] = [];\n let totalQuantity: number = 0;\n let lineCount: number = 0;\n let legacyNote: string | null = null;\n let legacyAttributes: Attribute[] = [];\n let legacyCheckoutUrlValue: string | undefined;\n let legacyDiscountCodesValue: CartDiscountCode[] = [];\n let legacyCartCostValue: RebuyContextProps['cartCost'] | undefined;\n let legacyCartIdValue: string | undefined;\n\n if (solidifiedHydrogenCart) {\n numericCartToken = Utilities.getIdFromGraphUrl(solidifiedHydrogenCart.id, 'Cart')?.toString() || null;\n cartSubtotalInCents = solidifiedHydrogenCart.cost?.subtotalAmount?.amount\n ? Utilities.amountToCents(parseFloat(solidifiedHydrogenCart.cost.subtotalAmount.amount))\n : 0;\n\n linesForCounts =\n (solidifiedHydrogenCart.lines.nodes?.length ?? 0) > 0\n ? (solidifiedHydrogenCart.lines.nodes as (CartLine | ComponentizableCartLine)[])\n : ((solidifiedHydrogenCart.lines.edges?.map((e) => e.node) as (CartLine | ComponentizableCartLine)[]) ??\n []);\n\n totalQuantity = solidifiedHydrogenCart.totalQuantity;\n lineCount = linesForCounts.length;\n legacyNote = solidifiedHydrogenCart.note ?? null;\n legacyAttributes = [...solidifiedHydrogenCart.attributes];\n legacyCheckoutUrlValue = solidifiedHydrogenCart.checkoutUrl;\n legacyDiscountCodesValue = [...solidifiedHydrogenCart.discountCodes];\n legacyCartCostValue = solidifiedHydrogenCart.cost;\n legacyCartIdValue = solidifiedHydrogenCart.id;\n } else {\n numericCartToken = legacyCartId ? Utilities.getIdFromGraphUrl(legacyCartId, 'Cart')?.toString() || null : null;\n const subtotalString = legacyCartCost?.subtotalAmount?.amount ?? legacyCartSubtotal;\n cartSubtotalInCents = subtotalString ? Utilities.amountToCents(parseFloat(subtotalString)) : 0;\n linesForCounts = Array.isArray(legacyCartLines)\n ? ([...legacyCartLines] as (CartLine | ComponentizableCartLine)[])\n : [];\n totalQuantity = legacyCartTotalQuantity ?? linesForCounts.reduce((sum, line) => sum + (line?.quantity ?? 0), 0);\n lineCount = legacyCartLinesLength ?? linesForCounts.length;\n legacyNote = legacyCartNote ?? null;\n legacyAttributes = legacyCartAttributes ? [...legacyCartAttributes] : [];\n legacyCheckoutUrlValue = legacyCheckoutUrl;\n legacyDiscountCodesValue = legacyDiscountCodes ? [...legacyDiscountCodes] : [];\n legacyCartCostValue = legacyCartCost;\n legacyCartIdValue = legacyCartId;\n }\n\n const contextParametersOutput: ContextParameters = {\n cache_key: cacheKey,\n cart: undefined,\n cart_count: totalQuantity,\n cart_item_count: totalQuantity,\n cart_line_count: lineCount,\n cart_subtotal: cartSubtotalInCents,\n\n cart_token: numericCartToken || undefined,\n cartAttributes: legacyAttributes,\n cartCost: legacyCartCostValue,\n cartId: legacyCartIdValue,\n cartLines: linesForCounts as CartLine[],\n cartNote: legacyNote,\n checkoutUrl: legacyCheckoutUrlValue,\n\n discountCodes: legacyDiscountCodesValue,\n\n hydrogenCart: solidifiedHydrogenCart,\n hydrogenReactCartActions,\n hydrogenReactCartError,\n\n hydrogenReactCartStatus,\n isHydrogenReact,\n time: queryObject.time ?? '',\n\n url: windowUrl,\n };\n\n const cartContext: CartContext = {\n attributes: '',\n item_count: totalQuantity,\n items: [],\n line_count: lineCount,\n note: legacyNote ?? '',\n subtotal: cartSubtotalInCents,\n token: numericCartToken ?? '',\n };\n\n if (legacyAttributes.length > 0) {\n const validAttributes = legacyAttributes.filter(\n (attr): attr is { key: string; value: string } =>\n typeof attr.key === 'string' && typeof attr.value === 'string'\n );\n cartContext.attributes = getEncodedAttributes(validAttributes);\n }\n\n if (linesForCounts.length > 0) {\n cartContext.items = linesForCounts.map((line): CartItem => {\n const item: CartItem = {\n attributes: line.attributes ? [...line.attributes] : [],\n product_id: line.merchandise?.product?.id\n ? Utilities.getIdFromGraphUrl(line.merchandise.product.id, 'Product')?.toString() || ''\n : '',\n properties: '',\n quantity: line.quantity,\n variant_id: line.merchandise?.id\n ? Utilities.getIdFromGraphUrl(line.merchandise.product.id, 'Product')?.toString() || ''\n : '',\n };\n\n if (line.attributes?.length) {\n const validLineAttributes = line.attributes.filter(\n (attr): attr is { key: string; value: string } =>\n typeof attr.key === 'string' && typeof attr.value === 'string'\n );\n item.properties = getEncodedAttributes(validLineAttributes);\n }\n\n return item;\n });\n }\n\n // Create a new object with all properties from contextParametersOutput\n // but with cart property set to cartContext\n return {\n ...contextParametersOutput,\n cart: cartContext,\n };\n};\n", "import type { Attribute } from '@shopify/hydrogen-react/storefront-api-types';\n\nexport const getEncodedAttributes = (attributes: Attribute[]) =>\n encodeURIComponent(\n JSON.stringify(attributes.reduce((merged, { key, value }) => ({ ...merged, [key]: value }), {}))\n );\n", "/* eslint-disable jsdoc/require-param */\nimport * as Utilities from '@rebuy/rebuy/utilities';\nimport { CartProvider, ShopifyProvider, useCart } from '@shopify/hydrogen-react';\nimport { useEffect, useMemo, useRef } from 'react';\nimport { useLocation } from 'react-router';\nimport { DebugKey } from '~/constants/debug';\nimport { RebuyConfigProvider, useRebuyConfig } from '~/context/RebuyConfigContext';\nimport { RebuyContext, type RebuyContextType } from '~/context/RebuyContext';\nimport type { RebuyHydrogenReactContextProviderProps, RebuyHydrogenReactProps } from '~/providers/types';\nimport { CART_FRAGMENT } from '~/queries/cart.queries';\nimport { SmartCartProvider as RebuySmartCartProvider } from '~/smart-cart/context/SmartCartContext';\nimport type { SmartCartConfig } from '~/smart-cart/types/smart-cart';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport type { HydrogenReactCartActions, RebuyContextProps } from '~/types/rebuyCustom';\nimport { createContextParameters } from '~/utils/createContextParameters';\n\n/**\n * Internal component handling Rebuy configuration fetching,\n * context setup, and conditional Smart Cart provider rendering\n * for Hydrogen React environments.\n */\nconst RebuyHydrogenReactContext = ({\n children,\n enableSmartCart,\n publicPrimaryDomain,\n publicStorefrontToken,\n}: RebuyHydrogenReactProps) => {\n const {\n apiKey,\n fetchError: configFetchError,\n loadingStatus: configLoadingStatus,\n rebuyConfig,\n shopDomain: configShopDomain,\n } = useRebuyConfig();\n\n const warningLogged = useRef(false);\n\n const location = useLocation();\n const queryObject = Utilities.queryStringToObject(location.search);\n const windowUrl = publicPrimaryDomain ? `${publicPrimaryDomain}${location.pathname}${location.search}` : '';\n\n // ---- Hydrogen React Cart Integration ----\n const {\n cartAttributesUpdate,\n cartCreate,\n discountCodesUpdate,\n error: hydrogenReactCartError,\n linesAdd,\n linesRemove,\n linesUpdate,\n noteUpdate,\n status: hydrogenReactCartStatus,\n ...hydrogenReactCartData\n } = useCart();\n\n const hydrogenReactCartActions: HydrogenReactCartActions | undefined = useMemo(\n () => ({\n cartAttributesUpdate,\n cartCreate,\n discountCodesUpdate,\n linesAdd,\n linesRemove,\n linesUpdate,\n noteUpdate,\n }),\n [cartAttributesUpdate, cartCreate, discountCodesUpdate, linesAdd, linesRemove, linesUpdate, noteUpdate]\n );\n\n // --- Context Parameters Memoization ---\n const contextParameters = useMemo(() => {\n const propsForParamCreation: RebuyContextProps = {\n cacheKey: rebuyConfig?.shop?.cache_key,\n hydrogenReactCartActions,\n hydrogenReactCartError,\n hydrogenReactCartStatus,\n isHydrogenReact: true,\n queryObject,\n sourceHydrogenCart: hydrogenReactCartData as any, // eslint-disable-line @typescript-eslint/no-explicit-any\n windowUrl,\n };\n\n return createContextParameters(propsForParamCreation);\n }, [\n rebuyConfig?.shop?.cache_key,\n windowUrl,\n queryObject,\n hydrogenReactCartData,\n hydrogenReactCartActions,\n hydrogenReactCartStatus,\n hydrogenReactCartError,\n ]);\n\n const defaultContextValue = useMemo(() => ({ contextParameters: {} }) as RebuyContextType, []);\n const rebuyContextValue = useMemo(\n () => (configLoadingStatus === 'success' && rebuyConfig ? { contextParameters } : defaultContextValue),\n [configLoadingStatus, rebuyConfig, contextParameters, defaultContextValue]\n );\n\n // --- Smart Cart Prerequisites Calculation ---\n const smartCartConfig = enableSmartCart ? (rebuyConfig?.smart_cart as SmartCartConfig | null) : null;\n const cacheKey = rebuyConfig?.shop?.cache_key || '';\n const shopifyDomainForSmartCart = configShopDomain || rebuyConfig?.shop?.domain || '';\n const storefrontAccessToken = publicStorefrontToken || rebuyConfig?.shop?.storefront_access_token || '';\n\n const hasAllSmartCartPrerequisites =\n enableSmartCart &&\n configLoadingStatus === 'success' &&\n !!rebuyConfig &&\n !!(smartCartConfig && apiKey && shopifyDomainForSmartCart && storefrontAccessToken);\n\n // --- State Logging ---\n useEffect(() => {\n if (configLoadingStatus === 'loading') return;\n const smartCartDetails = enableSmartCart\n ? {\n hasAllSmartCartPrerequisites,\n hasApiKey: !!apiKey,\n hasShopifyDomain: !!shopifyDomainForSmartCart,\n hasStorefrontToken: !!storefrontAccessToken,\n smartCartConfigLoaded: !!smartCartConfig,\n }\n : { smartCartEnabled: false };\n\n rebuyDebugLog.log(DebugKey.REBUY_HYDROGEN_REACT_PROVIDER, '[Rebuy React Provider State Update]', {\n apiKeyAvailable: !!apiKey,\n fetchError: configFetchError\n ? configFetchError instanceof Error\n ? configFetchError.message\n : configFetchError\n : null,\n loadingStatus: configLoadingStatus,\n rebuyConfigLoaded: !!rebuyConfig,\n ...smartCartDetails,\n });\n }, [\n configLoadingStatus,\n configFetchError,\n rebuyConfig,\n smartCartConfig,\n apiKey,\n shopifyDomainForSmartCart,\n storefrontAccessToken,\n hasAllSmartCartPrerequisites,\n enableSmartCart,\n ]);\n\n // --- Render Logic: Provide Context and Conditionally Render Smart Cart ---\n return (\n <RebuyContext.Provider value={rebuyContextValue}>\n {configLoadingStatus === 'success' && rebuyConfig ? (\n enableSmartCart && hasAllSmartCartPrerequisites ? (\n <RebuySmartCartProvider\n apiKey={apiKey!}\n cacheKey={cacheKey}\n config={smartCartConfig!}\n hydrogenCart={hydrogenReactCartData as any} // eslint-disable-line @typescript-eslint/no-explicit-any\n shopifyDomain={shopifyDomainForSmartCart}\n storefrontAccessToken={storefrontAccessToken}\n >\n {children}\n </RebuySmartCartProvider>\n ) : (\n <>\n {enableSmartCart &&\n !hasAllSmartCartPrerequisites &&\n !warningLogged.current &&\n (() => {\n console.warn(\n `[Rebuy React Provider] Rebuy config loaded, but Smart Cart prerequisites NOT met for ${shopifyDomainForSmartCart}. Smart Cart UI will not render. Check Rebuy Admin/env vars. Missing:`,\n {\n apiKey: !!apiKey,\n config: !!smartCartConfig,\n domain: !!shopifyDomainForSmartCart,\n token: !!storefrontAccessToken,\n }\n );\n warningLogged.current = true;\n\n return null;\n })()}\n {children}\n </>\n )\n ) : configLoadingStatus === 'error' ? (\n <>{children}</>\n ) : null}\n </RebuyContext.Provider>\n );\n};\n\n/**\n * Outer provider component responsible for setting up ShopifyProvider,\n * CartProvider (from @shopify/hydrogen-react), and wrapping the application\n * with the RebuyHydrogenReactContext.\n */\nexport const RebuyHydrogenReactContextProvider = ({\n cart,\n cartFragment = CART_FRAGMENT,\n\n // --- ShopifyProvider Props ---\n children,\n countryIsoCode = 'US',\n customerAccessToken = '',\n enableSmartCart = true,\n languageIsoCode = 'EN',\n numCartLines,\n onAttributesUpdate,\n\n // --- CartProvider Props ---\n onAttributesUpdateComplete,\n onBuyerIdentityUpdate,\n onBuyerIdentityUpdateComplete,\n onCreate,\n // --- CartProvider Callbacks (adapted) ---\n onCreateComplete,\n onDiscountCodesUpdate,\n onDiscountCodesUpdateComplete,\n onLineAdd,\n onLineAddComplete,\n onLineRemove,\n onLineRemoveComplete,\n onLineUpdate,\n onLineUpdateComplete,\n onNoteUpdate,\n onNoteUpdateComplete,\n overrideApiKey,\n publicPrimaryDomain,\n publicStoreDomain,\n publicStorefrontId,\n publicStorefrontToken,\n storefrontApiVersion = '2025-01',\n}: RebuyHydrogenReactContextProviderProps) => {\n // Adapt callbacks to prevent errors if undefined\n const adaptedCallbacks = useMemo(\n () => ({\n onAttributesUpdate: onAttributesUpdate ? () => onAttributesUpdate() : undefined,\n onAttributesUpdateComplete: onAttributesUpdateComplete ? () => onAttributesUpdateComplete() : undefined,\n onBuyerIdentityUpdate: onBuyerIdentityUpdate ? () => onBuyerIdentityUpdate() : undefined,\n onBuyerIdentityUpdateComplete: onBuyerIdentityUpdateComplete\n ? () => onBuyerIdentityUpdateComplete()\n : undefined,\n onCreate: onCreate ? () => onCreate() : undefined,\n onCreateComplete: onCreateComplete ? () => onCreateComplete() : undefined,\n onDiscountCodesUpdate: onDiscountCodesUpdate ? () => onDiscountCodesUpdate() : undefined,\n onDiscountCodesUpdateComplete: onDiscountCodesUpdateComplete\n ? () => onDiscountCodesUpdateComplete()\n : undefined,\n onLineAdd: onLineAdd ? () => onLineAdd() : undefined,\n onLineAddComplete: onLineAddComplete ? () => onLineAddComplete() : undefined,\n onLineRemove: onLineRemove ? () => onLineRemove() : undefined,\n onLineRemoveComplete: onLineRemoveComplete ? () => onLineRemoveComplete() : undefined,\n onLineUpdate: onLineUpdate ? () => onLineUpdate() : undefined,\n onLineUpdateComplete: onLineUpdateComplete ? () => onLineUpdateComplete() : undefined,\n onNoteUpdate: onNoteUpdate ? () => onNoteUpdate() : undefined,\n onNoteUpdateComplete: onNoteUpdateComplete ? () => onNoteUpdateComplete() : undefined,\n }),\n [\n // List all original callback props as dependencies\n onAttributesUpdate,\n onAttributesUpdateComplete,\n onBuyerIdentityUpdate,\n onBuyerIdentityUpdateComplete,\n onCreate,\n onCreateComplete,\n onDiscountCodesUpdate,\n onDiscountCodesUpdateComplete,\n onLineAdd,\n onLineAddComplete,\n onLineRemove,\n onLineRemoveComplete,\n onLineUpdate,\n onLineUpdateComplete,\n onNoteUpdate,\n onNoteUpdateComplete,\n ]\n );\n\n // --- ShopifyProvider Validation ---\n if (!publicStoreDomain) {\n console.warn(\n '[RebuyHydrogenReactContextProvider] Missing required prop: `publicStoreDomain` (for Rebuy config fetching).'\n );\n\n return <>{children}</>;\n }\n\n if (!publicStorefrontToken) {\n console.warn(\n '[RebuyHydrogenReactContextProvider] Missing `publicStorefrontToken` (Shopify Storefront API Token). This is required for ShopifyProvider and cart operations.'\n );\n }\n\n return (\n <ShopifyProvider\n countryIsoCode={countryIsoCode}\n languageIsoCode={languageIsoCode}\n storeDomain={publicStoreDomain}\n storefrontApiVersion={storefrontApiVersion}\n storefrontId={publicStorefrontId}\n storefrontToken={publicStorefrontToken}\n >\n <CartProvider\n cartFragment={cartFragment}\n countryCode={countryIsoCode}\n customerAccessToken={customerAccessToken}\n data={cart}\n languageCode={languageIsoCode}\n numCartLines={numCartLines}\n {...adaptedCallbacks}\n >\n <RebuyConfigProvider initialShopDomain={publicStoreDomain} overrideApiKey={overrideApiKey}>\n <RebuyHydrogenReactContext\n enableSmartCart={enableSmartCart}\n publicPrimaryDomain={publicPrimaryDomain}\n publicStorefrontToken={publicStorefrontToken}\n >\n {children}\n </RebuyHydrogenReactContext>\n </RebuyConfigProvider>\n </CartProvider>\n </ShopifyProvider>\n );\n};\n", "export const OPTION_FRAGMENT = `#graphql\n fragment OptionFragment on ProductOption {\n __typename\n id\n name\n optionValues {\n __typename\n id\n name\n swatch {\n __typename\n color\n image {\n __typename\n mediaContentType\n previewImage {\n __typename\n height\n id\n url\n width\n altText\n }\n id\n alt\n }\n }\n }\n }\n`;\n/*\n * STOREFRONT API QUERIES -----------------------------------------------------\n */\n\n// Docs: https://shopify.dev/docs/api/storefront/latest/objects/Cart\n\nexport const CART_LINE_FRAGMENT = `#graphql\n fragment CartLineFragment on CartLine {\n __typename\n id\n quantity\n cost {\n __typename\n amountPerQuantity {\n __typename\n amount\n currencyCode\n }\n compareAtAmountPerQuantity {\n __typename\n amount\n currencyCode\n }\n totalAmount {\n __typename\n amount\n currencyCode\n }\n subtotalAmount {\n __typename\n amount\n currencyCode\n }\n }\n attributes {\n __typename\n key\n value\n }\n discountAllocations {\n discountedAmount {\n __typename\n amount\n currencyCode\n }\n ... on CartAutomaticDiscountAllocation {\n __typename\n discountedAmount {\n amount\n currencyCode\n }\n title\n }\n ... on CartCodeDiscountAllocation {\n __typename\n code\n discountedAmount {\n amount\n currencyCode\n }\n }\n ... on CartCustomDiscountAllocation {\n __typename\n discountedAmount {\n amount\n currencyCode\n }\n title\n }\n }\n merchandise {\n ... on ProductVariant {\n __typename\n availableForSale\n id\n sku\n title\n compareAtPrice {\n __typename\n amount\n currencyCode\n }\n image {\n __typename\n altText\n height\n id\n url\n width\n }\n price {\n __typename\n amount\n currencyCode\n }\n product {\n __typename\n handle\n id\n productType\n tags\n title\n vendor\n description\n requiresSellingPlan\n collections(first: 10) {\n __typename\n nodes {\n __typename\n handle\n }\n }\n options {\n ...OptionFragment\n }\n images(first: 20) {\n __typename\n nodes {\n __typename\n altText\n height\n id\n url\n width\n }\n }\n sellingPlanGroups(first: 100) {\n __typename\n edges {\n __typename\n node {\n __typename\n appName\n name\n options { __typename name values }\n sellingPlans(first: 100) {\n __typename\n edges {\n __typename\n node {\n __typename\n id\n name\n options { __typename name value }\n priceAdjustments {\n __typename\n adjustmentValue {\n __typename\n ... on SellingPlanFixedAmountPriceAdjustment {\n adjustmentAmount { __typename amount currencyCode }\n }\n ... on SellingPlanFixedPriceAdjustment {\n price { __typename amount currencyCode }\n }\n ... on SellingPlanPercentagePriceAdjustment {\n adjustmentPercentage\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n selectedOptions {\n __typename\n name\n value\n }\n }\n }\n sellingPlanAllocation {\n __typename\n sellingPlan {\n __typename\n id\n name\n }\n }\n }\n` as const;\n\nexport const CART_LINE_COMPONENT_FRAGMENT = `#graphql\n fragment CartLineComponentFragment on ComponentizableCartLine {\n __typename\n id\n quantity\n cost {\n __typename\n amountPerQuantity { __typename amount currencyCode }\n compareAtAmountPerQuantity { __typename amount currencyCode }\n totalAmount { __typename amount currencyCode }\n subtotalAmount { __typename amount currencyCode }\n }\n attributes { __typename key value }\n discountAllocations {\n discountedAmount { __typename amount currencyCode }\n ... on CartAutomaticDiscountAllocation {\n __typename\n discountedAmount { amount currencyCode }\n title\n }\n ... on CartCodeDiscountAllocation {\n __typename\n code\n discountedAmount { amount currencyCode }\n }\n ... on CartCustomDiscountAllocation {\n __typename\n discountedAmount { amount currencyCode }\n title\n }\n }\n merchandise {\n ... on ProductVariant {\n __typename\n availableForSale\n id\n sku\n title\n compareAtPrice { __typename amount currencyCode }\n image { __typename altText height id url width }\n price { __typename amount currencyCode }\n product {\n __typename\n handle\n id\n productType\n tags\n title\n vendor\n description\n requiresSellingPlan\n collections(first: 10) {\n __typename\n nodes { __typename handle }\n }\n options {\n id\n name\n optionValues {\n __typename\n id\n name\n swatch {\n __typename\n color\n image {\n __typename\n mediaContentType\n previewImage { __typename height id url width altText }\n id\n alt\n }\n }\n }\n }\n images(first: 20) {\n __typename\n nodes { __typename altText height id url width }\n }\n sellingPlanGroups(first: 100) {\n __typename\n edges {\n __typename\n node {\n __typename\n appName\n name\n options { __typename name values }\n sellingPlans(first: 100) {\n __typename\n edges {\n __typename\n node {\n __typename\n id\n name\n options { __typename name value }\n priceAdjustments {\n __typename\n adjustmentValue {\n __typename\n ... on SellingPlanFixedAmountPriceAdjustment { adjustmentAmount { __typename amount currencyCode } }\n ... on SellingPlanFixedPriceAdjustment { price { __typename amount currencyCode } }\n ... on SellingPlanPercentagePriceAdjustment { adjustmentPercentage }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n selectedOptions { __typename name value }\n }\n }\n sellingPlanAllocation {\n __typename\n sellingPlan {\n __typename\n id\n name\n }\n }\n lineComponents {\n __typename\n id\n quantity\n cost {\n __typename\n amountPerQuantity { __typename amount currencyCode }\n compareAtAmountPerQuantity { __typename amount currencyCode }\n totalAmount { __typename amount currencyCode }\n subtotalAmount { __typename amount currencyCode }\n }\n attributes { __typename key value }\n discountAllocations {\n discountedAmount { __typename amount currencyCode }\n ... on CartAutomaticDiscountAllocation {\n __typename\n discountedAmount { amount currencyCode }\n title\n }\n ... on CartCodeDiscountAllocation {\n __typename\n code\n discountedAmount { amount currencyCode }\n }\n ... on CartCustomDiscountAllocation {\n __typename\n discountedAmount { amount currencyCode }\n title\n }\n }\n merchandise {\n ... on ProductVariant {\n __typename\n availableForSale\n id\n sku\n title\n compareAtPrice { __typename amount currencyCode }\n image { __typename altText height id url width }\n price { __typename amount currencyCode }\n product {\n __typename\n handle\n id\n productType\n tags\n title\n vendor\n description\n requiresSellingPlan\n collections(first: 10) {\n __typename\n nodes { __typename handle }\n }\n options {\n ...OptionFragment\n }\n images(first: 20) {\n __typename\n nodes { __typename altText height id url width }\n }\n sellingPlanGroups(first: 100) {\n __typename\n edges {\n __typename\n node {\n __typename\n appName\n name\n options { __typename name values }\n sellingPlans(first: 100) {\n __typename\n edges {\n __typename\n node {\n __typename\n id\n name\n options { __typename name value }\n priceAdjustments {\n __typename\n adjustmentValue {\n __typename\n ... on SellingPlanFixedAmountPriceAdjustment { adjustmentAmount { __typename amount currencyCode } }\n ... on SellingPlanFixedPriceAdjustment { price { __typename amount currencyCode } }\n ... on SellingPlanPercentagePriceAdjustment { adjustmentPercentage }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n selectedOptions { __typename name value }\n }\n }\n sellingPlanAllocation {\n __typename\n sellingPlan {\n __typename\n id\n name\n }\n }\n }\n }\n` as const;\n\nexport const CART_FRAGMENT = `#graphql\n fragment CartFragment on Cart {\n id\n checkoutUrl\n createdAt\n totalQuantity\n note\n updatedAt\n __typename\n buyerIdentity {\n __typename\n countryCode\n customer {\n __typename\n id\n email\n firstName\n lastName\n displayName\n }\n email\n phone\n }\n attributes {\n __typename\n key\n value\n }\n cost {\n __typename\n subtotalAmount {\n __typename\n amount\n currencyCode\n }\n totalAmount {\n __typename\n amount\n currencyCode\n }\n }\n discountAllocations {\n discountedAmount {\n __typename\n amount\n currencyCode\n }\n ... on CartAutomaticDiscountAllocation {\n __typename\n discountedAmount {\n amount\n currencyCode\n }\n title\n }\n ... on CartCodeDiscountAllocation {\n __typename\n code\n discountedAmount {\n amount\n currencyCode\n }\n }\n ... on CartCustomDiscountAllocation {\n __typename\n discountedAmount {\n amount\n currencyCode\n }\n title\n }\n }\n discountCodes {\n __typename\n applicable\n code\n }\n lines(first: $numCartLines) {\n __typename\n edges {\n __typename\n node {\n ...CartLineComponentFragment\n }\n }\n }\n }\n ${CART_LINE_FRAGMENT}\n ${CART_LINE_COMPONENT_FRAGMENT}\n ${OPTION_FRAGMENT}\n` as const;\n", "/* eslint-disable no-restricted-imports */\n// ~/smart-cart/components/SmartCartContainer.tsx\nimport clsx from 'clsx';\nimport React, { useCallback, useEffect, useMemo, useRef } from 'react';\nimport { AnchorSlot } from '~/smart-cart/components/_Layouts/AnchorSlot';\nimport { DoubleColumnLayout } from '~/smart-cart/components/_Layouts/DoubleColumnLayout';\nimport { SingleColumnLayout } from '~/smart-cart/components/_Layouts/SingleColumnLayout';\nimport { ScreenReaderText } from '~/smart-cart/components/ScreenReaderText/ScreenReaderText';\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport type { TitleBarSettings } from '~/smart-cart/types/smart-cart-component';\n\nimport './Global.css';\nimport styles from './SmartCartContainer.module.css';\n\ntype SmartCartContainerProps = { containerId?: string };\n\nexport const SmartCartContainer: React.FC<SmartCartContainerProps> = ({ containerId }) => {\n const { config, getItemCount, hideCart, isVisible } = useSmartCart();\n const containerRef = useRef<HTMLDivElement>(null);\n const previousFocusRef = useRef<HTMLElement | null>(null);\n\n const components = useMemo(() => (config && Array.isArray(config.components) ? config.components : []), [config]);\n\n const handleClose = useCallback(() => {\n hideCart();\n\n // Restore focus when closing\n if (previousFocusRef.current) {\n previousFocusRef.current.focus();\n }\n }, [hideCart]);\n\n // Store the focused element when opening the cart\n useEffect(() => {\n if (isVisible) {\n previousFocusRef.current = document.activeElement as HTMLElement;\n // Focus the close button when opening\n const closeButton = containerRef.current?.querySelector('#rebuy-cart-close');\n\n if (closeButton instanceof HTMLElement) {\n closeButton.focus();\n }\n }\n }, [isVisible]);\n\n // Prevent body scroll when cart is open\n useEffect(() => {\n if (isVisible) {\n document.body.classList.add('rebuy-smart-cart-open');\n } else {\n document.body.classList.remove('rebuy-smart-cart-open');\n }\n\n // Cleanup on unmount\n return () => {\n document.body.classList.remove('rebuy-smart-cart-open');\n };\n }, [isVisible]);\n\n const backgroundClassName = clsx(styles['rebuy-smart-cart__overlay-background'], {\n [styles['rebuy-smart-cart__overlay-background--visible']]: isVisible,\n });\n\n const flyoutContainerClasses = clsx(\n styles['rebuy-smart-cart'], // Base container class\n {\n [styles['rebuy-smart-cart--visible']]: isVisible,\n [styles['rebuy-smart-cart--layout-double']]:\n config?.layout === 'double' || config?.layout === 'double-right',\n }\n );\n\n const renderLayoutContent = () => {\n if (!config) return <div style={{ padding: '20px', textAlign: 'center' }}>Loading configuration...</div>;\n switch (config.layout) {\n case 'double':\n case 'double-right':\n return <DoubleColumnLayout components={components} itemCount={getItemCount()} layout={config.layout} />;\n default:\n return <SingleColumnLayout components={components} itemCount={getItemCount()} />;\n }\n };\n\n const defaultTitleId = 'rebuy-smart-cart-default-title';\n const titleBarComponent = components.find((c) => c.type === 'title_bar');\n const ariaLabelledBy = titleBarComponent ? `rebuy-title-${titleBarComponent.component_id}` : defaultTitleId;\n\n return (\n <React.Fragment>\n <div className={backgroundClassName} onClick={handleClose} />\n <div\n aria-labelledby={ariaLabelledBy}\n aria-modal=\"true\"\n className={flyoutContainerClasses}\n data-rebuy-cart-layout={config?.layout || 'single'}\n id={containerId || 'rebuy-cart-react'}\n ref={containerRef}\n role=\"dialog\"\n tabIndex={-1}\n >\n <header className={styles['rebuy-smart-cart__header']} data-rebuy-cart-anchor=\"header\">\n <div className={styles['rebuy-smart-cart__header-top-bar']} data-rebuy-cart-header-top-bar=\"\">\n <div className={styles['rebuy-smart-cart__header-content']} data-rebuy-cart-header-top-inner=\"\">\n <AnchorSlot anchor=\"header\" components={components} includeTypes={['title_bar', 'login']} />\n {!components.some(\n (c) => c.type === 'title_bar' && !(c.settings as TitleBarSettings)?.screen_reader_only\n ) && (\n <h2 id={defaultTitleId}>\n <ScreenReaderText>Your Cart</ScreenReaderText>\n </h2>\n )}\n </div>\n <button\n aria-label=\"Close Cart\"\n className={styles['rebuy-smart-cart__close-button']}\n id=\"rebuy-cart-close\"\n onClick={handleClose}\n type=\"button\"\n >\n \u2715<ScreenReaderText>Close Cart</ScreenReaderText>\n </button>\n </div>\n <AnchorSlot anchor=\"header\" components={components} excludeTypes={['title_bar', 'login']} />\n </header>\n\n {renderLayoutContent()}\n\n <div aria-live=\"polite\" className=\"rebuy-sr-only\" id=\"rebuy-cart-live-region\"></div>\n </div>\n </React.Fragment>\n );\n};\n", "// ~/smart-cart/components/AnchorSlot.tsx\nimport { useMemo, type FC } from 'react';\nimport { DebugKey } from '~/constants/debug';\n\nimport { componentRegistry } from '~/smart-cart/components/componentRegistry'; // Ensure path is correct\nimport type { ComponentAnchor, SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\n\ntype AnchorSlotProps = {\n anchor: ComponentAnchor;\n components: SmartCartComponentConfig[];\n /** Optional list of component types to *exclude*. If provided, these types are skipped. */\n excludeTypes?: string[];\n /** Optional list of component types to *include*. If provided, only these types are rendered. */\n includeTypes?: string[];\n};\n\nexport const AnchorSlot: FC<AnchorSlotProps> = ({ anchor, components, excludeTypes, includeTypes }) => {\n const componentsForSlot = useMemo(() => {\n return components\n .filter((comp) => {\n // Basic filtering\n const isCorrectAnchor = comp.anchor === anchor;\n const isVisible = comp.visibility_status !== 'hidden';\n const included = !includeTypes || includeTypes.includes(comp.type);\n const excluded = excludeTypes && excludeTypes.includes(comp.type);\n\n return isCorrectAnchor && isVisible && included && !excluded;\n })\n .sort((a, b) => a.anchor_order - b.anchor_order); // Sort by anchor_order\n }, [anchor, components, includeTypes, excludeTypes]);\n\n if (!componentsForSlot.length) {\n rebuyDebugLog.log(DebugKey.SC_ANCHOR_SLOT, `AnchorSlot: No components for anchor \"${anchor}\" with filters`, {\n excludeTypes,\n includeTypes,\n });\n\n return null; // Render nothing if no matching components\n }\n\n // rebuyDebugLog.log(DebugKey.SC_ANCHOR_SLOT, `AnchorSlot: Rendering ${componentsForSlot.length} components for anchor \"${anchor}\"`, componentsForSlot);\n\n return (\n <>\n {componentsForSlot.map((componentConfig) => {\n const Component = componentRegistry[componentConfig.type];\n\n if (!Component) {\n console.warn(`[SmartCartReact] No component registered for type: \"${componentConfig.type}\"`);\n\n return null; // Skip rendering if component type is unknown\n }\n\n // rebuyDebugLog.log(DebugKey.SC_ANCHOR_SLOT, `AnchorSlot: Rendering component ${componentConfig.type} (ID: ${componentConfig.component_id})`);\n return <Component componentConfig={componentConfig} key={componentConfig.component_id} />;\n })}\n </>\n );\n};\n", "import DOMPurify from 'dompurify';\nimport React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\nimport { ScreenReaderText } from '~/smart-cart/components/ScreenReaderText/ScreenReaderText';\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport type { AnnouncementBarSettings, SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\n\nimport styles from './AnnouncementBar.module.css';\n\n/* eslint-disable-next-line no-restricted-imports */\n\nconst AUTOPLAY_INTERVAL = 5_000; // Default interval (milliseconds)\nconst DRAG_THRESHOLD = 50; // Min pixels to drag to trigger slide change\n\n/**\n * Renders a rotating announcement bar based on configuration settings.\n * Uses a simple timer-based carousel.\n */\nexport const AnnouncementBar = React.memo(({ componentConfig }: { componentConfig: SmartCartComponentConfig }) => {\n const { isVisible } = useSmartCart();\n const [currentSlideIndex, setCurrentSlideIndex] = useState(0);\n const [isPaused, setIsPaused] = useState(false);\n const [isFocused, setIsFocused] = useState(false);\n const intervalRef = useRef<NodeJS.Timeout | null>(null);\n const containerRef = useRef<HTMLDivElement>(null);\n\n const [isDragging, setIsDragging] = useState(false);\n const [startX, setStartX] = useState(0);\n const [dragOffset, setDragOffset] = useState(0);\n\n const sanitizedMessages = useMemo(() => {\n const settings = componentConfig?.settings as AnnouncementBarSettings;\n const rawMessages = settings?.messages ?? [];\n\n if (!Array.isArray(rawMessages)) {\n console.warn('AnnouncementBar: messages configuration is not an array.', componentConfig);\n\n return [];\n }\n\n return rawMessages\n .filter((msg): msg is string => typeof msg === 'string' && msg.trim() !== '')\n .map((msg) => DOMPurify.sanitize(msg));\n }, [componentConfig]);\n\n const messageCount = sanitizedMessages.length;\n const isCarousel = messageCount >= 2;\n\n const clearTimer = useCallback(() => {\n if (intervalRef.current) {\n clearInterval(intervalRef.current);\n intervalRef.current = null;\n }\n }, []);\n\n const startTimer = useCallback(() => {\n clearTimer();\n\n // ! Note: This implementation moves the slides right, then resets by going back to the first slide (left).\n // ! In a future implementation, we can implement fade in/out transitions between slides, using something lightweight like react-transition-group.\n // TODO: Implement fade in/out transitions between slides, or looping behavior using clones (so the slides move in one direction).\n\n if (!isPaused && isVisible && isCarousel && !isFocused && !isDragging) {\n intervalRef.current = setInterval(() => {\n setCurrentSlideIndex((prevIndex) => (prevIndex + 1) % messageCount);\n }, AUTOPLAY_INTERVAL);\n }\n }, [clearTimer, isPaused, isVisible, isCarousel, messageCount, isFocused, isDragging]);\n\n const goToSlide = useCallback(\n (index: number) => {\n setCurrentSlideIndex((index + messageCount) % messageCount);\n },\n [messageCount]\n );\n\n useEffect(() => {\n startTimer();\n\n return clearTimer;\n }, [startTimer, isPaused, isVisible, isFocused]);\n\n useEffect(() => {\n if (!isVisible) {\n setCurrentSlideIndex(0);\n setIsPaused(false);\n setIsFocused(false);\n }\n }, [isVisible]);\n\n const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (!isCarousel) return;\n switch (event.key) {\n case 'ArrowLeft':\n event.preventDefault();\n goToSlide(currentSlideIndex - 1);\n setIsPaused(true);\n break;\n case 'ArrowRight':\n event.preventDefault();\n goToSlide(currentSlideIndex + 1);\n setIsPaused(true);\n break;\n case ' ':\n case 'Enter':\n event.preventDefault();\n setIsPaused((prevPaused) => !prevPaused);\n break;\n default:\n break;\n }\n };\n\n const handleFocus = () => setIsFocused(true);\n const handleBlur = () => setIsFocused(false);\n const handleMouseEnter = () => {\n if (isCarousel) setIsFocused(true);\n };\n const handleMouseLeave = () => {\n if (isCarousel) setIsFocused(false);\n };\n\n const handlePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {\n if (!isCarousel || !containerRef.current) return;\n setStartX(e.clientX);\n setIsDragging(true);\n setIsPaused(true);\n containerRef.current.style.cursor = 'grabbing';\n containerRef.current.setPointerCapture(e.pointerId);\n };\n\n const handlePointerMove = (e: React.PointerEvent<HTMLDivElement>) => {\n if (!isDragging || !isCarousel) return;\n e.preventDefault();\n setDragOffset(e.clientX - startX);\n };\n\n const handlePointerUpOrLeave = (e: React.PointerEvent<HTMLDivElement>) => {\n if (!isDragging || !isCarousel || !containerRef.current) return;\n try {\n containerRef.current.releasePointerCapture(e.pointerId);\n } catch (error) {\n /* Ignored */\n }\n setIsDragging(false);\n containerRef.current.style.cursor = 'grab';\n\n if (Math.abs(dragOffset) > DRAG_THRESHOLD) {\n if (dragOffset < 0) goToSlide(currentSlideIndex + 1);\n else goToSlide(currentSlideIndex - 1);\n }\n\n setDragOffset(0);\n };\n\n if (messageCount === 0) return null;\n\n const componentId = componentConfig.component_id;\n\n if (!isCarousel) {\n return (\n <div\n className={styles['rebuy-announcement-bar__static-message']}\n dangerouslySetInnerHTML={{ __html: sanitizedMessages[0] }}\n data-rebuy-component=\"announcement-bar\"\n data-rebuy-component-id={componentId}\n />\n );\n }\n\n return (\n <div\n aria-label={`Announcements (${isPaused ? 'Paused' : 'Playing'}). Use Left/Right arrows or swipe to navigate, Space/Enter to pause/play.`}\n aria-roledescription=\"carousel\"\n className={styles['rebuy-announcement-bar__container']}\n data-rebuy-component=\"announcement-bar\"\n data-rebuy-component-id={componentId}\n onBlur={handleBlur}\n onFocus={handleFocus}\n onKeyDown={handleKeyDown}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n onPointerDown={handlePointerDown}\n onPointerLeave={handlePointerUpOrLeave}\n onPointerMove={handlePointerMove}\n onPointerUp={handlePointerUpOrLeave}\n ref={containerRef}\n role=\"region\"\n style={{ touchAction: 'pan-y' }}\n tabIndex={0}\n >\n <ScreenReaderText aria-atomic=\"true\" aria-live=\"polite\">\n Announcement {currentSlideIndex + 1} of {messageCount}:{' '}\n {sanitizedMessages[currentSlideIndex]?.replace(/<[^>]*>?/gm, '') ?? ''}\n </ScreenReaderText>\n <div\n aria-hidden=\"true\"\n className={styles['rebuy-announcement-bar__message-wrapper']}\n style={{\n cursor: isDragging ? 'grabbing' : 'grab',\n transform: `translateX(calc(-${currentSlideIndex * 100}% + ${dragOffset}px))`,\n transition: isDragging ? 'none' : 'transform 0.5s ease-in-out',\n }}\n >\n {sanitizedMessages.map((message, index) => (\n <div\n className={styles['rebuy-announcement-bar__message-item']}\n dangerouslySetInnerHTML={{ __html: message }}\n key={`${componentId}-msg-${index}`}\n />\n ))}\n </div>\n </div>\n );\n});\nAnnouncementBar.displayName = 'AnnouncementBar';\n", "import type React from 'react';\nimport './ScreenReaderText.css';\n\ntype ScreenReaderTextProps = {\n children: React.ReactNode;\n};\n\nexport const ScreenReaderText = ({ children, ...props }: ScreenReaderTextProps) => (\n <span className=\"rebuy-sr-only\" {...props}>\n {children}\n </span>\n);\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/smart-cart/components/AnnouncementBar/AnnouncementBar.css\";\n const result = {\"rebuy-announcement-bar__container\":\"AnnouncementBar_rebuy-announcement-bar__container\",\"rebuy-announcement-bar__message-wrapper\":\"AnnouncementBar_rebuy-announcement-bar__message-wrapper\",\"rebuy-announcement-bar__message-item\":\"AnnouncementBar_rebuy-announcement-bar__message-item\",\"rebuy-announcement-bar__static-message\":\"AnnouncementBar_rebuy-announcement-bar__static-message\"};\n export default result;\n ", "import clsx from 'clsx';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { useFetcher } from 'react-router';\n\nimport { RebuyLink } from '~/components/RebuyLink';\nimport { ScreenReaderText } from '~/smart-cart/components/ScreenReaderText/ScreenReaderText';\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport { useCartItemFeatures } from '~/smart-cart/hooks/useCartItemFeatures';\nimport type { StorefrontCartLine } from '~/smart-cart/types/rebuy-storefront-cart';\nimport {\n getBundleOptionImage,\n getChildBundleTitle,\n getItemPropertyKeyClass,\n getItemPropertyValueClass,\n} from '~/smart-cart/utils/cartItemUtils';\nimport { sizeImage } from '~/smart-cart/utils/imageUtils';\nimport type { JsonValue } from '~/types/common';\n\n/* eslint-disable-next-line no-restricted-imports */\nimport styles from './CartItem.module.css';\n\nconst Spinner: React.FC<{ className?: string }> = ({ className }) => (\n <span className={clsx(styles['rebuy-cart-item__spinner'], className)}></span>\n);\n\ntype CartItemProps = {\n line: StorefrontCartLine;\n};\n\nexport const CartItem: React.FC<CartItemProps> = ({ line }) => {\n const { config, isCartBusy, isHydrogenReact, removeItem, updateItem } = useSmartCart();\n\n const itemFetcher = useFetcher<{ cart?: StorefrontCartLine; error?: string }>();\n\n // Local intent states for spinners\n const [isIncreasing, setIsIncreasing] = useState(false);\n const [isDecreasing, setIsDecreasing] = useState(false);\n const [isRemoving, setIsRemoving] = useState(false);\n const [isAdjustingBMSM, setIsAdjustingBMSM] = useState(false);\n const [isSwitchingSubscription, setIsSwitchingSubscription] = useState(false);\n const [switchingDirection, setSwitchingDirection] = useState<'upgrading' | 'downgrading' | null>(null);\n const { toggleCart } = useSmartCart();\n\n const {\n actions: itemActionsLogic,\n bmsm,\n bundle,\n isBundleExpanded,\n meta,\n pricing,\n properties,\n shouldHideQuantitySelector,\n sts,\n } = useCartItemFeatures({ config, line });\n\n // TODO: Update Query data in Hydrogen to support Selling Plan allocations\n\n const isLoadingCombined = useMemo(() => {\n // If isCartBusy is true, it's a global lock.\n // This covers H-React general loading AND TPB gift processing.\n if (isCartBusy) {\n return true;\n }\n\n // If not globally busy, consider local states for this specific item:\n // 1. For Remix: if this item's fetcher is active.\n if (!isHydrogenReact && itemFetcher.state !== 'idle') {\n return true;\n }\n\n // 2. For both: if any local intent spinner for *this item* is active.\n // These provide immediate feedback before isCartBusy might reflect the start of an operation.\n if (isIncreasing || isDecreasing || isRemoving || isAdjustingBMSM || isSwitchingSubscription) {\n return true;\n }\n\n return false;\n }, [\n isCartBusy,\n isHydrogenReact,\n itemFetcher.state,\n isIncreasing,\n isDecreasing,\n isRemoving,\n isAdjustingBMSM,\n isSwitchingSubscription,\n ]);\n\n const itemClasses = clsx(\n styles['rebuy-cart-item'],\n meta.baseCssClasses,\n meta.tagCssClasses,\n meta.attributeCssClasses,\n { [styles['rebuy-cart-item--updating']]: isLoadingCombined }\n );\n\n // --- Action Handlers ---\n const handleDecreaseQuantity = useCallback(() => {\n // Removed async\n if (isLoadingCombined) return;\n\n const payload = itemActionsLogic.prepareDecreaseQuantity();\n setIsDecreasing(true); // Set intent immediately\n\n if ('quantity' in payload) {\n // It's an UpdateLinePayload\n if (isHydrogenReact) {\n updateItem(payload.lineId, { attributes: payload.attributes, quantity: payload.quantity });\n } else {\n itemFetcher.submit(\n {\n action: 'cartLinesUpdate',\n data: {\n lines: [{ attributes: payload.attributes, id: payload.lineId, quantity: payload.quantity }],\n },\n } as JsonValue,\n { action: '/cart', encType: 'application/json', method: 'POST' }\n );\n }\n } else {\n // It's a RemoveLinePayload\n setIsRemoving(true); // Also set removing intent if quantity becomes 0\n setIsDecreasing(false); // Clear decreasing intent\n\n if (isHydrogenReact) {\n removeItem(payload.lineId);\n } else {\n itemFetcher.submit(\n {\n action: 'cartLinesRemove',\n data: { lineIds: [payload.lineId] },\n },\n { action: '/cart', encType: 'application/json', method: 'POST' }\n );\n }\n }\n }, [isLoadingCombined, itemActionsLogic, isHydrogenReact, updateItem, removeItem, itemFetcher]);\n\n const handleIncreaseQuantity = useCallback(() => {\n // Removed async\n if (isLoadingCombined) return;\n setIsIncreasing(true);\n\n const payload = itemActionsLogic.prepareIncreaseQuantity();\n\n if (isHydrogenReact) {\n updateItem(payload.lineId, { attributes: payload.attributes, quantity: payload.quantity });\n } else {\n itemFetcher.submit(\n {\n action: 'cartLinesUpdate',\n data: {\n lines: [{ attributes: payload.attributes, id: payload.lineId, quantity: payload.quantity }],\n },\n } as JsonValue,\n { action: '/cart', encType: 'application/json', method: 'POST' }\n );\n }\n }, [isLoadingCombined, itemActionsLogic, isHydrogenReact, updateItem, itemFetcher]);\n\n const handleRemoveItem = useCallback(() => {\n // Removed async\n if (isLoadingCombined) return;\n setIsRemoving(true);\n\n const payload = itemActionsLogic.prepareRemoveItem();\n\n if (isHydrogenReact) {\n removeItem(payload.lineId);\n } else {\n itemFetcher.submit(\n {\n action: 'cartLinesRemove',\n data: { lineIds: [payload.lineId] },\n },\n { action: '/cart', encType: 'application/json', method: 'POST' }\n );\n }\n }, [isLoadingCombined, itemActionsLogic, isHydrogenReact, removeItem, itemFetcher]);\n\n const handleAdjustBMSMQuantity = useCallback(\n (tierQuantity: number) => {\n // Removed async\n if (isLoadingCombined) return;\n\n const payload = itemActionsLogic.prepareAdjustBMSMQuantity(tierQuantity);\n\n if (!payload) return;\n setIsAdjustingBMSM(true);\n\n if (isHydrogenReact) {\n updateItem(payload.lineId, { attributes: payload.attributes, quantity: payload.quantity });\n } else {\n itemFetcher.submit(\n {\n action: 'cartLinesUpdate',\n data: {\n lines: [{ attributes: payload.attributes, id: payload.lineId, quantity: payload.quantity }],\n },\n } as JsonValue,\n { action: '/cart', encType: 'application/json', method: 'POST' }\n );\n }\n },\n [isLoadingCombined, itemActionsLogic, isHydrogenReact, updateItem, itemFetcher]\n );\n\n const handleSwitchSubscriptionChange = useCallback(\n (event: React.ChangeEvent<HTMLSelectElement>) => {\n // Removed async\n if (isLoadingCombined) return;\n\n const targetValue = event.target.value;\n const targetSellingPlanId = targetValue === 'onetime' ? null : targetValue;\n\n setSwitchingDirection(\n targetSellingPlanId === null && sts.isCurrentlySubscription\n ? 'downgrading'\n : targetSellingPlanId !== null && !sts.isCurrentlySubscription\n ? 'upgrading'\n : null\n );\n setIsSwitchingSubscription(true);\n\n const payload = itemActionsLogic.prepareSubscriptionSwitch(targetSellingPlanId);\n\n if (isHydrogenReact) {\n updateItem(payload.lineId, { attributes: payload.attributes, sellingPlanId: payload.sellingPlanId });\n } else {\n itemFetcher.submit(\n {\n action: 'cartLinesUpdate',\n data: {\n lines: [\n {\n attributes: payload.attributes,\n id: payload.lineId,\n sellingPlanId: payload.sellingPlanId,\n },\n ],\n },\n } as JsonValue,\n { action: '/cart', encType: 'application/json', method: 'POST' }\n );\n }\n },\n [isLoadingCombined, itemActionsLogic, isHydrogenReact, updateItem, itemFetcher, sts.isCurrentlySubscription]\n );\n\n const handleUpgradeToSubscriptionClick = useCallback(() => {\n // Renamed and removed async\n if (isLoadingCombined || sts.isCurrentlySubscription || sts.availableFrequencies.length === 0) return;\n\n const defaultFrequencyId = sts.availableFrequencies[0].id;\n\n if (!defaultFrequencyId) return;\n\n setSwitchingDirection('upgrading');\n setIsSwitchingSubscription(true);\n\n const payload = itemActionsLogic.prepareSubscriptionSwitch(defaultFrequencyId);\n\n if (isHydrogenReact) {\n updateItem(payload.lineId, { attributes: payload.attributes, sellingPlanId: payload.sellingPlanId });\n } else {\n itemFetcher.submit(\n {\n action: 'cartLinesUpdate',\n data: {\n lines: [\n {\n attributes: payload.attributes,\n id: payload.lineId,\n sellingPlanId: payload.sellingPlanId,\n },\n ],\n },\n } as JsonValue,\n { action: '/cart', encType: 'application/json', method: 'POST' }\n );\n }\n }, [\n isLoadingCombined,\n itemActionsLogic,\n isHydrogenReact,\n updateItem,\n itemFetcher,\n sts.isCurrentlySubscription,\n sts.availableFrequencies,\n ]);\n\n // Effect to reset local loading states\n useEffect(() => {\n const resetLocalSpinners = () => {\n setIsIncreasing(false);\n setIsDecreasing(false);\n setIsRemoving(false);\n setIsAdjustingBMSM(false);\n setIsSwitchingSubscription(false);\n setSwitchingDirection(null);\n };\n\n if (isHydrogenReact) {\n // isCartBusy includes the H-React global loading state.\n // If isCartBusy is false, it implies H-React global loading is also false.\n if (!isCartBusy) {\n resetLocalSpinners();\n }\n } else {\n if (itemFetcher.state === 'idle') {\n resetLocalSpinners(); // Reset when item's own fetcher is idle\n\n if (itemFetcher.data?.error) {\n console.error('CartItem Action Error (Remix):', itemFetcher.data.error);\n // TODO: Display this error in the UI, perhaps via a local state or a toast\n }\n }\n }\n }, [isHydrogenReact, isCartBusy, itemFetcher.state, itemFetcher.data]);\n\n const selectValue = line.sellingPlanAllocation?.sellingPlan.id ?? 'onetime';\n\n return (\n <li\n aria-label={meta.ariaLabel}\n className={itemClasses}\n data-line-id={line.id}\n data-variant-id={line.merchandise.id}\n >\n {/* Media (Image/Link) */}\n <div className={styles['rebuy-cart-item__media']}>\n <RebuyLink\n ariaLabel={meta.linkLabel}\n handle={meta.itemUrl}\n onClick={() => {\n toggleCart();\n }}\n >\n <img alt={meta.imageAltText} height={120} loading=\"lazy\" src={meta.imageUrl} width={120} />\n </RebuyLink>\n </div>\n {/* Item Info */}\n <div className={styles['rebuy-cart-item__info']}>\n <RebuyLink\n ariaLabel={meta.linkLabel}\n className={styles['rebuy-cart-item__product-title']}\n handle={meta.itemUrl}\n onClick={() => {\n toggleCart();\n }}\n role=\"heading\"\n >\n {meta.productTitle}\n </RebuyLink>\n {meta.variantTitle && (\n <div className={styles['rebuy-cart-item__variant-title']}>{meta.variantTitle}</div>\n )}\n\n {properties.hasVisibleProperties && (\n <div className={styles['rebuy-cart-item__properties-list']}>\n {properties.deliveryFrequency && (\n <div\n className={clsx(\n styles['rebuy-cart-item__property'],\n styles['rebuy-cart-item__property--delivery-frequency']\n )}\n >\n {properties.deliveryFrequency}\n </div>\n )}\n {properties.visibleProperties.map((prop, index) => (\n <div\n className={clsx(\n styles['rebuy-cart-item__property'],\n getItemPropertyKeyClass(prop),\n getItemPropertyValueClass(prop)\n )}\n key={`${line.id}-prop-${index}`}\n >\n {prop.key !== '_Discount' ? (\n <>\n <span className={styles['rebuy-cart-item__property-key']}>{prop.key}</span>\n <span className={styles['rebuy-cart-item__property-separator']}>: </span>\n <span className={styles['rebuy-cart-item__property-value']}>{prop.value}</span>\n </>\n ) : (\n <span className={styles['rebuy-cart-item__property-value']}>{prop.value}</span>\n )}\n </div>\n ))}\n </div>\n )}\n\n <button\n aria-label={`Remove ${meta.productTitle}`}\n className={styles['rebuy-cart-item__remove-button']}\n disabled={isLoadingCombined}\n onClick={handleRemoveItem}\n type=\"button\"\n >\n {isRemoving ? <Spinner /> : '\u2715'}\n </button>\n\n {!shouldHideQuantitySelector && (\n <div className={styles['rebuy-cart-item__quantity-selector-area']}>\n <div className={styles['rebuy-cart-item__quantity-selector']}>\n <button\n aria-label={`Decrease quantity of ${meta.productTitle}`}\n className={styles['rebuy-cart-item__quantity-selector-button']}\n disabled={isLoadingCombined}\n onClick={handleDecreaseQuantity}\n type=\"button\"\n >\n {isDecreasing ? <Spinner /> : '-'}\n </button>\n <span aria-live=\"polite\" className={styles['rebuy-cart-item__quantity-selector-label']}>\n <ScreenReaderText>Quantity of {meta.productTitle}</ScreenReaderText>\n {line.quantity}\n </span>\n <button\n aria-label={`Increase quantity of ${meta.productTitle}`}\n className={styles['rebuy-cart-item__quantity-selector-button']}\n disabled={isLoadingCombined}\n onClick={handleIncreaseQuantity}\n type=\"button\"\n >\n {isIncreasing ? <Spinner /> : '+'}\n </button>\n </div>\n </div>\n )}\n\n <div className={styles['rebuy-cart-item__price-details']}>\n {pricing.hasDiscount && pricing.compareAtDisplayPrice ? (\n <>\n <span\n aria-label=\"Sale price\"\n className={clsx(\n styles['rebuy-cart-item__money'],\n styles['rebuy-cart-item__money--sale']\n )}\n >\n <ScreenReaderText>Sale price</ScreenReaderText>\n {pricing.displayPrice}\n </span>\n <span\n aria-label=\"Original price\"\n className={clsx(\n styles['rebuy-cart-item__money'],\n styles['rebuy-cart-item__money--compare-at']\n )}\n >\n <ScreenReaderText>Original price</ScreenReaderText>\n {pricing.compareAtDisplayPrice}\n </span>\n </>\n ) : (\n <span aria-label=\"Price\" className={styles['rebuy-cart-item__money']}>\n <ScreenReaderText>Price</ScreenReaderText>\n {pricing.displayPrice}\n </span>\n )}\n </div>\n\n {bundle.isBundleParent && bundle.showToggle && (\n <div className={styles['rebuy-cart-item__bundle-section']}>\n {bundle.itemCount > 0 && (\n <button\n aria-controls={`bundle-details-${line.id}`}\n aria-expanded={isBundleExpanded}\n aria-label={`${isBundleExpanded ? 'Collapse' : 'Expand'} bundle details for ${meta.productTitle}`}\n className={styles['rebuy-cart-item__bundle-toggle-button']}\n disabled={isLoadingCombined}\n onClick={itemActionsLogic.toggleBundle}\n type=\"button\"\n >\n {isBundleExpanded ? 'Hide' : 'Show'} {bundle.itemCount} item\n {bundle.itemCount !== 1 ? 's' : ''}\n <span aria-hidden=\"true\" className={styles['rebuy-cart-item__bundle-chev-icon']}>\n {isBundleExpanded ? '\u25B2' : '\u25BC'}\n </span>\n </button>\n )}\n {bundle.itemCount > 0 && isBundleExpanded && (\n <ul\n className={styles['rebuy-cart-item__bundle-children-list']}\n id={`bundle-details-${line.id}`}\n tabIndex={-1}\n >\n {Array.from({ length: bundle.itemCount }).map((_, index) => {\n const optionData = { name: 'Placeholder Option', value: 'Details...' }; // Replace with actual data\n const childTitle = getChildBundleTitle(optionData);\n const childImage = getBundleOptionImage(\n line.merchandise.product,\n optionData,\n index\n ); // Pass product\n\n return (\n <li\n className={styles['rebuy-cart-item__bundle-child-item']}\n key={`${line.id}-bundle-child-${index}`}\n >\n <div className={styles['rebuy-cart-item__bundle-child-media-wrapper']}>\n <div className={styles['rebuy-cart-item__bundle-child-image-wrapper']}>\n <img\n alt={childTitle}\n className={styles['rebuy-cart-item__bundle-child-image']}\n loading=\"lazy\"\n src={sizeImage(childImage, '40x40')}\n />\n </div>\n </div>\n <div className={styles['rebuy-cart-item__bundle-child-details']}>\n <h5 className={styles['rebuy-cart-item__bundle-child-title']}>\n {childTitle}\n </h5>\n </div>\n </li>\n );\n })}\n </ul>\n )}\n </div>\n )}\n </div>{' '}\n {/* End Item Info */}\n {bmsm.isEnabledAndApplicable && (\n <div className={styles['rebuy-cart-item__bmsm-section']}>\n {bmsm.isButtonMode ? (\n <div className={styles['rebuy-cart-item__bmsm-button-wrapper']}>\n {bmsm.nextApplicableTiers.map((tier) => (\n <button\n aria-label={`${bmsm.getButtonText(tier)} for ${meta.productTitle}`}\n className={styles['rebuy-cart-item__bmsm-button']}\n disabled={isLoadingCombined}\n key={`bmsm-${line.id}-${tier.quantity}`}\n onClick={() => handleAdjustBMSMQuantity(tier.quantity ?? 0)}\n >\n <span>{bmsm.getButtonText(tier)}</span>\n </button>\n ))}\n </div>\n ) : (\n <span className={styles['rebuy-cart-item__bmsm-dynamic-message']}>{bmsm.dynamicText}</span>\n )}\n </div>\n )}\n {sts.isEnabledAndApplicable && (\n <div className={styles['rebuy-cart-item__sts-section']}>\n {!sts.isCurrentlySubscription && sts.availableFrequencies.length > 0 ? (\n <button\n aria-label={`Switch ${meta.productTitle} to a Subscription`}\n className={styles['rebuy-cart-item__sts-action-button']}\n disabled={isLoadingCombined}\n onClick={handleUpgradeToSubscriptionClick}\n type=\"button\"\n >\n {isSwitchingSubscription && switchingDirection === 'upgrading' ? (\n <Spinner />\n ) : (\n <span>{sts.getUpgradeButtonLabel()}</span>\n )}\n </button>\n ) : sts.isCurrentlySubscription || sts.canDowngrade ? (\n <>\n {isSwitchingSubscription ? (\n <span className={styles['rebuy-cart-item__sts-loading-replacement']}>\n {sts.getLoadingLabel(switchingDirection)}\n </span>\n ) : (\n <select\n aria-label={`Subscription delivery frequency for ${meta.productTitle}`}\n className={styles['rebuy-cart-item__sts-select']}\n disabled={isLoadingCombined}\n onChange={handleSwitchSubscriptionChange}\n value={selectValue}\n >\n {sts.canDowngrade && (\n <optgroup label={sts.getOneTimeGroupLabel()}>\n <option value=\"onetime\">{sts.getOneTimeLabel()}</option>\n </optgroup>\n )}\n {sts.availableFrequencies.length > 0 && (\n <optgroup label={sts.getGroupLabel()}>\n {sts.availableFrequencies.map((freq) => (\n <option key={freq.id} value={freq.id}>\n {sts.getOptionLabel(freq.id)}\n </option>\n ))}\n </optgroup>\n )}\n </select>\n )}\n </>\n ) : null}\n </div>\n )}\n </li>\n );\n};\n", "import { Link } from 'react-router';\nimport type { RebuyLinkProps } from './types';\n\nexport const RebuyLink = ({ ariaLabel, children, className, handle, onClick, role = 'link' }: RebuyLinkProps) => {\n return (\n <Link aria-label={ariaLabel} className={className} onClick={onClick} rel=\"nofollow\" role={role} to={handle}>\n {children}\n </Link>\n );\n};\n", "/* eslint-disable jsdoc/require-param, jsdoc/require-returns */\n\nimport type { AttributeInput as HRAttributeInput } from '@shopify/hydrogen-react/storefront-api-types';\nimport { useCallback, useMemo, useState } from 'react';\nimport { DebugKey } from '~/constants/debug';\n\nimport { LineItemAttributeKey, RebuyLineItemAttribution } from '~/smart-cart/constants';\nimport type {\n StorefrontAttribute,\n StorefrontCartLine,\n StorefrontProduct,\n} from '~/smart-cart/types/rebuy-storefront-cart';\nimport type {\n BuyMoreSaveMoreTier as BmsmTier,\n SmartCartConfig,\n SwitchToSubscriptionLanguage,\n} from '~/smart-cart/types/smart-cart';\nimport {\n bMSMFinalTierNotReached,\n buyMoreSaveMoreDynamicText,\n calculateDefaultSellingPlanDiscount,\n calculatePricingData,\n getAvailableSellingPlans,\n getBMSMButtonText,\n getBMSMTiers,\n getDiscountProperties,\n getItemAttributeClasses,\n getItemBundleLength,\n getItemDeliveryFrequency,\n getItemImageAlt,\n getItemLinkLabel,\n getItemProductTagsClasses,\n getItemURL,\n getSwitchToSubscriptionLabelWithDiscount,\n getVisibleItemProperties,\n hasBMSMButtons,\n hideBundleOptions,\n isBMSMEnabled,\n isCartItemHiddenByStandardLogic,\n isTieredProgressBarGiftItem,\n itemHasBMSM,\n itemIsBundle,\n mergeAttributes,\n removeAttributes,\n} from '~/smart-cart/utils/cartItemUtils';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport { sizeImage } from '~/smart-cart/utils/imageUtils';\n\n// Helper function to map StorefrontAttribute[] to HRAttributeInput[]\n// Ensures keys/values are strings as required by H-React input type and Storefront API\nexport const mapCartAttributes = (attributes?: StorefrontAttribute[] | null): HRAttributeInput[] => {\n if (!attributes) return [];\n\n return attributes\n .filter((attr): attr is { key: string; value: string } => typeof attr.key === 'string' && attr.value !== null)\n .map((attr) => ({\n key: attr.key,\n value: attr.value,\n }));\n};\n\ntype UseCartItemFeaturesProps = {\n config: SmartCartConfig | null;\n line: StorefrontCartLine;\n};\n\n// Data types returned by \"prepare\" functions\nexport type UpdateLinePayload = {\n attributes?: HRAttributeInput[];\n lineId: string;\n quantity?: number;\n sellingPlanId?: string | null;\n};\nexport type RemoveLinePayload = {\n lineId: string;\n};\n\nexport const useCartItemFeatures = ({ config, line }: UseCartItemFeaturesProps) => {\n const [isBundleExpanded, setIsBundleExpanded] = useState(false);\n\n // --- Memoized Calculations (Derived State) ---\n\n // Meta Info\n const productTitle = useMemo(() => line.merchandise.product.title, [line.merchandise.product.title]);\n const variantTitle = useMemo(\n () => (line.merchandise.title !== 'Default Title' ? line.merchandise.title : null),\n [line.merchandise.title]\n );\n const itemUrl = useMemo(() => getItemURL(line), [line]);\n const imageAltText = useMemo(() => getItemImageAlt(line), [line]);\n const imageUrl = useMemo(() => sizeImage(line.merchandise.image?.url, '120x120'), [line.merchandise.image?.url]);\n const linkLabel = useMemo(() => getItemLinkLabel(line), [line]);\n const tagCssClasses = useMemo(() => getItemProductTagsClasses(line), [line]);\n const attributeCssClasses = useMemo(() => getItemAttributeClasses(line), [line]);\n const baseCssClasses = useMemo(\n () => `product-${line.merchandise.product.handle}`,\n [line.merchandise.product.handle]\n );\n const pricing = useMemo(() => calculatePricingData(line), [line]);\n const deliveryFrequency = useMemo(() => getItemDeliveryFrequency(line), [line]);\n const standardProperties = useMemo(() => getVisibleItemProperties(line), [line]);\n const discountProperties = useMemo(() => getDiscountProperties(line), [line]);\n const allVisibleProperties = useMemo(\n () => [...standardProperties, ...discountProperties],\n [standardProperties, discountProperties]\n );\n const hasVisibleProperties = useMemo(\n () => allVisibleProperties.length > 0 || !!deliveryFrequency,\n [allVisibleProperties, deliveryFrequency]\n );\n const isBundleParent = useMemo(() => itemIsBundle(line), [line]);\n const bundleItemCount = useMemo(() => (isBundleParent ? getItemBundleLength(line) : 0), [isBundleParent, line]);\n const shouldHideBundleOptions = useMemo(() => isBundleParent && hideBundleOptions(line), [isBundleParent, line]);\n const showBundleToggle = useMemo(\n () => isBundleParent && !shouldHideBundleOptions && bundleItemCount > 0,\n [isBundleParent, shouldHideBundleOptions, bundleItemCount]\n );\n const shouldHideQuantitySelector = useMemo((): boolean => {\n if (isTieredProgressBarGiftItem(line)) return true;\n\n if (isCartItemHiddenByStandardLogic(line)) return true;\n\n return false;\n }, [line]);\n\n // BMSM Features\n const isBmsmGloballyEnabled = useMemo(() => isBMSMEnabled(config), [config]);\n const isBmsmEligible = useMemo(\n () => isBmsmGloballyEnabled && itemHasBMSM(line, config),\n [isBmsmGloballyEnabled, line, config]\n );\n const bmsmNotAtFinalTier = useMemo(\n () => isBmsmEligible && bMSMFinalTierNotReached(line, config),\n [isBmsmEligible, line, config]\n );\n const isBmsmEnabledAndApplicable = useMemo(\n () => isBmsmEligible && bmsmNotAtFinalTier,\n [isBmsmEligible, bmsmNotAtFinalTier]\n );\n const isBmsmButtonMode = useMemo(\n () => isBmsmEnabledAndApplicable && hasBMSMButtons(config),\n [isBmsmEnabledAndApplicable, config]\n );\n const bmsmTiers = useMemo(\n () => (isBmsmEnabledAndApplicable ? getBMSMTiers(config) : []),\n [isBmsmEnabledAndApplicable, config]\n );\n const bmsmNextApplicableTiers = useMemo(\n () =>\n isBmsmButtonMode\n ? bmsmTiers\n .filter((tier) => tier.quantity && tier.quantity > line.quantity)\n .sort((a, b) => (a.quantity ?? 0) - (b.quantity ?? 0))\n : [],\n [isBmsmButtonMode, bmsmTiers, line.quantity]\n );\n const bmsmDynamicText = useMemo(\n () => (isBmsmEnabledAndApplicable && !isBmsmButtonMode ? buyMoreSaveMoreDynamicText(line, config) : ''),\n [isBmsmEnabledAndApplicable, isBmsmButtonMode, line, config]\n );\n\n // STS Features\n const isStsGloballyEnabled = useMemo(() => config?.switch_to_subscription_enabled ?? false, [config]);\n const productHasSellingPlans = useMemo(\n () => (line.merchandise.product.sellingPlanGroups?.edges ?? []).length > 0,\n [line.merchandise.product.sellingPlanGroups]\n );\n const isStsEligible = useMemo(\n () => isStsGloballyEnabled && productHasSellingPlans,\n [isStsGloballyEnabled, productHasSellingPlans]\n );\n const isCurrentlySubscription = useMemo(() => !!line.sellingPlanAllocation, [line.sellingPlanAllocation]);\n const productRequiresSellingPlan = useMemo(\n () => (line.merchandise.product as StorefrontProduct).requiresSellingPlan ?? false,\n [line.merchandise.product]\n );\n const downgradeGloballyAllowed = useMemo(\n () => !(config?.switch_to_subscription?.disable_downgrade ?? false),\n [config?.switch_to_subscription?.disable_downgrade]\n );\n const canStsDowngrade = useMemo(\n () => isStsEligible && downgradeGloballyAllowed && !productRequiresSellingPlan,\n [isStsEligible, downgradeGloballyAllowed, productRequiresSellingPlan]\n );\n const stsAvailableFrequencies = useMemo(() => getAvailableSellingPlans(line), [line]);\n const defaultSellingPlanDiscountPercent = useMemo(\n () => calculateDefaultSellingPlanDiscount(stsAvailableFrequencies, line),\n [stsAvailableFrequencies, line]\n );\n const isStsEnabledAndApplicable = useMemo(\n () =>\n isStsEligible &&\n (canStsDowngrade ||\n stsAvailableFrequencies.length > 1 ||\n (!isCurrentlySubscription && stsAvailableFrequencies.length > 0)),\n [isStsEligible, canStsDowngrade, stsAvailableFrequencies.length, isCurrentlySubscription]\n );\n const getStsLabel = useCallback(\n // This remains as it's for UI text\n (key: keyof SwitchToSubscriptionLanguage, fallback?: string): string => {\n const labelTemplate = config?.switch_to_subscription?.language?.[key] ?? fallback ?? key.toString();\n const discount = defaultSellingPlanDiscountPercent;\n\n if (\n (key === 'upgrade_to_subscription_label' || key === 'subscription_option_group_label') &&\n discount > 0\n ) {\n return labelTemplate.replace('{{subscription_discount}}', discount.toString());\n }\n\n return labelTemplate;\n },\n [config?.switch_to_subscription?.language, defaultSellingPlanDiscountPercent]\n );\n\n // --- Payload Preparation \"Actions\" (Callbacks) ---\n\n const prepareDecreaseQuantity = useCallback((): UpdateLinePayload | RemoveLinePayload => {\n const newQuantity = line.quantity - 1;\n\n if (newQuantity <= 0) {\n rebuyDebugLog.log(DebugKey.SC_CART_ITEM_FEATURES, `Preparing remove for ${line.id} (qty became 0).`);\n\n return { lineId: line.id };\n }\n let finalAttributes: StorefrontAttribute[] | undefined = undefined;\n const currentAttributes = line.attributes;\n const currentBmsmAttr = currentAttributes?.find(\n (a) => a.key === LineItemAttributeKey.ATTRIBUTION && a.value === RebuyLineItemAttribution.BUY_MORE_SAVE_MORE\n );\n\n if (currentBmsmAttr) {\n const bmsmTiers = getBMSMTiers(config);\n\n if (bmsmTiers.length > 0) {\n const minBmsmQuantity = Math.min(...bmsmTiers.map((t) => t.quantity ?? Infinity));\n\n if (newQuantity < minBmsmQuantity) {\n finalAttributes = removeAttributes(currentAttributes, [\n LineItemAttributeKey.SOURCE,\n LineItemAttributeKey.ATTRIBUTION,\n ]);\n }\n } else {\n finalAttributes = removeAttributes(currentAttributes, [\n LineItemAttributeKey.SOURCE,\n LineItemAttributeKey.ATTRIBUTION,\n ]);\n }\n }\n const finalAttributesInput = mapCartAttributes(finalAttributes);\n rebuyDebugLog.log(DebugKey.SC_CART_ITEM_FEATURES, `Preparing decrease qty for ${line.id} to ${newQuantity}.`);\n\n return { attributes: finalAttributesInput, lineId: line.id, quantity: newQuantity };\n }, [line, config]);\n\n const prepareIncreaseQuantity = useCallback((): UpdateLinePayload => {\n const newQuantity = line.quantity + 1;\n let finalAttributes: StorefrontAttribute[] | undefined = undefined;\n const currentAttributes = line.attributes;\n const isEligibleForBmsm = itemHasBMSM(line, config);\n const hasBmsmAttr = currentAttributes?.some(\n (a) => a.key === LineItemAttributeKey.ATTRIBUTION && a.value === RebuyLineItemAttribution.BUY_MORE_SAVE_MORE\n );\n\n if (isEligibleForBmsm && !hasBmsmAttr) {\n const bmsmTiers = getBMSMTiers(config);\n\n if (bmsmTiers.length > 0) {\n const minBmsmQuantity = Math.min(...bmsmTiers.map((t) => t.quantity ?? Infinity));\n\n if (newQuantity >= minBmsmQuantity) {\n const bmsmAttributesToAdd: StorefrontAttribute[] = [\n { key: LineItemAttributeKey.SOURCE, value: 'Rebuy' },\n { key: LineItemAttributeKey.ATTRIBUTION, value: RebuyLineItemAttribution.BUY_MORE_SAVE_MORE },\n ];\n finalAttributes = mergeAttributes(currentAttributes, bmsmAttributesToAdd);\n }\n }\n }\n const finalAttributesInput = mapCartAttributes(finalAttributes);\n rebuyDebugLog.log(DebugKey.SC_CART_ITEM_FEATURES, `Preparing increase qty for ${line.id} to ${newQuantity}.`);\n\n return { attributes: finalAttributesInput, lineId: line.id, quantity: newQuantity };\n }, [line, config]);\n\n const prepareRemoveItem = useCallback((): RemoveLinePayload => {\n rebuyDebugLog.log(DebugKey.SC_CART_ITEM_FEATURES, `Preparing remove for ${line.id}.`);\n\n return { lineId: line.id };\n }, [line.id]);\n\n const prepareAdjustBMSMQuantity = useCallback(\n (tierQuantity: number): UpdateLinePayload | null => {\n if (tierQuantity === line.quantity) return null;\n\n const currentAttributes = line.attributes;\n const bmsmAttributes: StorefrontAttribute[] = [\n { key: LineItemAttributeKey.SOURCE, value: 'Rebuy' },\n {\n key: LineItemAttributeKey.ATTRIBUTION,\n value: RebuyLineItemAttribution.BUY_MORE_SAVE_MORE,\n },\n ];\n const finalAttributes = mergeAttributes(currentAttributes, bmsmAttributes);\n const finalAttributesInput = mapCartAttributes(finalAttributes);\n rebuyDebugLog.log(\n DebugKey.SC_CART_ITEM_FEATURES,\n `Preparing BMSM qty adjustment for ${line.id} to ${tierQuantity}.`\n );\n\n return { attributes: finalAttributesInput, lineId: line.id, quantity: tierQuantity };\n },\n [line]\n );\n\n const toggleBundle = useCallback(() => {\n setIsBundleExpanded((prev) => !prev);\n }, []);\n\n const prepareSubscriptionSwitch = useCallback(\n (targetSellingPlanId: string | null): UpdateLinePayload => {\n const currentAttributes = line.attributes;\n let finalAttributesArray: StorefrontAttribute[] | undefined = undefined;\n const hasBmsmAttr = currentAttributes?.some(\n (a) =>\n a.key === LineItemAttributeKey.ATTRIBUTION &&\n a.value === RebuyLineItemAttribution.BUY_MORE_SAVE_MORE\n );\n\n if (!hasBmsmAttr) {\n let newAttributionValue: string | null = null;\n let isSubscriptionStateChange = false;\n\n if (targetSellingPlanId === null && isCurrentlySubscription) {\n newAttributionValue = RebuyLineItemAttribution.SWITCH_TO_ONE_TIME;\n isSubscriptionStateChange = true;\n } else if (targetSellingPlanId !== null && !isCurrentlySubscription) {\n newAttributionValue = RebuyLineItemAttribution.SWITCH_TO_SUBSCRIPTION;\n isSubscriptionStateChange = true;\n }\n let keysToRemove: string[] = [];\n\n if (isSubscriptionStateChange) {\n keysToRemove = [LineItemAttributeKey.ATTRIBUTION, LineItemAttributeKey.SOURCE].filter((key) =>\n currentAttributes?.find(\n (attr) =>\n attr.key === key &&\n (attr.value === RebuyLineItemAttribution.SWITCH_TO_SUBSCRIPTION ||\n attr.value === RebuyLineItemAttribution.SWITCH_TO_ONE_TIME ||\n attr.value === 'Rebuy')\n )\n );\n }\n const cleanedAttributes = removeAttributes(currentAttributes, keysToRemove);\n\n if (newAttributionValue) {\n const stsAttributes: StorefrontAttribute[] = [\n { key: LineItemAttributeKey.SOURCE, value: 'Rebuy' },\n { key: LineItemAttributeKey.ATTRIBUTION, value: newAttributionValue },\n ];\n finalAttributesArray = mergeAttributes(cleanedAttributes, stsAttributes);\n } else {\n finalAttributesArray = cleanedAttributes;\n }\n } else {\n finalAttributesArray = currentAttributes;\n }\n const finalAttributesInput = mapCartAttributes(finalAttributesArray);\n rebuyDebugLog.log(\n DebugKey.SC_CART_ITEM_FEATURES,\n `Preparing subscription switch for ${line.id} to plan ${targetSellingPlanId ?? 'one-time'}.`\n );\n\n return { attributes: finalAttributesInput, lineId: line.id, sellingPlanId: targetSellingPlanId };\n },\n [line, isCurrentlySubscription]\n );\n\n // --- Return the hook's public interface ---\n return useMemo(\n () => ({\n actions: {\n prepareAdjustBMSMQuantity,\n prepareDecreaseQuantity,\n prepareIncreaseQuantity,\n prepareRemoveItem,\n prepareSubscriptionSwitch,\n toggleBundle,\n },\n bmsm: {\n dynamicText: bmsmDynamicText,\n getButtonText: (tier: BmsmTier) => getBMSMButtonText(tier, config),\n isButtonMode: isBmsmButtonMode,\n isEnabledAndApplicable: isBmsmEnabledAndApplicable,\n nextApplicableTiers: bmsmNextApplicableTiers,\n },\n bundle: {\n isBundleParent: isBundleParent,\n itemCount: bundleItemCount,\n showToggle: showBundleToggle,\n },\n isBundleExpanded,\n meta: {\n ariaLabel: productTitle,\n attributeCssClasses,\n baseCssClasses,\n imageAltText,\n imageUrl,\n itemUrl,\n linkLabel,\n productTitle,\n tagCssClasses,\n variantTitle,\n },\n pricing: pricing,\n properties: {\n deliveryFrequency,\n hasVisibleProperties,\n visibleProperties: allVisibleProperties,\n },\n shouldHideQuantitySelector,\n sts: {\n availableFrequencies: stsAvailableFrequencies,\n canDowngrade: canStsDowngrade,\n getDowngradingLabel: () =>\n getSwitchToSubscriptionLabelWithDiscount(\n 'downgrading_label',\n config,\n 0,\n 'Switching to One-Time...'\n ),\n getGroupLabel: () =>\n getSwitchToSubscriptionLabelWithDiscount(\n 'subscription_option_group_label',\n config,\n defaultSellingPlanDiscountPercent,\n 'Subscribe & Save {{subscription_discount}}%'\n ),\n getLoadingLabel: (direction?: 'upgrading' | 'downgrading' | null) => {\n const key =\n direction === 'upgrading'\n ? 'upgrading_label'\n : direction === 'downgrading'\n ? 'downgrading_label'\n : '';\n const fallback =\n direction === 'upgrading'\n ? 'Switching to Subscription...'\n : direction === 'downgrading'\n ? 'Switching to One-Time...'\n : 'Updating...';\n\n return key\n ? getSwitchToSubscriptionLabelWithDiscount(\n key as keyof SwitchToSubscriptionLanguage,\n config,\n 0,\n fallback\n )\n : fallback;\n },\n getOneTimeGroupLabel: () =>\n getSwitchToSubscriptionLabelWithDiscount(\n 'onetime_option_group_label',\n config,\n 0,\n 'Purchase Options'\n ),\n getOneTimeLabel: () =>\n getSwitchToSubscriptionLabelWithDiscount('onetime_option_label', config, 0, 'One-Time Purchase'),\n getOptionLabel: (frequencyId: string) => {\n const plan = stsAvailableFrequencies.find((f) => f.id === frequencyId);\n\n return plan?.name ?? frequencyId;\n },\n getUpgradeButtonLabel: () => {\n const key =\n defaultSellingPlanDiscountPercent > 0\n ? 'upgrade_to_subscription_label'\n : 'upgrade_to_subscription_without_discount_label';\n const fallback =\n defaultSellingPlanDiscountPercent > 0\n ? 'Switch & Save {{subscription_discount}}%'\n : 'Switch to Subscription';\n\n return getSwitchToSubscriptionLabelWithDiscount(\n key,\n config,\n defaultSellingPlanDiscountPercent,\n fallback\n );\n },\n getUpgradingLabel: () =>\n getSwitchToSubscriptionLabelWithDiscount(\n 'upgrading_label',\n config,\n 0,\n 'Switching to Subscription...'\n ),\n isCurrentlySubscription: isCurrentlySubscription,\n isEnabledAndApplicable: isStsEnabledAndApplicable,\n },\n }),\n [\n isBundleExpanded,\n prepareIncreaseQuantity,\n prepareDecreaseQuantity,\n prepareRemoveItem,\n prepareAdjustBMSMQuantity,\n toggleBundle,\n prepareSubscriptionSwitch,\n isBmsmEnabledAndApplicable,\n isBmsmButtonMode,\n bmsmNextApplicableTiers,\n config,\n bmsmDynamicText,\n isStsEnabledAndApplicable,\n isCurrentlySubscription,\n canStsDowngrade,\n stsAvailableFrequencies,\n getStsLabel,\n line,\n isBundleParent,\n showBundleToggle,\n bundleItemCount,\n allVisibleProperties,\n deliveryFrequency,\n hasVisibleProperties,\n pricing,\n productTitle,\n variantTitle,\n imageUrl,\n itemUrl,\n imageAltText,\n linkLabel,\n baseCssClasses,\n tagCssClasses,\n attributeCssClasses,\n defaultSellingPlanDiscountPercent,\n shouldHideQuantitySelector,\n ]\n );\n};\n\nexport type UseCartItemFeaturesReturn = ReturnType<typeof useCartItemFeatures>;\n", "// ~/smart-cart/utils/imageUtils.ts\n\n// TODO: REMOVE THIS AND USE npm-rebuy utils instead\nimport { NO_IMAGE_SHOPIFY_PLACEHOLDER } from '~/smart-cart/constants';\n\nexport const sizeImage = (src: string | undefined | null, size: string): string => {\n const safeSrc = src || NO_IMAGE_SHOPIFY_PLACEHOLDER;\n\n // Handle cases where the src might already have query parameters\n const [baseSrc, queryParams] = safeSrc.split('?');\n const extensionMatch = baseSrc.match(/\\.(jpg|jpeg|gif|png|bmp|webp)(\\?.*)?$/i);\n\n if (!extensionMatch) {\n // Cannot determine extension, return original or placeholder\n return safeSrc;\n }\n\n const extension = extensionMatch[1];\n // Remove existing size modifiers like _small, _large, _100x100, etc.\n const cleanedBase = baseSrc.replace(\n /_(pico|icon|thumb|small|compact|medium|large|grande|original|master|(\\d+)x(\\d)*|x(\\d+)|(\\d+)x)@?\\d?x?\\.(jpg|jpeg|gif|png|bmp|webp)/,\n `.${extension}`\n );\n\n const sizeModifier = size ? `_${size}` : '';\n const finalBase = cleanedBase.replace(`.${extension}`, `${sizeModifier}.${extension}`);\n\n return queryParams ? `${finalBase}?${queryParams}` : finalBase;\n};\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/smart-cart/components/CartItem/CartItem.css\";\n const result = {\"rebuy-cart-item\":\"CartItem_rebuy-cart-item\",\"rebuy-cart-item__media\":\"CartItem_rebuy-cart-item__media\",\"rebuy-cart-item__info\":\"CartItem_rebuy-cart-item__info\",\"rebuy-cart-item__remove-button\":\"CartItem_rebuy-cart-item__remove-button\",\"rebuy-cart-item__product-title\":\"CartItem_rebuy-cart-item__product-title\",\"rebuy-cart-item__variant-title\":\"CartItem_rebuy-cart-item__variant-title\",\"rebuy-cart-item__property--discount-message\":\"CartItem_rebuy-cart-item__property--discount-message\",\"rebuy-cart-item__properties-list\":\"CartItem_rebuy-cart-item__properties-list\",\"rebuy-cart-item__property\":\"CartItem_rebuy-cart-item__property\",\"rebuy-cart-item__property--delivery-frequency\":\"CartItem_rebuy-cart-item__property--delivery-frequency\",\"rebuy-cart-item__property-key\":\"CartItem_rebuy-cart-item__property-key\",\"rebuy-cart-item__property-separator\":\"CartItem_rebuy-cart-item__property-separator\",\"rebuy-cart-item__property-value\":\"CartItem_rebuy-cart-item__property-value\",\"rebuy-cart-item__price-details\":\"CartItem_rebuy-cart-item__price-details\",\"rebuy-cart-item__quantity-selector-area\":\"CartItem_rebuy-cart-item__quantity-selector-area\",\"rebuy-cart-item__quantity-selector\":\"CartItem_rebuy-cart-item__quantity-selector\",\"rebuy-cart-item__quantity-selector-label\":\"CartItem_rebuy-cart-item__quantity-selector-label\",\"rebuy-cart-item__quantity-selector-button\":\"CartItem_rebuy-cart-item__quantity-selector-button\",\"rebuy-cart-item__spinner\":\"CartItem_rebuy-cart-item__spinner\",\"rebuy-cart-item__money\":\"CartItem_rebuy-cart-item__money\",\"rebuy-cart-item__money--sale\":\"CartItem_rebuy-cart-item__money--sale\",\"rebuy-cart-item__money--compare-at\":\"CartItem_rebuy-cart-item__money--compare-at\",\"rebuy-cart-item__bmsm-section\":\"CartItem_rebuy-cart-item__bmsm-section\",\"rebuy-cart-item__sts-section\":\"CartItem_rebuy-cart-item__sts-section\",\"rebuy-cart-item__bundle-section\":\"CartItem_rebuy-cart-item__bundle-section\",\"rebuy-cart-item__bmsm-button-wrapper\":\"CartItem_rebuy-cart-item__bmsm-button-wrapper\",\"rebuy-cart-item__bmsm-button\":\"CartItem_rebuy-cart-item__bmsm-button\",\"rebuy-cart-item__bmsm-dynamic-message\":\"CartItem_rebuy-cart-item__bmsm-dynamic-message\",\"rebuy-cart-item__sts-action-button\":\"CartItem_rebuy-cart-item__sts-action-button\",\"rebuy-cart-item__sts-select\":\"CartItem_rebuy-cart-item__sts-select\",\"rebuy-cart-item__sts-loading-replacement\":\"CartItem_rebuy-cart-item__sts-loading-replacement\",\"rebuy-cart-item__bundle-toggle-button\":\"CartItem_rebuy-cart-item__bundle-toggle-button\",\"rebuy-cart-item__bundle-chev-icon\":\"CartItem_rebuy-cart-item__bundle-chev-icon\",\"rebuy-cart-item__bundle-children-list\":\"CartItem_rebuy-cart-item__bundle-children-list\",\"rebuy-cart-item__bundle-child-item\":\"CartItem_rebuy-cart-item__bundle-child-item\",\"rebuy-cart-item__bundle-child-media-wrapper\":\"CartItem_rebuy-cart-item__bundle-child-media-wrapper\",\"rebuy-cart-item__bundle-child-image-wrapper\":\"CartItem_rebuy-cart-item__bundle-child-image-wrapper\",\"rebuy-cart-item__bundle-child-image\":\"CartItem_rebuy-cart-item__bundle-child-image\",\"rebuy-cart-item__bundle-child-details\":\"CartItem_rebuy-cart-item__bundle-child-details\",\"rebuy-cart-item__bundle-child-title\":\"CartItem_rebuy-cart-item__bundle-child-title\",\"rebuy-cart-item__bundle-child-value\":\"CartItem_rebuy-cart-item__bundle-child-value\",\"rebuy-cart-item--updating\":\"CartItem_rebuy-cart-item--updating\"};\n export default result;\n ", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/smart-cart/components/EmptyCart/EmptyCart.css\";\n const result = {\"rebuy-empty-cart-message\":\"EmptyCart_rebuy-empty-cart-message\"};\n export default result;\n ", "// ~/smart-cart/components/EmptyCart/EmptyCart.tsx\n\nimport type React from 'react';\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\n\n/* eslint-disable-next-line no-restricted-imports */\nimport styles from './EmptyCart.module.css';\n\nexport const EmptyCart: React.FC = () => {\n const { config } = useSmartCart();\n const emptyCartMarkup = config?.empty_cart_markup || '<p>Your cart is empty.</p>';\n\n return <div className={styles['rebuy-empty-cart-message']} dangerouslySetInnerHTML={{ __html: emptyCartMarkup }} />;\n};\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/smart-cart/components/CartItemList/CartItemList.css\";\n const result = {\"rebuy-cart-item-list__container\":\"CartItemList_rebuy-cart-item-list__container\",\"rebuy-cart-item-list\":\"CartItemList_rebuy-cart-item-list\"};\n export default result;\n ", "// ~/smart-cart/components/CartItemList/CartItemList.tsx\n\nimport type { CartLine } from '@shopify/hydrogen/storefront-api-types';\nimport type React from 'react';\nimport { CartItem } from '~/smart-cart/components/CartItem/CartItem';\nimport { EmptyCart } from '~/smart-cart/components/EmptyCart/EmptyCart';\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport type { SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\nimport { isCartItemHiddenByStandardLogic, isTieredProgressBarGiftItem } from '~/smart-cart/utils/cartItemUtils';\n\n/* eslint-disable-next-line no-restricted-imports */\nimport styles from './CartItemList.module.css';\n\ntype CartItemListProps = {\n componentConfig: Extract<SmartCartComponentConfig, { type: 'cart_items' }>;\n};\n\nexport const CartItemList: React.FC<CartItemListProps> = ({ componentConfig }) => {\n const { cartData, isLoading: isCartLoading, isProgressBarLineItemMode } = useSmartCart();\n\n // Access lines directly from cartData.lines.nodes.\n // We assume cartData.lines.nodes, if it exists, is an array of CartLine-compatible objects.\n // The type annotation CartLine[] helps TypeScript, but the actual objects\n // must conform to this shape for runtime correctness.\n const lines = (cartData?.lines?.nodes ?? []) as CartLine[];\n\n const visibleLines = lines.filter((line) => {\n if (!line || !line.id || !line.merchandise) return false;\n\n if (isCartItemHiddenByStandardLogic(line)) return false;\n\n if (!isProgressBarLineItemMode && isTieredProgressBarGiftItem(line)) return false;\n\n return true;\n });\n\n const hasVisibleItems = visibleLines.length > 0;\n\n return (\n <div\n className={styles['rebuy-cart-item-list__container']}\n data-rebuy-component=\"cart-items\"\n data-rebuy-component-id={componentConfig.component_id}\n >\n {hasVisibleItems ? (\n <ul className={styles['rebuy-cart-item-list']} data-smartcart-items=\"\" role=\"group\" tabIndex={0}>\n {/* Now map directly over `line` as it's already the CartLine object */}\n {visibleLines.map((line) => (\n <CartItem key={line.id} line={line} />\n ))}\n </ul>\n ) : (\n !isCartLoading && <EmptyCart />\n )}\n </div>\n );\n};\n", "import clsx from 'clsx';\nimport React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; // Added useMemo\nimport { useFetcher } from 'react-router';\n\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport type { SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\nimport type { JsonValue } from '~/types/common';\n\n/* eslint-disable-next-line no-restricted-imports */\nimport styles from './CartNoteInput.module.css';\n\ntype CartNoteInputProps = {\n componentConfig: Extract<SmartCartComponentConfig, { type: 'notes' }>;\n};\n\ntype SaveMessage = {\n text: string;\n type: 'success' | 'error';\n};\n\nexport const CartNoteInput = React.memo(({ componentConfig }: CartNoteInputProps) => {\n const {\n cartData,\n getItemCount,\n isHydrogenReact,\n isLoading: isGlobalCartLoading,\n updateCartNote: hrUpdateCartNote,\n } = useSmartCart();\n\n const noteFetcher = useFetcher<{ cart?: typeof cartData; error?: string; userErrors?: { message: string }[] }>();\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n const isTextareaFocusedRef = useRef(false); // Ref to track focus state without causing re-renders\n\n const settings = componentConfig.settings || {};\n const label = settings?.language?.notes_label ?? 'Add a note (optional)';\n const placeholder = settings?.language?.notes_placeholder ?? 'Your notes...';\n const limitChars = settings?.limit_characters ?? true;\n const maxLength = settings?.max_length ?? 200;\n\n // Initialize currentNoteValue from cartData.note only ONCE on mount,\n // or when cartData.note changes AND the textarea is NOT focused and not saving.\n const [currentNoteValue, setCurrentNoteValue] = useState(cartData?.note || '');\n const [isTextareaVisible, setIsTextareaVisible] = useState(!!cartData?.note);\n const [isSaving, setIsSaving] = useState(false);\n const [saveMessage, setSaveMessage] = useState<SaveMessage | null>(null);\n const saveMessageTimerRef = useRef<NodeJS.Timeout | null>(null);\n\n const currentCartNoteFromCtx = cartData?.note || '';\n // isNoteChanged should compare the current input value with the last known *saved* value (from context)\n const isNoteChanged = currentNoteValue.trim() !== currentCartNoteFromCtx.trim();\n const hasItems = getItemCount() > 0;\n\n const isLoadingCombined = useMemo(() => {\n if (isHydrogenReact) return isGlobalCartLoading || isSaving;\n\n return noteFetcher.state !== 'idle' || isSaving;\n }, [isHydrogenReact, isGlobalCartLoading, noteFetcher.state, isSaving]);\n\n const canSave = isNoteChanged && !isLoadingCombined;\n\n // Effect to update local state when cartData.note changes externally (e.g. after save or from another source)\n // Only update if the textarea is not focused and we are not in the middle of a save operation.\n useEffect(() => {\n const noteFromCart = cartData?.note || '';\n\n if (!isTextareaFocusedRef.current && !isSaving && noteFromCart !== currentNoteValue) {\n setCurrentNoteValue(noteFromCart);\n }\n\n // Also, if a note appears in the cart and the toggle is off, make it visible\n // (unless the user has explicitly closed it *after* a note was present)\n // This part might need more nuanced UX logic if it causes unwanted opening.\n if (noteFromCart && !isTextareaVisible && !isSaving) {\n // Let's be less aggressive about opening it automatically.\n // User can open it with the toggle.\n // setIsTextareaVisible(true);\n } else if (!noteFromCart && isTextareaVisible && !isSaving && !currentNoteValue.trim()) {\n // If cart note is empty, and local value is also empty, and it's visible,\n // we might consider closing it if that's the desired UX after clearing.\n // For now, let user control visibility via toggle primarily.\n }\n }, [cartData?.note, isSaving, currentNoteValue, isTextareaVisible]); // Removed currentNoteValue from deps to avoid loop on typing\n\n useEffect(() => {\n return () => {\n if (saveMessageTimerRef.current) clearTimeout(saveMessageTimerRef.current);\n };\n }, []);\n\n const displaySaveMessage = (text: string, type: 'success' | 'error') => {\n setSaveMessage({ text, type });\n\n if (saveMessageTimerRef.current) clearTimeout(saveMessageTimerRef.current);\n saveMessageTimerRef.current = setTimeout(() => setSaveMessage(null), 3000);\n };\n\n const handleToggle = useCallback(\n (event: React.ChangeEvent<HTMLInputElement>) => {\n const checked = event.target.checked;\n setIsTextareaVisible(checked);\n setSaveMessage(null);\n\n if (!checked && currentNoteValue.trim()) {\n setIsSaving(true);\n const noteToClear = ''; // Always send empty string to clear\n setCurrentNoteValue(noteToClear); // Update local state immediately for visual feedback\n\n if (isHydrogenReact) {\n hrUpdateCartNote(noteToClear);\n } else {\n noteFetcher.submit({ action: 'noteUpdate', data: { note: noteToClear } } as JsonValue, {\n action: '/cart',\n encType: 'application/json',\n method: 'POST',\n });\n }\n } else if (checked) {\n setTimeout(() => textareaRef.current?.focus(), 50);\n }\n },\n [currentNoteValue, isHydrogenReact, hrUpdateCartNote, noteFetcher] // currentNoteValue IS needed here\n );\n\n const handleInputChange = useCallback(\n (event: React.ChangeEvent<HTMLTextAreaElement>) => {\n let value = event.target.value;\n\n if (limitChars && value.length > maxLength) value = value.substring(0, maxLength);\n setCurrentNoteValue(value);\n setSaveMessage(null);\n },\n [limitChars, maxLength]\n );\n\n const handleTextareaFocus = () => {\n isTextareaFocusedRef.current = true;\n };\n\n const handleTextareaBlur = () => {\n isTextareaFocusedRef.current = false;\n // Optional: If you want to auto-save on blur if changed:\n // if (isNoteChanged && canSave && !isSaving) {\n // handleSave();\n // }\n };\n\n const handleSave = useCallback(() => {\n if (!canSave) return; // canSave already checks isLoadingCombined\n\n setIsSaving(true);\n const noteToSave = currentNoteValue.trim();\n\n if (isHydrogenReact) {\n hrUpdateCartNote(noteToSave);\n } else {\n noteFetcher.submit({ action: 'noteUpdate', data: { note: noteToSave } } as JsonValue, {\n action: '/cart',\n encType: 'application/json',\n method: 'POST',\n });\n }\n }, [canSave, currentNoteValue, isHydrogenReact, hrUpdateCartNote, noteFetcher]);\n\n const handleKeyDown = useCallback(\n (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault();\n handleSave();\n }\n },\n [handleSave]\n );\n\n useEffect(() => {\n if (isHydrogenReact) {\n if (!isGlobalCartLoading && isSaving) {\n setIsSaving(false);\n // For H-React, we assume cartData.note is the source of truth after operation\n const noteSuccessfullySaved = (cartData?.note || '') === currentNoteValue.trim();\n\n if (noteSuccessfullySaved) {\n displaySaveMessage('Saved', 'success');\n } else {\n // This could happen if there was an error not reflected in isGlobalCartLoading\n // or if cartData update is lagging. More robust error handling might be needed.\n displaySaveMessage('Note updated', 'success'); // More generic message\n }\n }\n } else {\n if (noteFetcher.state === 'idle' && isSaving) {\n setIsSaving(false);\n const fetchData = noteFetcher.data;\n\n if (fetchData?.error || fetchData?.userErrors?.length) {\n displaySaveMessage(\n fetchData.error || fetchData.userErrors?.[0]?.message || 'Error saving note',\n 'error'\n );\n } else {\n displaySaveMessage('Saved', 'success');\n // If save was successful (no error), and the fetcher returns the updated cart,\n // currentNoteValue should align with cartData.note due to the other useEffect.\n }\n }\n }\n }, [\n isHydrogenReact,\n isGlobalCartLoading,\n noteFetcher.state,\n noteFetcher.data,\n isSaving,\n cartData?.note,\n currentNoteValue, // currentNoteValue needed for comparison\n ]);\n\n if (!hasItems) return null;\n\n const remainingChars = limitChars ? Math.max(0, maxLength - currentNoteValue.length) : null;\n const buttonClasses = clsx(\n styles['rebuy-cart-note-input__save-button'],\n isNoteChanged && styles['rebuy-cart-note-input__save-button--visible'], // Show if changed\n saveMessage?.type === 'success' && styles['rebuy-cart-note-input__save-button--saved'],\n saveMessage?.type === 'error' && styles['rebuy-cart-note-input__save-button--error'],\n isSaving && styles['rebuy-cart-note-input__save-button--saving']\n );\n const buttonContent = isSaving ? 'Saving...' : saveMessage?.text || 'Save';\n const helpTextId = `rebuy-cart-note-help-${componentConfig.component_id}`;\n const remainingCharsId = `rebuy-cart-note-remaining-${componentConfig.component_id}`;\n const describedByIds = [remainingChars !== null && currentNoteValue ? remainingCharsId : null, helpTextId]\n .filter(Boolean)\n .join(' ');\n\n return (\n <div\n className={styles['rebuy-cart-note-input']}\n data-rebuy-component=\"notes\"\n data-rebuy-component-id={componentConfig.component_id ?? 'notes'}\n >\n <label className={styles['rebuy-cart-note-input__toggle-control']}>\n <input\n checked={isTextareaVisible}\n className={styles['rebuy-cart-note-input__toggle-checkbox']}\n disabled={isLoadingCombined && isSaving}\n onChange={handleToggle}\n type=\"checkbox\"\n />\n <span\n className={styles['rebuy-cart-note-input__toggle-label']}\n dangerouslySetInnerHTML={{ __html: label }}\n />\n </label>\n\n {isTextareaVisible && (\n <div className={styles['rebuy-cart-note-input__content-area']}>\n <div className={styles['rebuy-cart-note-input__textarea-wrapper']}>\n <textarea\n aria-describedby={describedByIds || undefined}\n aria-label={label}\n className={styles['rebuy-cart-note-input__textarea']}\n disabled={isLoadingCombined}\n maxLength={limitChars ? maxLength : undefined}\n onBlur={handleTextareaBlur} // Track blur\n onChange={handleInputChange}\n onFocus={handleTextareaFocus} // Track focus\n onKeyDown={handleKeyDown}\n placeholder={placeholder}\n ref={textareaRef}\n rows={2}\n value={currentNoteValue} // Controlled component\n />\n <button\n aria-label={\n saveMessage?.text || (isNoteChanged ? 'Save note changes' : 'Note is up to date')\n }\n className={buttonClasses} // Make sure this is defined or use your existing logic\n disabled={!canSave || isSaving}\n onClick={handleSave}\n type=\"button\"\n >\n {buttonContent}\n </button>\n </div>\n <div\n className={clsx(\n styles['rebuy-cart-note-input__meta-info'],\n !isNoteChanged && !saveMessage && styles['rebuy-cart-note-input__meta-info--hidden']\n )}\n >\n {limitChars && currentNoteValue.length > 0 && remainingChars !== null && (\n <small\n aria-live=\"polite\"\n className={styles['rebuy-cart-note-input__remaining-chars-indicator']}\n id={remainingCharsId}\n >\n {`You have ${remainingChars} characters remaining.`}\n </small>\n )}\n <small className={styles['rebuy-cart-note-input__help-text']} id={helpTextId}>\n Press Enter to save, Shift+Enter for new line.\n </small>\n </div>\n </div>\n )}\n </div>\n );\n});\nCartNoteInput.displayName = 'CartNoteInput';\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/smart-cart/components/CartNoteInput/CartNoteInput.css\";\n const result = {\"rebuy-cart-note-input\":\"CartNoteInput_rebuy-cart-note-input\",\"rebuy-cart-note-input__toggle-control\":\"CartNoteInput_rebuy-cart-note-input__toggle-control\",\"rebuy-cart-note-input__toggle-checkbox\":\"CartNoteInput_rebuy-cart-note-input__toggle-checkbox\",\"rebuy-cart-note-input__toggle-label\":\"CartNoteInput_rebuy-cart-note-input__toggle-label\",\"rebuy-cart-note-input__textarea-wrapper\":\"CartNoteInput_rebuy-cart-note-input__textarea-wrapper\",\"rebuy-cart-note-input__textarea\":\"CartNoteInput_rebuy-cart-note-input__textarea\",\"rebuy-cart-note-input__save-button\":\"CartNoteInput_rebuy-cart-note-input__save-button\",\"rebuy-cart-note-input__save-button--visible\":\"CartNoteInput_rebuy-cart-note-input__save-button--visible\",\"rebuy-cart-note-input__save-button--saving\":\"CartNoteInput_rebuy-cart-note-input__save-button--saving\",\"rebuy-cart-note-input__save-button--saved\":\"CartNoteInput_rebuy-cart-note-input__save-button--saved\",\"rebuy-cart-note-input__save-button--error\":\"CartNoteInput_rebuy-cart-note-input__save-button--error\",\"rebuy-cart-note-input__meta-info\":\"CartNoteInput_rebuy-cart-note-input__meta-info\",\"rebuy-cart-note-input__meta-info--hidden\":\"CartNoteInput_rebuy-cart-note-input__meta-info--hidden\",\"rebuy-cart-note-input__remaining-chars-indicator\":\"CartNoteInput_rebuy-cart-note-input__remaining-chars-indicator\",\"rebuy-cart-note-input__help-text\":\"CartNoteInput_rebuy-cart-note-input__help-text\",\"rebuy-cart-note-input__content-area\":\"CartNoteInput_rebuy-cart-note-input__content-area\"};\n export default result;\n ", "// ~/smart-cart/components/CartSubtotal/CartSubtotal.tsx\nimport clsx from 'clsx';\nimport React, { useCallback, useMemo, useState } from 'react';\n\nimport { ScreenReaderText } from '~/smart-cart/components/ScreenReaderText/ScreenReaderText';\nimport { CartExclusionProductTag } from '~/smart-cart/constants';\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport type {\n StorefrontAutomaticDiscountAllocation,\n StorefrontCodeDiscountAllocation,\n StorefrontCustomDiscountAllocation,\n StorefrontTypedDiscountAllocation,\n} from '~/smart-cart/types/rebuy-storefront-cart';\nimport type { CartSubtotalSettings, SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\nimport { formatMoney } from '~/smart-cart/utils/moneyUtils';\n\n/* eslint-disable-next-line no-restricted-imports */\nimport styles from './CartSubtotal.module.css';\n\ntype FormattedDiscountItem = { amount: string; title: string };\ntype CartSubtotalProps = {\n componentConfig: Extract<SmartCartComponentConfig, { type: 'cart_subtotal' }>;\n};\n\n/**\n * Gets the display title for a discount allocation\n *\n * @param {StorefrontTypedDiscountAllocation} alloc - The discount allocation\n *\n * @returns {string} The formatted title for display\n */\nconst getDiscountAllocationTitle = (alloc: StorefrontTypedDiscountAllocation): string => {\n switch (alloc.__typename) {\n case 'CartCodeDiscountAllocation':\n return (alloc as StorefrontCodeDiscountAllocation).code.toUpperCase();\n case 'CartAutomaticDiscountAllocation':\n return (alloc as StorefrontAutomaticDiscountAllocation).title;\n case 'CartCustomDiscountAllocation':\n return (alloc as StorefrontCustomDiscountAllocation).title;\n default:\n return 'Discount';\n }\n};\n\nexport const CartSubtotalComponent = ({ componentConfig }: CartSubtotalProps) => {\n const { cartData } = useSmartCart();\n const [isDiscountSummaryExpanded, setIsDiscountSummaryExpanded] = useState(false);\n const settings = useMemo(\n () => (componentConfig?.settings ?? {}) as CartSubtotalSettings,\n [componentConfig?.settings]\n );\n\n // TODO: Extract all of this calculation logic into a hook that can be used by other components\n\n const allLines = useMemo(() => cartData?.lines?.edges ?? [], [cartData?.lines?.edges]);\n const excludedLines = useMemo(\n () =>\n allLines\n .map((edge) => edge.node)\n .filter((line) =>\n line.merchandise.product.tags?.includes(CartExclusionProductTag.EXCLUDE_FROM_CART_SUBTOTAL)\n ),\n [allLines]\n );\n const excludedLinesValue = useMemo(\n () => excludedLines.reduce((sum, line) => sum + parseFloat(line.cost.subtotalAmount?.amount ?? '0'), 0),\n [excludedLines]\n );\n\n const apiSubtotalAmount = useMemo(\n () => parseFloat(cartData?.cost?.subtotalAmount?.amount ?? '0'),\n [cartData?.cost?.subtotalAmount?.amount]\n );\n\n const apiTotalAmount = useMemo(\n () => parseFloat(cartData?.cost?.totalAmount?.amount ?? '0'),\n [cartData?.cost?.totalAmount?.amount]\n );\n\n const adjustedPreDiscountSubtotal = useMemo(\n () => Math.max(0, apiSubtotalAmount - excludedLinesValue),\n [apiSubtotalAmount, excludedLinesValue]\n );\n\n const adjustedFinalTotal = useMemo(\n () => Math.max(0, apiTotalAmount - excludedLinesValue),\n [apiTotalAmount, excludedLinesValue]\n );\n\n const totalItemCount = useMemo(() => cartData?.totalQuantity ?? 0, [cartData?.totalQuantity]);\n\n const subtotalLabel = useMemo(() => {\n const singular = settings.subtotal_singular_text ?? 'Subtotal ({{item_count}} item)';\n const plural = settings.subtotal_plural_text ?? 'Subtotal ({{item_count}} items)';\n\n return (totalItemCount === 1 ? singular : plural).replace('{{item_count}}', String(totalItemCount));\n }, [totalItemCount, settings.subtotal_singular_text, settings.subtotal_plural_text]);\n\n const currencyCode = useMemo(\n () => cartData?.cost?.subtotalAmount?.currencyCode ?? 'USD',\n [cartData?.cost?.subtotalAmount?.currencyCode]\n );\n\n const hasOrderDiscount = useMemo(\n () => adjustedPreDiscountSubtotal > adjustedFinalTotal,\n [adjustedPreDiscountSubtotal, adjustedFinalTotal]\n );\n\n const formattedFinalTotal = useMemo(\n () => formatMoney(adjustedFinalTotal, currencyCode),\n [adjustedFinalTotal, currencyCode]\n );\n\n const formattedPreDiscountSubtotal = useMemo(\n () => formatMoney(adjustedPreDiscountSubtotal, currencyCode),\n [adjustedPreDiscountSubtotal, currencyCode]\n );\n\n const groupedCartLevelDiscounts = useMemo<FormattedDiscountItem[]>(() => {\n if (!cartData?.discountAllocations) return [];\n\n const grouped = cartData.discountAllocations.reduce<Record<string, number>>((acc, alloc) => {\n const amount = parseFloat(alloc.discountedAmount?.amount ?? '0');\n\n if (amount === 0) return acc;\n\n const title = getDiscountAllocationTitle(alloc);\n acc[title] = (acc[title] ?? 0) + amount;\n\n return acc;\n }, {});\n\n return Object.entries(grouped).map(([title, totalAmount]) => ({\n amount: `- ${formatMoney(totalAmount, currencyCode)}`,\n title,\n }));\n }, [cartData?.discountAllocations, currencyCode]);\n\n const shouldShowDiscountSummary = useMemo(\n () => settings.show_discount_summary === true && groupedCartLevelDiscounts.length > 0,\n [settings.show_discount_summary, groupedCartLevelDiscounts.length]\n );\n\n const discountSummaryCountLabel = useMemo(() => {\n if (!shouldShowDiscountSummary) return '';\n\n const count = groupedCartLevelDiscounts.length;\n const singular = settings.discount_summary_count_label ?? '{{discount_count}} order discount applied';\n const plural = settings.discount_summary_count_label_plural ?? '{{discount_count}} order discounts applied';\n\n return (count === 1 ? singular : plural).replace('{{discount_count}}', String(count));\n }, [\n shouldShowDiscountSummary,\n groupedCartLevelDiscounts.length,\n settings.discount_summary_count_label,\n settings.discount_summary_count_label_plural,\n ]);\n\n const toggleDiscountSummary = useCallback(() => setIsDiscountSummaryExpanded((prev) => !prev), []);\n\n if (totalItemCount === 0) return null; // Hide if cart is empty\n\n const rootClasses = clsx(\n styles['rebuy-cart-subtotal'],\n shouldShowDiscountSummary ? styles['rebuy-cart-subtotal--with-summary'] : styles['rebuy-cart-subtotal--simple']\n );\n const primaryPrice = formattedFinalTotal;\n const compareAtPrice = hasOrderDiscount ? formattedPreDiscountSubtotal : null;\n const summaryId = `rebuy-discount-summary-details-${componentConfig.component_id}`;\n\n return (\n <div\n className={rootClasses}\n data-rebuy-component=\"cart-subtotal\"\n data-rebuy-component-id={componentConfig.component_id}\n >\n {/* Common Row structure for subtotal display */}\n <div className={styles['rebuy-cart-subtotal__row']}>\n <div className={styles['rebuy-cart-subtotal__label']}>\n <span>{subtotalLabel}</span>\n </div>\n <div className={styles['rebuy-cart-subtotal__amount-wrapper']}>\n <ScreenReaderText>Cart subtotal</ScreenReaderText>\n {compareAtPrice ? (\n <>\n <span className={styles['rebuy-cart-subtotal__price--final']}>\n <ScreenReaderText>Final price</ScreenReaderText>\n <span>{primaryPrice}</span>\n </span>\n <span className={styles['rebuy-cart-subtotal__price--compare-at']}>\n <ScreenReaderText>Original price</ScreenReaderText>\n <span>{compareAtPrice}</span>\n </span>\n </>\n ) : (\n <span>{primaryPrice}</span>\n )}\n </div>\n </div>\n\n {shouldShowDiscountSummary && (\n <div\n className={clsx(styles['rebuy-cart-subtotal__discount-summary'], {\n [styles['rebuy-cart-subtotal__discount-summary--expanded']]: isDiscountSummaryExpanded,\n })}\n >\n <button\n aria-controls={summaryId}\n aria-expanded={isDiscountSummaryExpanded}\n className={styles['rebuy-cart-subtotal__discount-summary-header']}\n onClick={toggleDiscountSummary}\n >\n <span>{discountSummaryCountLabel}</span>\n <span aria-hidden=\"true\" className={styles['rebuy-cart-subtotal__discount-summary-icon']}>\n <i>&#9660;</i> {/* Simple arrow. // TODO: replace with SVG icon */}\n </span>\n </button>\n <div\n aria-hidden={!isDiscountSummaryExpanded}\n className={styles['rebuy-cart-subtotal__discount-summary-details']}\n id={summaryId}\n role=\"region\"\n >\n {groupedCartLevelDiscounts.map((discount, index) => (\n <div className={styles['rebuy-cart-subtotal__discount-summary-item']} key={index}>\n <span>{discount.title}</span>\n <span>{discount.amount}</span>\n </div>\n ))}\n </div>\n </div>\n )}\n </div>\n );\n};\n\nexport const CartSubtotal = React.memo(CartSubtotalComponent);\n\nCartSubtotal.displayName = 'CartSubtotal';\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/smart-cart/components/CartSubtotal/CartSubtotal.css\";\n const result = {\"rebuy-cart-subtotal\":\"CartSubtotal_rebuy-cart-subtotal\",\"rebuy-cart-subtotal--simple\":\"CartSubtotal_rebuy-cart-subtotal--simple\",\"rebuy-cart-subtotal__label\":\"CartSubtotal_rebuy-cart-subtotal__label\",\"rebuy-cart-subtotal__amount-wrapper\":\"CartSubtotal_rebuy-cart-subtotal__amount-wrapper\",\"rebuy-cart-subtotal__price--compare-at\":\"CartSubtotal_rebuy-cart-subtotal__price--compare-at\",\"rebuy-cart-subtotal__price--final\":\"CartSubtotal_rebuy-cart-subtotal__price--final\",\"rebuy-cart-subtotal--with-summary\":\"CartSubtotal_rebuy-cart-subtotal--with-summary\",\"rebuy-cart-subtotal__row\":\"CartSubtotal_rebuy-cart-subtotal__row\",\"rebuy-cart-subtotal__discount-summary\":\"CartSubtotal_rebuy-cart-subtotal__discount-summary\",\"rebuy-cart-subtotal__discount-summary-header\":\"CartSubtotal_rebuy-cart-subtotal__discount-summary-header\",\"rebuy-cart-subtotal__discount-summary-icon\":\"CartSubtotal_rebuy-cart-subtotal__discount-summary-icon\",\"rebuy-cart-subtotal__discount-summary--expanded\":\"CartSubtotal_rebuy-cart-subtotal__discount-summary--expanded\",\"rebuy-cart-subtotal__discount-summary-details\":\"CartSubtotal_rebuy-cart-subtotal__discount-summary-details\",\"rebuy-cart-subtotal__discount-summary-item\":\"CartSubtotal_rebuy-cart-subtotal__discount-summary-item\"};\n export default result;\n ", "// ~/smart-cart/components/CartTitleBar/CartTitleBar.tsx\nimport DOMPurify from 'dompurify';\nimport React, { useMemo } from 'react';\n\nimport { ScreenReaderText } from '~/smart-cart/components/ScreenReaderText/ScreenReaderText';\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\n\n/* eslint-disable-next-line no-restricted-imports */\nimport styles from './CartTitleBar.module.css';\n\n/**\n * Renders the Smart Cart Title Bar based on configuration.\n * Fetches settings from the SmartCartContext.\n */\nexport const CartTitleBar = React.memo(() => {\n const { getComponentConfigByType } = useSmartCart();\n const componentConfig = getComponentConfigByType('title_bar');\n\n const title = componentConfig?.settings?.title ?? 'Your Cart';\n const headingTag = componentConfig?.settings?.heading_tag ?? 'h2';\n const screenReaderOnly = componentConfig?.settings?.screen_reader_only ?? false;\n\n const sanitizedTitle = useMemo(() => {\n if (typeof window !== 'undefined') return DOMPurify.sanitize(title);\n\n return title;\n }, [title]);\n\n const DynamicHeadingTag = headingTag as React.ElementType;\n\n if (title === '' && !screenReaderOnly) return null;\n\n if (screenReaderOnly) {\n return (\n <DynamicHeadingTag\n data-rebuy-component-id={componentConfig?.component_id ?? 'title_bar'}\n id=\"rebuy-cart-title\"\n >\n <ScreenReaderText>{sanitizedTitle}</ScreenReaderText>\n </DynamicHeadingTag>\n );\n }\n\n return (\n <DynamicHeadingTag\n className={styles['rebuy-cart-title-bar']}\n dangerouslySetInnerHTML={{ __html: sanitizedTitle }}\n data-rebuy-component=\"title-bar\"\n data-rebuy-component-id={componentConfig?.component_id ?? 'title_bar'}\n id=\"rebuy-cart-title\"\n />\n );\n});\nCartTitleBar.displayName = 'CartTitleBar';\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/smart-cart/components/CartTitleBar/CartTitleBar.css\";\n const result = {\"rebuy-cart-title-bar\":\"CartTitleBar_rebuy-cart-title-bar\"};\n export default result;\n ", "// ~/smart-cart/components/CheckoutArea/CheckoutArea.tsx\nimport React, { useCallback, useEffect, useMemo, useState } from 'react';\nimport { useFetcher } from 'react-router';\n\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport type { StorefrontAttribute } from '~/smart-cart/types/rebuy-storefront-cart';\nimport type { CheckoutSettings, SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\nimport { formatMoney } from '~/smart-cart/utils/moneyUtils';\nimport type { JsonValue } from '~/types/common';\n\n/* eslint-disable-next-line no-restricted-imports */\nimport styles from './CheckoutArea.module.css';\n\ntype CheckoutAreaProps = {\n componentConfig: Extract<SmartCartComponentConfig, { type: 'checkout' }>;\n};\ntype ProcessingSource = 'checkout' | 'view_cart' | 'shop_pay' | 'terms';\n\nexport const CheckoutArea = React.memo(({ componentConfig }: CheckoutAreaProps) => {\n const {\n cartData,\n checkout,\n getItemCount,\n hideCart,\n isHydrogenReact,\n isLoading: isGlobalCartLoading,\n updateCartAttributes: hrUpdateCartAttributes,\n } = useSmartCart();\n\n const termsFetcher = useFetcher<{ cart?: typeof cartData; error?: string; userErrors?: { message: string }[] }>();\n const settings = componentConfig.settings as CheckoutSettings;\n\n const [termsAccepted, setTermsAccepted] = useState(false);\n const [processingSource, setProcessingSource] = useState<ProcessingSource | null>(null);\n\n // Sync termsAccepted with cartData attribute\n useEffect(() => {\n const termsAttr = cartData?.attributes?.find((attr) => attr.key === 'Terms and Conditions');\n const acceptedInCart = termsAttr?.value === 'Accepted';\n\n // Only update if not currently processing a terms change, to avoid race conditions\n if (processingSource !== 'terms' && termsAccepted !== acceptedInCart) {\n setTermsAccepted(acceptedInCart);\n }\n }, [cartData?.attributes, termsAccepted, processingSource]);\n\n const hasItems = getItemCount() > 0;\n const hasTermsEnabled = useMemo(() => !!settings?.terms?.enabled, [settings?.terms?.enabled]);\n\n const isLoadingCombined = useMemo(() => {\n if (isHydrogenReact) return isGlobalCartLoading || processingSource === 'terms';\n\n return termsFetcher.state !== 'idle' || processingSource === 'terms';\n }, [isHydrogenReact, isGlobalCartLoading, termsFetcher.state, processingSource]);\n\n const isAnyCriticalActionProcessing = useMemo(() => {\n if (isHydrogenReact) return isGlobalCartLoading; // H-React has one global loading indicator for cart ops\n\n // For Remix, if we had multiple fetchers for different actions in this component, we'd check all.\n // Here, we only have termsFetcher. Other actions are page navigations.\n return (\n termsFetcher.state !== 'idle' ||\n processingSource === 'checkout' ||\n processingSource === 'shop_pay' ||\n processingSource === 'view_cart'\n );\n }, [isHydrogenReact, isGlobalCartLoading, termsFetcher.state, processingSource]);\n\n const isCheckoutDisabled = useMemo(\n () => !hasItems || isAnyCriticalActionProcessing || (hasTermsEnabled && !termsAccepted),\n [hasItems, isAnyCriticalActionProcessing, hasTermsEnabled, termsAccepted]\n );\n\n const isTermsCheckboxDisabled = useMemo(() => {\n if (isHydrogenReact) return isGlobalCartLoading || processingSource === 'terms';\n\n return termsFetcher.state !== 'idle' || processingSource === 'terms';\n }, [isHydrogenReact, isGlobalCartLoading, termsFetcher.state, processingSource]);\n\n const hasCheckoutButton = useMemo(() => !!settings?.checkout_button?.enabled, [settings?.checkout_button?.enabled]);\n const hasViewCartButton = useMemo(\n () => !!settings?.view_cart_button?.enabled,\n [settings?.view_cart_button?.enabled]\n );\n const hasContinueShoppingButton = useMemo(\n () => !!settings?.continue_shopping_button?.enabled,\n [settings?.continue_shopping_button?.enabled]\n );\n const hasShopPayButton = useMemo(() => !!settings?.shop_pay?.enabled, [settings?.shop_pay?.enabled]);\n const hasInstallments = useMemo(\n () => settings?.installments?.enabled && settings?.installments?.provider,\n [settings?.installments?.enabled, settings?.installments?.provider]\n );\n const hasPrePurchase = useMemo(\n () => settings?.pre_purchase?.enabled && settings?.pre_purchase?.widget_id,\n [settings?.pre_purchase?.enabled, settings?.pre_purchase?.widget_id]\n );\n const checkoutLabel = useMemo(\n () =>\n processingSource === 'checkout'\n ? (settings?.language?.checking_out_label ?? 'Checking Out...')\n : (settings?.language?.checkout_label ?? 'Checkout \u2192'),\n [processingSource, settings?.language]\n );\n const viewCartLabel = useMemo(\n () =>\n processingSource === 'view_cart'\n ? (settings?.language?.view_cart_working_label ?? 'Redirecting...')\n : (settings?.language?.view_cart_label ?? 'View Cart'),\n [processingSource, settings?.language]\n );\n const continueShoppingLabel = useMemo(\n () => settings?.language?.continue_shopping_label ?? 'Continue Shopping',\n [settings?.language?.continue_shopping_label]\n );\n const termsLabel = useMemo(\n () => settings?.language?.terms_and_conditions_label ?? 'I agree to the terms and conditions',\n [settings?.language?.terms_and_conditions_label]\n );\n const installmentsMessage = useMemo(() => {\n const totalAmountData = cartData?.cost?.totalAmount;\n\n if (!hasInstallments || !totalAmountData?.amount || !totalAmountData?.currencyCode) return '';\n const paymentCount = parseInt(settings?.installments?.payment_count ?? '4', 10);\n\n if (isNaN(paymentCount) || paymentCount <= 0) return '';\n const totalAmount = parseFloat(totalAmountData.amount);\n\n if (isNaN(totalAmount)) return '';\n const paymentAmount = totalAmount / paymentCount;\n const formattedPayment = formatMoney(paymentAmount, totalAmountData.currencyCode);\n const provider = settings?.installments?.provider ?? 'Installments Provider';\n const termsUrl = settings?.installments?.terms_url ?? '#';\n\n return `or ${paymentCount} interest-free installments of ${formattedPayment} by <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"${termsUrl}\">${provider}</a>`;\n }, [hasInstallments, cartData?.cost?.totalAmount, settings?.installments]);\n\n const handleTermsChange = useCallback(async () => {\n if (!hasTermsEnabled || isTermsCheckboxDisabled || !hasItems) return;\n\n setProcessingSource('terms');\n const newAcceptedState = !termsAccepted;\n setTermsAccepted(newAcceptedState);\n\n const attribute: StorefrontAttribute = {\n key: 'Terms and Conditions',\n value: newAcceptedState ? 'Accepted' : '',\n };\n\n const otherAttributes = cartData?.attributes?.filter((attr) => attr.key !== 'Terms and Conditions') || [];\n const attributesToUpdate = [...otherAttributes, attribute];\n\n if (isHydrogenReact) {\n try {\n await hrUpdateCartAttributes(attributesToUpdate);\n } catch (error) {\n console.error('[CheckoutArea H-React] Error updating terms:', error);\n setTermsAccepted(!newAcceptedState);\n }\n } else {\n termsFetcher.submit(\n { action: 'cartAttributesUpdate', data: { attributes: attributesToUpdate } } as JsonValue,\n { action: '/cart', encType: 'application/json', method: 'POST' }\n );\n }\n }, [\n hasTermsEnabled,\n isTermsCheckboxDisabled,\n hasItems,\n termsAccepted,\n isHydrogenReact,\n hrUpdateCartAttributes,\n termsFetcher,\n cartData?.attributes,\n ]);\n\n // Effect to reset processingSource for terms when operation completes\n useEffect(() => {\n if (processingSource === 'terms') {\n if (isHydrogenReact && !isGlobalCartLoading) {\n setProcessingSource(null);\n // Verify if the change persisted from cartData\n const termsAttr = cartData?.attributes?.find((attr) => attr.key === 'Terms and Conditions');\n const acceptedInCart = termsAttr?.value === 'Accepted';\n\n if (termsAccepted !== acceptedInCart) {\n console.warn('[CheckoutArea H-React] Terms state discrepancy after update.');\n setTermsAccepted(acceptedInCart); // Force sync\n }\n } else if (!isHydrogenReact && termsFetcher.state === 'idle') {\n setProcessingSource(null);\n\n if (termsFetcher.data?.error || termsFetcher.data?.userErrors?.length) {\n console.error(\n '[CheckoutArea Remix] Error updating terms:',\n termsFetcher.data.error || termsFetcher.data.userErrors\n );\n // Revert optimistic update if there was an error\n setTermsAccepted((prev) => !prev);\n } else {\n // Verify from returned cart data if possible\n const termsAttr = termsFetcher.data?.cart?.attributes?.find(\n (attr: StorefrontAttribute) => attr.key === 'Terms and Conditions'\n );\n const acceptedInFetcherCart = termsAttr?.value === 'Accepted';\n\n if (termsAccepted !== acceptedInFetcherCart && termsFetcher.data?.cart) {\n console.warn('[CheckoutArea Remix] Terms state discrepancy after fetcher update.');\n setTermsAccepted(acceptedInFetcherCart); // Force sync\n }\n }\n }\n }\n }, [\n isHydrogenReact,\n isGlobalCartLoading,\n termsFetcher.state,\n termsFetcher.data,\n processingSource,\n termsAccepted,\n cartData?.attributes,\n ]);\n\n const handleCheckoutClick = useCallback(() => {\n if (isCheckoutDisabled) return;\n setProcessingSource('checkout');\n const routing = settings?.checkout_button?.routing ?? 'automatic';\n const routingLink = settings?.checkout_button?.routing_link ?? '';\n try {\n if (routing === 'custom' && routingLink) window.location.href = routingLink;\n else if (routing === 'shopify') window.location.href = '/checkout';\n else if (routing === 'recharge') checkout();\n else checkout();\n } catch (error) {\n console.error('Checkout Error:', error);\n setProcessingSource(null); // Reset on error\n }\n }, [isCheckoutDisabled, settings?.checkout_button, checkout]);\n\n const handleViewCartClick = useCallback(() => {\n if (isAnyCriticalActionProcessing && processingSource !== 'terms') return;\n setProcessingSource('view_cart');\n window.location.href = '/cart';\n }, [isAnyCriticalActionProcessing, processingSource]);\n\n const handleContinueShoppingClick = useCallback(() => {\n if (isAnyCriticalActionProcessing && processingSource !== 'terms') return;\n hideCart();\n }, [isAnyCriticalActionProcessing, processingSource, hideCart]);\n\n const handleShopPayClick = useCallback(() => {\n if (isLoadingCombined || (!!processingSource && processingSource !== 'terms') || !hasItems) return;\n setProcessingSource('shop_pay');\n try {\n const checkoutUrl = cartData?.checkoutUrl;\n\n if (checkoutUrl) {\n const shopPayUrl = new URL(checkoutUrl);\n shopPayUrl.searchParams.set('payment', 'shop_pay');\n window.location.href = shopPayUrl.toString();\n } else {\n setProcessingSource(null); // Reset if no URL\n }\n } catch (error) {\n console.error('Shop Pay Error:', error);\n setProcessingSource(null); // Reset on error\n }\n }, [isLoadingCombined, processingSource, hasItems, cartData?.checkoutUrl]);\n\n const shopPaySvg = useMemo(\n () => ({\n __html: `<?xml version=\"1.0\" encoding=\"UTF-8\"?><svg width=\"80\" height=\"30\" fill=\"none\" viewBox=\"0 0 4317 1037\" xmlns=\"http://www.w3.org/2000/svg\"><g clip-path=\"url(#a)\" fill=\"#fff\"><path d=\"m1106 326.19c-34.62-72.633-100.26-119.55-199.17-119.55-30.36 0.529-60.193 8.026-87.198 21.908-27.003 13.884-50.46 33.785-68.555 58.168l-3.61 4.398v-284.67c0-1.6452-0.653-3.2229-1.817-4.3862-1.163-1.1633-2.742-1.817-4.387-1.817h-139.85c-1.625 0.029561-3.173 0.69609-4.312 1.8562-1.14 1.1601-1.778 2.7211-1.778 4.3469v816.56c0 1.615 0.643 3.163 1.785 4.305 1.142 1.143 2.69 1.785 4.305 1.785h149.78c1.626 0 3.187-0.637 4.347-1.778 1.16-1.139 1.826-2.687 1.856-4.312v-348.16c0-67.67 45.113-115.6 117.3-115.6 78.949 0 98.912 64.964 98.912 131.17v332.6c0 1.615 0.641 3.163 1.783 4.305 1.142 1.143 2.692 1.785 4.307 1.785h149.44c1.63 0 3.19-0.637 4.35-1.778 1.16-1.139 1.83-2.687 1.86-4.312v-352.45c0-12.068 0-23.911-1.58-35.414-2.57-37.698-11.97-74.616-27.75-108.95z\"/><path d=\"m358.09 447.21s-76.242-17.933-104.32-25.151c-28.084-7.218-77.145-22.557-77.145-59.663s39.587-48.949 79.739-48.949c40.151 0 84.814 9.7 88.31 54.25 0.141 1.606 0.88 3.098 2.07 4.186 1.191 1.086 2.746 1.684 4.358 1.679l147.63-0.564c0.869 2e-3 1.729-0.175 2.526-0.52s1.514-0.851 2.107-1.487c0.593-0.634 1.049-1.385 1.338-2.204 0.289-0.82 0.408-1.69 0.345-2.557-9.135-142.56-134.21-193.54-249.59-193.54-136.81 0-236.85 90.227-236.85 189.7 0 72.633 20.527 140.76 181.92 188.12 28.309 8.233 66.769 18.947 100.38 28.309 40.376 11.279 62.143 28.309 62.143 55.151 0 31.128-45.113 52.782-89.437 52.782-64.174 0-109.74-23.797-113.46-66.543-0.194-1.563-0.955-3.003-2.141-4.043-1.185-1.04-2.711-1.608-4.288-1.596l-147.3 0.677c-0.86355 0-1.7182 0.173-2.5133 0.511-0.79503 0.337-1.514 0.83-2.114 1.452-0.6 0.62-1.0688 1.356-1.3783 2.162-0.30948 0.807-0.45331 1.667-0.42301 2.53 6.767 134.55 136.69 207.07 257.83 207.07 180.45 0 262-101.5 262-196.58 0.226-44.663-10.038-146.39-161.73-185.19z\"/><path d=\"m2257.4 206.41c-74.99 0-137.82 41.504-178.31 91.582v-85.717c0-1.596-0.63-3.129-1.75-4.267-1.1-1.139-2.63-1.794-4.23-1.822h-140.07c-1.61 0-3.17 0.64-4.31 1.782-1.14 1.143-1.79 2.693-1.79 4.307v800.77c0.04 1.59 0.7 3.12 1.84 4.23 1.14 1.12 2.67 1.75 4.26 1.75h149.89c1.58 0 3.1-0.63 4.22-1.75s1.75-2.65 1.75-4.23v-263.24h2.26c23.79 36.315 88.87 79.851 173.92 79.851 159.91 0 293.23-132.63 293.23-311.85 0.12-172-132.52-311.4-300.91-311.4zm-13.87 470.65c-31.56 0.784-62.67-7.857-89.3-24.819-26.63-16.964-47.62-41.479-60.27-70.418-12.64-28.94-16.38-60.991-10.72-92.063 5.64-31.072 20.43-59.755 42.45-82.388 22.03-22.636 50.3-38.194 81.21-44.69 30.9-6.496 63.04-3.637 92.31 8.214 29.28 11.85 54.35 32.155 72.04 58.322 17.68 26.168 27.16 57.009 27.25 88.591 0.32 20.643-3.44 41.149-11.05 60.339s-18.95 36.686-33.35 51.483c-14.39 14.797-31.57 26.604-50.56 34.743-18.97 8.14-39.36 12.45-60.01 12.686z\"/><path d=\"m1483.3 171.23c-139.74 0-209.44 47.482-265.39 85.491l-1.69 1.127c-2.88 1.974-4.91 4.966-5.69 8.374-0.77 3.409-0.23 6.983 1.52 10.01l55.26 95.188c1.04 1.782 2.46 3.313 4.15 4.482 1.7 1.17 3.63 1.951 5.67 2.286 1.99 0.359 4.03 0.272 5.98-0.255s3.76-1.478 5.3-2.791l4.39-3.608c28.76-24.136 74.89-56.393 186.55-65.19 62.14-4.961 115.83 11.279 155.41 48.272 43.54 40.152 69.6 105 69.6 173.46 0 125.98-74.22 205.15-193.43 206.73-98.24-0.564-164.22-51.768-164.22-127.45 0-40.152 18.16-66.317 53.58-92.483 2.7-1.934 4.61-4.781 5.38-8.015s0.34-6.637-1.21-9.579l-49.63-93.837c-0.91-1.679-2.15-3.161-3.64-4.361s-3.2-2.094-5.04-2.631c-1.88-0.559-3.85-0.717-5.79-0.466-1.95 0.253-3.82 0.911-5.49 1.933-55.71 33.045-124.06 93.497-120.34 209.66 4.51 147.86 127.45 260.76 287.26 265.38h18.95c189.92-6.204 327.07-147.18 327.07-338.35 0-175.49-127.9-363.39-364.51-363.39z\"/><path d=\"m3148.9 261.46h-95.2c-2.22 0.029-4.36 0.93-5.94 2.509-1.59 1.58-2.49 3.715-2.5 5.95v199.74c0.01 2.225 0.92 4.346 2.51 5.908 1.58 1.562 3.71 2.439 5.93 2.439h95.2c57.97 0 100.72-45.678 100.72-108.27s-42.75-108.27-100.72-108.27z\"/><path d=\"m3441.4 614.8c0 28.985 24.47 45.113 67.1 45.113 57.97 0 92.25-31.354 92.25-86.957v-16.014l-86.83 4.511c-45.8 2.255-72.52 21.317-72.52 53.347z\"/><path d=\"m4146.3 2.0498h-1279c-20.97-2e-5 -41.76 4.1346-61.13 12.167-19.39 8.0328-37 19.806-51.82 34.648-14.84 14.842-26.6 32.46-34.62 51.85-8.03 19.389-12.14 40.168-12.12 61.15v700.16c0 42.366 16.82 82.999 46.77 112.97 29.95 29.968 70.57 46.818 112.92 46.848h1279c21.01 0.06 41.83-4.02 61.26-12.01 19.42-7.99 37.08-19.737 51.97-34.557 14.87-14.823 26.7-32.434 34.78-51.828 8.07-19.393 12.23-40.187 12.27-61.193v-700.16c0.03-21.048-4.08-41.898-12.12-61.35-8.04-19.452-19.85-37.122-34.74-51.995-14.89-14.873-32.58-26.655-52.04-34.668-19.46-8.0136-40.32-12.101-61.38-12.026zm-992.5 554.56h-100.6c-2.24 0-4.38 0.89-5.98 2.476-1.58 1.587-2.48 3.739-2.48 5.983v143.23c0 2.243-0.89 4.395-2.47 5.981-1.59 1.587-3.74 2.478-5.98 2.478h-70.84c-2.22-0.029-4.37-0.93-5.95-2.511-1.58-1.578-2.46-3.713-2.5-5.948v-516.66c0-2.242 0.89-4.394 2.49-5.981 1.58-1.586 3.72-2.477 5.96-2.477h188.35c106.7 0 183.05 77.708 183.05 186.77s-75.79 186.88-182.47 186.88l-0.58-0.224zm530.09 151.58c0.02 1.12-0.18 2.231-0.61 3.271-0.42 1.039-1.04 1.986-1.82 2.783-0.8 0.797-1.73 1.431-2.77 1.863-1.02 0.431-2.14 0.654-3.26 0.654h-66.88c-1.12 0-2.23-0.223-3.26-0.654-1.04-0.432-1.98-1.066-2.76-1.863s-1.41-1.744-1.82-2.783c-0.42-1.04-0.63-2.151-0.61-3.271v-15.451c0.1-1.357-0.22-2.713-0.95-3.865-0.71-1.154-1.78-2.045-3.06-2.54-1.26-0.494-2.65-0.565-3.96-0.203-1.33 0.36-2.48 1.135-3.31 2.209-19.97 21.767-52.45 37.556-104.22 37.556-76.23 0-126.66-39.699-126.66-108.27-0.73-16.72 2.72-33.359 10.05-48.408 7.32-15.046 18.3-28.026 31.92-37.758 27.51-20.64 70.14-31.354 133.41-33.836l67.1-2.255v-19.626c0-39.587-26.61-56.391-69.36-56.391-42.74 0-69.7 15.113-76 39.813-0.51 1.744-1.58 3.27-3.06 4.333-1.46 1.064-3.25 1.602-5.07 1.531h-66.2c-1.22 0.031-2.43-0.207-3.55-0.693-1.1-0.488-2.11-1.214-2.92-2.128-0.8-0.915-1.4-1.992-1.74-3.162-0.35-1.169-0.44-2.398-0.25-3.603 9.93-58.648 58.42-103.2 161.85-103.2 109.85 0 149.43 51.092 149.43 148.65l0.34 207.3zm416.63-335.2-148.87 397.11c-33.84 92.256-93.06 115.94-157.91 115.94-12.21 0.298-24.41-1.184-36.2-4.398-1.84-0.495-3.45-1.579-4.63-3.089-1.15-1.507-1.78-3.355-1.8-5.258v-60.34c0-1.262 0.27-2.51 0.8-3.654 0.54-1.144 1.31-2.157 2.28-2.964 0.98-0.809 2.11-1.392 3.33-1.71s2.5-0.363 3.74-0.131c10.23 1.94 20.61 2.922 31.02 2.934 17.93 0.899 35.65-4.247 50.32-14.615 14.65-10.368 25.41-25.358 30.54-42.567l4.41-13.873c0.68-1.856 0.68-3.894 0-5.752l-139.19-357.52c-0.42-1.278-0.54-2.64-0.34-3.972 0.21-1.333 0.72-2.6 1.48-3.698 0.79-1.098 1.82-1.997 3.01-2.625 1.19-0.627 2.52-0.965 3.86-0.984h67.68c1.73 0.017 3.41 0.551 4.84 1.537 1.43 0.984 2.53 2.374 3.16 3.99l94.52 252.18c0.63 1.647 1.73 3.066 3.18 4.067 1.46 1.003 3.17 1.538 4.94 1.538 1.75 0 3.49-0.535 4.93-1.538 1.45-1.001 2.57-2.42 3.18-4.067l82.01-251.51c0.54-1.715 1.63-3.209 3.09-4.264 1.46-1.056 3.21-1.617 5.01-1.601h69.38c1.33-6e-3 2.65 0.306 3.86 0.904 1.19 0.6 2.24 1.472 3.04 2.547s1.33 2.322 1.56 3.643c0.24 1.319 0.16 2.675-0.23 3.958v-0.226z\"/></g><defs><clipPath id=\"a\"><rect transform=\"translate(0 .24023)\" width=\"4317\" height=\"1036.8\" fill=\"#fff\"/></clipPath></defs></svg>`,\n }),\n []\n );\n\n if (!settings) return null;\n\n return (\n <div\n className={styles['rebuy-checkout-area']}\n data-rebuy-component=\"checkout-area\"\n data-rebuy-component-id={componentConfig.component_id}\n >\n {hasTermsEnabled && (\n <div className={styles['rebuy-checkout-area__terms']}>\n <input\n checked={termsAccepted}\n className={styles['rebuy-checkout-area__terms-checkbox']}\n disabled={isTermsCheckboxDisabled || !hasItems}\n id={`rebuy-terms-checkbox-${componentConfig.component_id}`}\n name=\"rebuy-terms-checkbox\"\n onChange={handleTermsChange}\n type=\"checkbox\"\n />\n <label\n className={styles['rebuy-checkout-area__terms-label']}\n dangerouslySetInnerHTML={{ __html: termsLabel }}\n htmlFor={`rebuy-terms-checkbox-${componentConfig.component_id}`}\n />\n </div>\n )}\n\n {hasCheckoutButton && (\n <button\n className={styles['rebuy-checkout-area__checkout-button']}\n disabled={isCheckoutDisabled}\n onClick={handleCheckoutClick}\n type=\"button\"\n >\n <span dangerouslySetInnerHTML={{ __html: checkoutLabel }} />\n </button>\n )}\n\n {hasViewCartButton && (\n <button\n className={styles['rebuy-checkout-area__view-cart-button']}\n disabled={isAnyCriticalActionProcessing && processingSource !== 'terms'}\n onClick={handleViewCartClick}\n type=\"button\"\n >\n <span dangerouslySetInnerHTML={{ __html: viewCartLabel }} />\n </button>\n )}\n\n {hasContinueShoppingButton && (\n <button\n className={styles['rebuy-checkout-area__continue-shopping-button']}\n disabled={isAnyCriticalActionProcessing && processingSource !== 'terms'}\n onClick={handleContinueShoppingClick}\n type=\"button\"\n >\n <span\n dangerouslySetInnerHTML={{\n __html: continueShoppingLabel,\n }}\n />\n </button>\n )}\n\n {hasShopPayButton && (\n <button\n aria-label=\"Checkout with Shop Pay\"\n className={styles['rebuy-checkout-area__shop-pay-button']}\n dangerouslySetInnerHTML={shopPaySvg}\n disabled={isCheckoutDisabled}\n onClick={handleShopPayClick}\n />\n )}\n\n {hasInstallments && installmentsMessage && hasItems && (\n <div\n className={styles['rebuy-checkout-area__installments-message']}\n dangerouslySetInnerHTML={{\n __html: installmentsMessage,\n }}\n />\n )}\n\n {/* // TODO: Consider how this will need to be different in the NPM Rebuy Hydrogen package */}\n {/* Pre-Purchase Widget Trigger */}\n {hasPrePurchase && hasItems && <div data-rebuy-id={settings.pre_purchase.widget_id} />}\n </div>\n );\n});\n\nCheckoutArea.displayName = 'CheckoutArea';\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/smart-cart/components/CheckoutArea/CheckoutArea.css\";\n const result = {\"rebuy-checkout-area\":\"CheckoutArea_rebuy-checkout-area\",\"rebuy-checkout-area__terms\":\"CheckoutArea_rebuy-checkout-area__terms\",\"rebuy-checkout-area__terms-checkbox\":\"CheckoutArea_rebuy-checkout-area__terms-checkbox\",\"rebuy-checkout-area__terms-label\":\"CheckoutArea_rebuy-checkout-area__terms-label\",\"rebuy-checkout-area__installments-message\":\"CheckoutArea_rebuy-checkout-area__installments-message\",\"rebuy-checkout-area__checkout-button\":\"CheckoutArea_rebuy-checkout-area__checkout-button\",\"rebuy-checkout-area__view-cart-button\":\"CheckoutArea_rebuy-checkout-area__view-cart-button\",\"rebuy-checkout-area__continue-shopping-button\":\"CheckoutArea_rebuy-checkout-area__continue-shopping-button\",\"rebuy-checkout-area__shop-pay-button\":\"CheckoutArea_rebuy-checkout-area__shop-pay-button\"};\n export default result;\n ", "/* eslint-disable import/order */\nimport { RebuyClient } from '@rebuy/rebuy';\nimport * as Utilities from '@rebuy/rebuy/utilities';\nimport { flattenConnection } from '@shopify/hydrogen';\nimport { useContext, useEffect, useMemo, useRef, useState } from 'react';\nimport { Close } from '~/assets/Close';\nimport { useRebuyConfig } from '~/context/RebuyConfigContext';\nimport { RebuyContext } from '~/context/RebuyContext';\nimport { useBreakpoint } from '~/hooks/useBreakpoint';\nimport { usePopupTrigger } from '~/hooks/usePopupTrigger';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport type {\n CartItem,\n CustomEndpointQueryParams,\n RebuyProduct,\n RecommendedEndpointQueryParams,\n} from '~/types/rebuyCustom';\nimport { widgetSettingsSchema, type WidgetSettings } from '~/types/widgets';\nimport { filterContextForWidgetEndpoints } from '~/utils/filterContextUtils';\nimport type { RebuyWidgetProps } from './types';\nimport { WidgetContent } from './WidgetContent';\n\nimport { DebugKey } from '~/constants/debug';\nimport styles from './RebuyWidget.module.css';\n\nexport const RebuyWidget = (props: RebuyWidgetProps) => {\n const {\n addToCartCallback,\n customTitle,\n customTitleLevel = 'h2',\n customTitleStyle,\n isCrossSell,\n popupTriggerId,\n product,\n productId,\n variant,\n variantId,\n widgetId,\n } = props;\n\n // Get API key and config from the new config context\n const { apiKey: apiKeyFromConfig, loadingStatus: configLoadingStatus, rebuyConfig } = useRebuyConfig();\n\n const [settings, setSettings] = useState<WidgetSettings | null>(null);\n const [loadingSettings, setLoadingSettings] = useState<boolean>(true);\n const [error, setError] = useState<string | null>(null);\n const [showPopup, setShowPopup] = useState<boolean>(false);\n const [popupShownOnce, setPopupShownOnce] = useState<boolean>(false);\n const popupRef = useRef<HTMLDivElement>(null);\n const [clientInstance, setClientInstance] = useState<RebuyClient | null>(null);\n\n // Get general context parameters (for things like cart data, customer info, etc.)\n const rebuyGeneralContext = useContext(RebuyContext);\n const generalContextParams = rebuyGeneralContext?.contextParameters;\n\n // Cache key should primarily come from rebuyConfig, with fallback to general context\n const mainCacheKey = rebuyConfig?.shop?.cache_key;\n const generalContextCacheKey = generalContextParams?.cache_key;\n const cacheKeyToUse = mainCacheKey || generalContextCacheKey || '';\n\n const [initialized, setInitialized] = useState(false);\n const shopifyProductId = product?.id ?? productId ?? null;\n const shopifyVariantId = variant?.id ?? variantId ?? null;\n const [products, setProducts] = useState<RebuyProduct[]>([]);\n\n // Get current breakpoint to check if widget should be displayed\n const currentBreakpoint = useBreakpoint(settings);\n\n // Check if layout style is \"none\" for current breakpoint\n const shouldHideWidget = settings?.layout?.[currentBreakpoint]?.style === 'none';\n\n // Use the custom hook for popup triggers\n usePopupTrigger(settings, popupTriggerId, widgetId, popupShownOnce, showPopup, setShowPopup, setPopupShownOnce);\n\n // Initialize Rebuy API client\n useEffect(() => {\n if (!clientInstance && apiKeyFromConfig && configLoadingStatus === 'success') {\n const client = new RebuyClient(apiKeyFromConfig);\n\n // Set general context parameters if available, using default filter (CustomEndpoint)\n // as settings.endpoint is not yet known here.\n if (generalContextParams) {\n const filteredParams = filterContextForWidgetEndpoints(generalContextParams, undefined);\n client.setContextParameters(filteredParams as Record<string, unknown>);\n }\n\n setClientInstance(client);\n setInitialized(true);\n }\n }, [clientInstance, apiKeyFromConfig, configLoadingStatus, generalContextParams]);\n\n // Update context parameters whenever they change, or when settings are available/change\n useEffect(() => {\n if (!clientInstance || !generalContextParams) return;\n\n // Now filter based on settings.endpoint if available, otherwise default filter.\n const filteredParams = filterContextForWidgetEndpoints(generalContextParams, settings?.endpoint);\n clientInstance.setContextParameters(filteredParams as Record<string, unknown>);\n }, [clientInstance, generalContextParams, settings]);\n\n // Fetch widget settings\n useEffect(() => {\n // Don't proceed if config is still loading\n if (configLoadingStatus === 'loading') {\n return;\n }\n\n // Exit early if essential dependencies for fetching settings are not ready\n if (!widgetId) {\n setError('Widget ID is missing.');\n setSettings(null);\n setLoadingSettings(false);\n\n return;\n }\n\n if (configLoadingStatus === 'error') {\n setError('Rebuy configuration failed to load.');\n setSettings(null);\n setLoadingSettings(false);\n\n return;\n }\n\n if (!apiKeyFromConfig && configLoadingStatus === 'success') {\n setError('Rebuy API Key is missing.');\n setSettings(null);\n setLoadingSettings(false);\n\n return;\n }\n\n if (!clientInstance || !initialized) {\n // Don't set error here - just return and wait for initialization\n return;\n }\n\n const fetchSettings = async () => {\n setLoadingSettings(true);\n setError(null); // Clear previous errors before a new fetch attempt\n try {\n const settingsParams: Record<string, unknown> = { id: widgetId };\n\n if (cacheKeyToUse) {\n settingsParams.cache_key = cacheKeyToUse;\n }\n const settingsResponse = (await clientInstance.getShieldedAsset(\n '/api/v1/widgets/settings',\n settingsParams\n )) as unknown as {\n data: unknown;\n };\n\n // Parse settings data using Zod schema\n const parseResult = widgetSettingsSchema.safeParse(settingsResponse?.data);\n\n if (!parseResult.success) {\n throw new Error(`Invalid settings data: ${parseResult.error.message}`);\n }\n\n const fetchedWidgetSettings = parseResult.data;\n\n if (!fetchedWidgetSettings.endpoint || fetchedWidgetSettings.endpoint.trim() === '') {\n throw new Error('Received invalid settings data: endpoint is missing or invalid.');\n }\n\n setSettings({\n ...fetchedWidgetSettings,\n hide_quantity_selector: fetchedWidgetSettings.hide_quantity_selector ?? false,\n });\n } catch (e) {\n console.error(`[RebuyWidget] Error fetching widget settings for ID ${widgetId}:`, e);\n setError(e instanceof Error ? e.message : 'Failed to load widget configuration.');\n setSettings(null); // Reset settings on error\n } finally {\n setLoadingSettings(false);\n }\n };\n fetchSettings();\n }, [widgetId, clientInstance, configLoadingStatus, apiKeyFromConfig, cacheKeyToUse, initialized]);\n\n // Extract cart product and variant IDs from generalContextParams\n // These IDs are typically numeric in the `contextParameters.cart` object.\n const cartProductIds = useMemo(() => {\n return (generalContextParams?.cart?.items || [])\n .map((item: CartItem) => item.product_id)\n .filter(Boolean)\n .join(',');\n }, [generalContextParams?.cart?.items]);\n\n const cartVariantIds = useMemo(() => {\n return (generalContextParams?.cart?.items || [])\n .map((item: CartItem) => item.variant_id)\n .filter(Boolean)\n .join(',');\n }, [generalContextParams?.cart?.items]);\n\n // Memoize request object on prop changes (e.g. product)\n const request = useMemo(() => {\n const req = {\n endpoint: settings?.endpoint || '/api/v1/products/recommended',\n params: {} as CustomEndpointQueryParams | RecommendedEndpointQueryParams,\n };\n\n if (shopifyProductId) {\n const pId = Utilities.getIdFromGraphUrl(shopifyProductId, 'Product');\n\n if (pId !== null) req.params.shopify_product_ids = pId.toString();\n }\n\n if (shopifyVariantId) {\n const vId = Utilities.getIdFromGraphUrl(shopifyVariantId, 'ProductVariant');\n\n if (vId !== null) req.params.shopify_variant_ids = vId.toString();\n }\n\n if (settings?.limit) {\n req.params.limit = settings.limit;\n }\n\n /* Cart widgets may refresh their products when the cart changes */\n if (settings?.type?.toLowerCase() === 'cart') {\n if (cartProductIds) {\n const existingPids = req.params.shopify_product_ids ? req.params.shopify_product_ids.split(',') : [];\n const cartPidsArray = cartProductIds.split(',');\n req.params.shopify_product_ids = [...new Set([...existingPids, ...cartPidsArray])].join(',');\n }\n\n if (cartVariantIds) {\n const existingVids = req.params.shopify_variant_ids ? req.params.shopify_variant_ids.split(',') : [];\n const cartVidsArray = cartVariantIds.split(',');\n req.params.shopify_variant_ids = [...new Set([...existingVids, ...cartVidsArray])].join(',');\n }\n }\n\n return req;\n }, [settings, shopifyProductId, shopifyVariantId, cartProductIds, cartVariantIds]);\n\n // Update product recommendations on cart or request change\n useEffect(() => {\n let isMounted = true;\n\n if (!clientInstance || !initialized || !settings || configLoadingStatus !== 'success') return;\n\n const fetchData = async () => {\n try {\n // Copy params to avoid mutation. Client context parameters are handled separately.\n const paramsForApi: CustomEndpointQueryParams | RecommendedEndpointQueryParams = {\n ...request.params,\n };\n\n // Ensure we have the cache key\n if (cacheKeyToUse) {\n paramsForApi.cache_key = cacheKeyToUse;\n }\n\n // Add a uuid for cache busting\n paramsForApi.uuid = crypto.randomUUID?.() || Math.random().toString(36).substring(2);\n\n // Make sure API key is included in params sent directly to getStorefrontData,\n // as client contextParameters might not include 'key' by design of the filter.\n if (apiKeyFromConfig) {\n paramsForApi.key = apiKeyFromConfig;\n }\n\n // Fix endpoint if needed\n let endpointToUse = request.endpoint;\n\n if (endpointToUse && endpointToUse.startsWith('/') && !endpointToUse.startsWith('/api/v1/')) {\n if (endpointToUse.startsWith('/custom') || endpointToUse.startsWith('/rules')) {\n endpointToUse = `/api/v1${endpointToUse}`;\n }\n }\n\n const { data } = (await clientInstance.getStorefrontData(endpointToUse, paramsForApi)) as {\n data: RebuyProduct[];\n };\n\n // Set state only if component is still mounted\n if (isMounted) {\n setProducts(\n Array.isArray(data)\n ? data.map((p) => ({\n ...p,\n variants: { nodes: p.variants ? flattenConnection(p.variants) : [] },\n }))\n : []\n );\n }\n } catch (e) {\n console.error(`Error fetching products for widget ID ${widgetId}`, e);\n\n if (isMounted) {\n setProducts([]);\n setError(e instanceof Error ? e.message : 'Failed to load products.');\n }\n }\n };\n\n fetchData();\n\n return () => {\n isMounted = false;\n };\n }, [\n clientInstance,\n initialized,\n request,\n widgetId,\n settings,\n configLoadingStatus,\n apiKeyFromConfig,\n cacheKeyToUse,\n ]);\n\n // Handle click outside popup to close\n useEffect(() => {\n if (!showPopup) return;\n\n const handleClickOutside = (event: MouseEvent) => {\n if (popupRef.current && !popupRef.current.contains(event.target as Node)) {\n setShowPopup(false);\n }\n };\n\n document.addEventListener('mousedown', handleClickOutside);\n\n return () => {\n document.removeEventListener('mousedown', handleClickOutside);\n };\n }, [showPopup]);\n\n const closePopup = () => {\n setShowPopup(false);\n };\n\n if (configLoadingStatus === 'loading') return null;\n\n if (configLoadingStatus === 'error') {\n console.error('Rebuy configuration failed to load');\n\n return null;\n }\n\n // If products array is empty AND settings are loaded AND not currently loading settings,\n // then we can confidently say there are no products.\n if (products?.length === 0 && settings && !loadingSettings) {\n rebuyDebugLog.log(DebugKey.WIDGET, 'No products to render for widgetId:', widgetId);\n\n return null;\n }\n\n if (error && !products?.length) {\n // Only return null for error if there are no products to show\n console.error('[RebuyWidget] Error state:', error);\n\n return null;\n }\n\n // If layout style is \"none\" for current breakpoint, don't render anything\n if (settings && !loadingSettings && shouldHideWidget) {\n return null;\n }\n\n return (\n <>\n {/* Render only if not loading settings, and either products exist or settings are not yet fully processed (to avoid flicker) */}\n {(settings || products?.length > 0) && !loadingSettings && (\n <div className={styles['rebuy-widget__container']} id={`rebuy-widget-${widgetId}`}>\n {settings?.display_type === 'popup' &&\n (settings.popup_trigger !== 'add_to_cart' ||\n (settings.popup_trigger === 'add_to_cart' && popupTriggerId)) ? (\n <div>\n {showPopup && (\n <div className={styles['rebuy-widget__popup-overlay']}>\n <div className={styles['rebuy-widget__popup-content']} ref={popupRef}>\n <div className={styles['rebuy-widget__content']}>\n <button\n aria-label=\"close modal\"\n className={styles['rebuy-widget__modal-close']}\n onClick={closePopup}\n >\n <Close />\n </button>\n <WidgetContent\n addToCartCallback={() => {\n addToCartCallback?.();\n // Set timeout is required: Do not touch\n setTimeout(() => {\n closePopup();\n }, 0);\n }}\n customTitle={customTitle}\n customTitleLevel={customTitleLevel}\n customTitleStyle={customTitleStyle}\n isHydrogenReact={\n rebuyGeneralContext?.contextParameters?.isHydrogenReact\n }\n isInPopup={true} // Explicitly true for popup\n onDismiss={closePopup}\n products={products}\n settings={settings!} // settings will be non-null here\n />\n </div>\n </div>\n </div>\n )}\n </div>\n ) : (\n <div className={styles['rebuy-widget__content']}>\n <WidgetContent\n addToCartCallback={addToCartCallback}\n customTitle={customTitle}\n customTitleLevel={customTitleLevel}\n customTitleStyle={customTitleStyle}\n isCrossSell={isCrossSell} // Only present in embedded to support in cart widgets\n isHydrogenReact={rebuyGeneralContext?.contextParameters?.isHydrogenReact}\n isInPopup={settings?.display_type === 'popup'} // Correctly reflect if it's a popup type\n products={products}\n settings={settings!} // settings will be non-null here due to outer check\n />\n </div>\n )}\n </div>\n )}\n </>\n );\n};\n", "export const Close = () => {\n return (\n <svg height=\"1em\" viewBox=\"0 0 352 512\" width=\"1em\">\n <path d=\"M242.72 256l100.07-100.07c12.28-12.28 12.28-32.19 0-44.48l-22.24-22.24c-12.28-12.28-32.19-12.28-44.48 0L176 189.28 75.93 89.21c-12.28-12.28-32.19-12.28-44.48 0L9.21 111.45c-12.28 12.28-12.28 32.19 0 44.48L109.28 256 9.21 356.07c-12.28 12.28-12.28 32.19 0 44.48l22.24 22.24c12.28 12.28 32.19 12.28 44.48 0L176 322.72l100.07 100.07c12.28 12.28 32.19 12.28 44.48 0l22.24-22.24c12.28-12.28 12.28-32.19 0-44.48L242.72 256z\" />\n </svg>\n );\n};\n", "import { useEffect, useState } from 'react';\nimport type { WidgetSettings } from '~/types/widgets';\n\ntype Breakpoint = 'small' | 'medium' | 'large';\n\nexport const useBreakpoint = (settings: WidgetSettings | null): Breakpoint => {\n const [breakpoint, setBreakpoint] = useState<Breakpoint>('medium');\n\n useEffect(() => {\n if (!settings?.breakpoints) return;\n\n const handleResize = () => {\n const width = window.innerWidth;\n\n // Convert breakpoint values to numbers for comparison\n const mediumMax =\n typeof settings.breakpoints.medium.max === 'number'\n ? settings.breakpoints.medium.max\n : parseFloat(settings.breakpoints.medium.max) || 0;\n const mediumMin =\n typeof settings.breakpoints.medium.min === 'number'\n ? settings.breakpoints.medium.min\n : parseFloat(settings.breakpoints.medium.min) || 0;\n\n if (width <= mediumMax) {\n if (width >= mediumMin) {\n setBreakpoint('medium');\n } else {\n setBreakpoint('small');\n }\n } else {\n setBreakpoint('large');\n }\n };\n\n // Set initial breakpoint\n handleResize();\n\n // Debounce configuration\n const debounceDelay = 150; // ms\n let timeoutId: ReturnType<typeof setTimeout>;\n\n // Debounced resize handler\n const debouncedHandleResize = () => {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(handleResize, debounceDelay);\n };\n\n // Add resize listener with debounce\n window.addEventListener('resize', debouncedHandleResize);\n\n // Clean up\n return () => {\n window.removeEventListener('resize', debouncedHandleResize);\n clearTimeout(timeoutId);\n };\n }, [settings]);\n\n return breakpoint;\n};\n", "import { useCallback, useEffect } from 'react';\nimport type { WidgetSettings } from '~/types/widgets';\n\nexport const usePopupTrigger = (\n settings: WidgetSettings | null,\n popupTriggerId: string | undefined,\n widgetId: string,\n popupShownOnce: boolean,\n showPopup: boolean,\n setShowPopup: (show: boolean) => void,\n setPopupShownOnce: (shown: boolean) => void\n) => {\n const delayInMs = settings?.display_type === 'popup' ? (settings?.popup_delay || 0) * 1000 : 0;\n const popupTrigger = settings?.popup_trigger;\n\n const showPopupWithDelay = useCallback(() => {\n if (!settings || settings.display_type !== 'popup') return;\n\n setTimeout(() => {\n setShowPopup(true);\n setPopupShownOnce(true);\n }, delayInMs);\n }, [delayInMs, setShowPopup, setPopupShownOnce, settings]);\n\n // Handle load trigger\n useEffect(() => {\n if (!settings || settings.display_type !== 'popup' || popupTrigger !== 'load' || popupShownOnce) return;\n\n const timer = setTimeout(() => {\n setShowPopup(true);\n setPopupShownOnce(true);\n }, delayInMs);\n\n return () => clearTimeout(timer);\n }, [popupTrigger, popupShownOnce, delayInMs, setShowPopup, setPopupShownOnce, settings]);\n\n // Handle add_to_cart trigger\n useEffect(() => {\n if (!settings || settings.display_type !== 'popup' || popupTrigger !== 'add_to_cart' || !popupTriggerId) return;\n\n const selector = `#${popupTriggerId}`;\n const handleCartAdd = () => {\n if (!showPopup) {\n showPopupWithDelay();\n }\n };\n\n // Setup a mutation observer to watch for the element if it's not immediately available\n const observer = new MutationObserver(() => {\n const elements = document.querySelectorAll(selector);\n\n if (elements.length) {\n elements.forEach((el) => {\n el.addEventListener('click', handleCartAdd);\n });\n observer.disconnect();\n }\n });\n\n // First check if element already exists\n const elements = document.querySelectorAll(selector);\n\n if (elements.length) {\n elements.forEach((el) => {\n el.addEventListener('click', handleCartAdd);\n });\n } else {\n // If not, start observing\n observer.observe(document.body, { childList: true, subtree: true });\n }\n\n return () => {\n observer.disconnect();\n document.querySelectorAll(selector).forEach((el) => {\n el.removeEventListener('click', handleCartAdd);\n });\n };\n }, [popupTrigger, popupTriggerId, showPopup, showPopupWithDelay, settings]);\n\n // Handle form submit trigger\n useEffect(() => {\n if (!settings || settings.display_type !== 'popup' || popupTrigger !== 'submit') return;\n\n const selector = 'form';\n const handleSubmit = () => {\n showPopupWithDelay();\n };\n\n const forms = document.querySelectorAll(selector);\n forms.forEach((form) => {\n form.addEventListener('submit', handleSubmit);\n });\n\n return () => {\n forms.forEach((form) => {\n form.removeEventListener('submit', handleSubmit);\n });\n };\n }, [popupTrigger, showPopupWithDelay, settings]);\n\n // Handle exit intent trigger\n useEffect(() => {\n if (!settings || settings.display_type !== 'popup' || popupTrigger !== 'exit') return;\n\n const handleExitIntent = (e: MouseEvent) => {\n if (e.clientY <= 0 && !popupShownOnce) {\n showPopupWithDelay();\n }\n };\n\n const handleVisibilityChange = () => {\n if (document.visibilityState === 'hidden' && !popupShownOnce) {\n const shouldShowOnFocus = true;\n localStorage.setItem(`rebuy-popup-pending-${widgetId}`, shouldShowOnFocus.toString());\n } else if (document.visibilityState === 'visible') {\n const pendingPopup = localStorage.getItem(`rebuy-popup-pending-${widgetId}`);\n\n if (pendingPopup === 'true' && !popupShownOnce) {\n showPopupWithDelay();\n localStorage.removeItem(`rebuy-popup-pending-${widgetId}`);\n }\n }\n };\n\n document.addEventListener('mouseleave', handleExitIntent);\n document.addEventListener('visibilitychange', handleVisibilityChange);\n\n // Check visibility state on mount\n if (document.visibilityState === 'visible') {\n const pendingPopup = localStorage.getItem(`rebuy-popup-pending-${widgetId}`);\n\n if (pendingPopup === 'true' && !popupShownOnce) {\n showPopupWithDelay();\n localStorage.removeItem(`rebuy-popup-pending-${widgetId}`);\n }\n }\n\n return () => {\n document.removeEventListener('mouseleave', handleExitIntent);\n document.removeEventListener('visibilitychange', handleVisibilityChange);\n };\n }, [popupTrigger, popupShownOnce, showPopupWithDelay, widgetId, settings]);\n};\n", "import { z } from 'zod';\nimport { type RebuyProduct, type RebuyProductVariant, type RebuyWidgetMetadata } from '~/types/rebuyCustom';\nimport type { HydrogenProduct } from '~/types/shopify';\n\nconst integrationsSchema = z.object({\n judgeme: z.boolean(),\n junip: z.boolean(),\n klaviyo: z.boolean(),\n loox: z.boolean(),\n okendo: z.boolean(),\n opinew: z.boolean(),\n recharge: z.boolean(),\n reviewsio: z.boolean(),\n stamped: z.boolean(),\n yotpo: z.boolean(),\n});\n\nconst discountSchema = z.object({\n amount: z.union([z.string(), z.number()]),\n bundle_protection: z\n .object({\n allowed_removals: z.number(),\n disable_atc_on_incomplete: z.boolean(),\n enabled: z.boolean(),\n })\n .optional(),\n discount_protection: z\n .object({\n enabled: z.boolean(),\n minimum_items_to_get_discount: z.number(),\n })\n .optional(),\n discounted_by: z.string().optional(),\n discounted_from: z.string().optional(),\n discountedBy: z.string().optional(),\n discountedFrom: z.string().optional(),\n message: z.string().optional(),\n quantity: z.number().optional(),\n show_saving_amount: z.boolean().optional(),\n showSavingAmount: z.boolean().optional(),\n type: z.string(),\n});\n\nconst excludeItemsSchema = z.object({\n digital_items: z.boolean(),\n gift_cards: z.boolean(),\n});\n\nconst timerSchema = z.object({\n action: z.enum(['dismiss', 'checkout', 'cart', 'stop']),\n duration_minutes: z.union([z.number(), z.null()]),\n duration_seconds: z.union([z.number(), z.null()]),\n enabled: z.boolean(),\n});\n\nconst layoutSizeSchema = z.object({\n carousel: z.boolean(),\n columns: z.number(),\n show_paginations: z.boolean(),\n style: z.string(),\n});\n\nconst layoutSchema = z.object({\n large: layoutSizeSchema,\n medium: layoutSizeSchema,\n small: layoutSizeSchema,\n});\n\nconst productOptionsSchema = z.object({\n hide_out_of_stock_variants: z.boolean(),\n match_on_selling_plan: z.boolean().optional(),\n match_variant: z.boolean(),\n match_variant_out_of_stock: z.boolean().optional(),\n show_product_description: z.enum(['show', 'hide']),\n show_subscription_options: z.string(),\n show_variant_options: z.enum(['default', 'never', 'always', 'dynamic']),\n show_variant_title: z.enum(['show', 'hide']),\n show_variants_as_products: z.boolean(),\n variant_display_limit: z.string(),\n});\n\nconst viewOptionsSchema = z.object({\n cookie_days: z.number(),\n display_actions: z.boolean(),\n limit_views: z.boolean(),\n max_views: z.number(),\n variant_selector: z.string(),\n});\n\nconst imagesSchema = z.object({\n border_radius: z.number(),\n border_radius_unit: z.string(),\n fixed_height: z.boolean(),\n fixed_width: z.boolean(),\n height: z.number(),\n source: z.string(),\n width: z.number(),\n});\n\nconst breakpointSizeSchema = z.object({\n max: z.union([z.string(), z.number()]),\n min: z.union([z.string(), z.number()]),\n});\n\nconst breakpointsSchema = z.object({\n large: breakpointSizeSchema,\n medium: breakpointSizeSchema,\n small: breakpointSizeSchema,\n});\n\nconst placementSizeSchema = z.object({\n enabled: z.boolean(),\n location: z.string(),\n selector: z.string().nullable(),\n});\n\nconst placementSchema = z.object({\n large: placementSizeSchema,\n medium: placementSizeSchema,\n small: placementSizeSchema,\n});\n\nconst languageSchema = z.object({\n add_to_cart: z.string(),\n added_to_cart: z.string(),\n adding_to_cart: z.string(),\n cart_switch_to_onetime: z.string(),\n cart_switch_to_subscription: z.string(),\n cart_switch_to_subscription_footer: z.string(),\n checkout: z.string(),\n continue: z.string(),\n decline: z.string(),\n delivery_frequency_label: z.string(),\n description: z.string(),\n learn_more_label: z.string(),\n remove_body: z.string(),\n remove_confirm: z.string(),\n remove_deny: z.string(),\n remove_from_cart: z.string(),\n remove_title: z.string(),\n removed_from_cart: z.string(),\n removing_from_cart: z.string(),\n saving_amount_text: z.string(),\n sold_out_label: z.string(),\n super_title: z.string(),\n thank_you_button: z.string(),\n thank_you_description: z.string(),\n thank_you_title: z.string(),\n timer_title: z.string(),\n title: z.string(),\n total_price_label: z.string(),\n upgrade_to_subscription: z.string(),\n variant_option: z.string(),\n variant_options: z.string(),\n});\n\nconst quantityInputsSchema = z.object({\n default_quantity: z.number(),\n enabled: z.boolean(),\n max_value: z.number(),\n min_value: z.number(),\n});\n\nconst stylesSchema = z.object({\n background_color: z.string(),\n border_color: z.string(),\n button_background: z.string(),\n button_border_color: z.string(),\n button_border_width: z.union([z.string(), z.number()]),\n button_radius: z.union([z.string(), z.number()]),\n button_text: z.string(),\n carousel_control_background: z.string(),\n carousel_control_text: z.string(),\n carousel_paging_dots: z.string(),\n compare_price: z.string(),\n custom_css: z.string(),\n description: z.string(),\n input_background: z.string(),\n input_border: z.string(),\n input_text: z.string(),\n price: z.string(),\n product_description: z.string(),\n product_title: z.string(),\n reviews_background: z.string(),\n reviews_foreground: z.string(),\n reviews_text: z.string(),\n sale_price: z.string(),\n supertitle: z.string(),\n title: z.string(),\n});\n\nconst trackingSchema = z.object({\n enable_attribution: z.boolean(),\n enable_product_discovery: z.boolean(),\n enable_source: z.boolean(),\n enable_widget: z.boolean(),\n});\n\nconst callbackSchema = z.object({\n enabled: z.boolean(),\n function: z.string(),\n});\n\nconst callbacksSchema = z.object({\n add: callbackSchema,\n alternativePaymentsRefresh: callbackSchema,\n beforeAdd: callbackSchema,\n beforeChange: callbackSchema,\n beforeDecline: callbackSchema,\n beforeHide: callbackSchema,\n beforeProductsChange: callbackSchema,\n beforeReady: callbackSchema,\n beforeRemove: callbackSchema,\n beforeShow: callbackSchema,\n change: callbackSchema,\n decline: callbackSchema,\n hide: callbackSchema,\n init: callbackSchema,\n productsChange: callbackSchema,\n ready: callbackSchema,\n refresh: callbackSchema,\n remove: callbackSchema,\n selectedVariantChange: callbackSchema,\n shippingRateRefresh: callbackSchema,\n show: callbackSchema,\n view: callbackSchema,\n});\n\nconst shopSchema = z.object({\n currency: z.string(),\n money_format: z.string(),\n myshopify_domain: z.string(),\n});\n\nexport const widgetSettingsSchema = z\n .object({\n advance: z.union([z.array(z.any()), z.object({}).passthrough()]).optional(),\n allow_gifts_without_purchase: z.boolean().optional(),\n allow_remove: z.boolean().optional(),\n breakpoints: breakpointsSchema,\n callbacks: callbacksSchema,\n close_redirect: z.string().optional(),\n decline_redirect: z.string().optional(),\n discount: discountSchema,\n display_type: z.string().optional(),\n endpoint: z.string().min(1),\n exclude_items: excludeItemsSchema,\n hide_quantity_selector: z.boolean().optional(),\n images: imagesSchema,\n integrations: integrationsSchema.optional(),\n key: z.string().optional(),\n language: languageSchema,\n layout: layoutSchema,\n learn_more: z.string().optional(),\n limit: z.number().optional(),\n metafields: z.boolean().optional(),\n placement: placementSchema,\n popup_delay: z.number().optional(),\n popup_trigger: z.string().optional(),\n popup_trigger_selector: z.string().optional(),\n preview_mode: z.boolean().optional(),\n product_options: productOptionsSchema,\n product_type: z.string().optional(),\n quantity_inputs: quantityInputsSchema,\n redirect: z.string().optional(),\n remove_redirect: z.string().optional(),\n shipping: z.union([z.array(z.any()), z.object({}).passthrough()]).optional(),\n shop: shopSchema.optional(),\n show_continue_button: z.boolean().optional(),\n styles: stylesSchema,\n subscription: z.union([z.array(z.any()), z.object({}).passthrough()]).optional(),\n subscription_is_default: z.boolean().optional(),\n theme: z.string().optional(),\n timer: timerSchema,\n tracking: trackingSchema,\n type: z.string().optional(),\n variant_metafields: z.boolean().optional(),\n view_options: viewOptionsSchema,\n })\n .passthrough();\n\nexport const widgetConfigSettingsSchema = z.object({\n config: widgetSettingsSchema,\n});\n\nexport const widgetNestedConfigSettingsSchema = z.object({\n data: z.object({\n config: widgetSettingsSchema,\n }),\n});\n\nexport const widgetConfigUnionSettingsSchema = z.union([widgetConfigSettingsSchema, widgetNestedConfigSettingsSchema]);\n\nexport type WidgetSettings = z.infer<typeof widgetSettingsSchema>;\nexport type WidgetConfig = z.infer<typeof widgetConfigSettingsSchema>;\nexport type WidgetConfigUnionSettings = z.infer<typeof widgetConfigUnionSettingsSchema>;\n\nexport type RebuyWidgetContextType = {\n apiKey?: string;\n cacheKey?: string;\n dataSource: string;\n isHydrogenReact: boolean;\n key: string;\n limit: number;\n metadata: RebuyWidgetMetadata;\n options: Record<string, unknown>;\n product?: HydrogenProduct;\n productId?: string;\n products: RebuyProduct[];\n variant?: RebuyProductVariant;\n variantId?: string;\n};\n\nexport type WidgetChildProps = {\n addToCartCallback?: () => void;\n cacheKey?: string;\n customTitle?: string;\n customTitleLevel?: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';\n customTitleStyle?: React.CSSProperties;\n};\n", "import type { ContextParameters, CustomEndpointQueryParams, RecommendedEndpointQueryParams } from '~/types/rebuyCustom';\n\n// Helper function to filter context parameters\nexport const filterContextForWidgetEndpoints = (\n sourceParams: Readonly<ContextParameters> | undefined | null,\n endpointUrl?: string // Optional endpoint URL\n): Partial<CustomEndpointQueryParams | RecommendedEndpointQueryParams> => {\n if (!sourceParams) {\n return {};\n }\n\n const filtered: Partial<CustomEndpointQueryParams | RecommendedEndpointQueryParams> = {};\n let allowedKeys: string[];\n\n if (endpointUrl === '/api/v1/products/recommended') {\n allowedKeys = [\n 'shopify_product_ids',\n 'shopify_collection_id',\n 'shopify_variant_ids',\n 'metafields',\n 'variant_metafields',\n 'bust_cache',\n 'format',\n 'limit',\n 'any_variant_price_less_than',\n 'any_variant_price_less_than_or_equal_to',\n 'any_variant_price_equal_to',\n 'variant_price_greater_than',\n 'variant_price_greater_than_or_equal_to',\n 'unset_variants',\n 'filter_oos',\n 'context',\n 'country_code',\n ];\n } else {\n // Default to CustomEndpointQueryParams keys for custom data sources or if endpoint is initially unknown\n allowedKeys = [\n 'shopify_product_ids',\n 'shopify_variant_ids',\n 'shopify_customer_id',\n 'cart_subtotal',\n 'cart_line_count',\n 'cart_item_count',\n 'metafields',\n 'variant_metafields',\n 'time',\n 'limit',\n 'url',\n 'format',\n 'country_code',\n ];\n }\n\n for (const key of allowedKeys) {\n if (key === 'cart_item_count' && endpointUrl !== '/api/v1/products/recommended') {\n if (\n Object.prototype.hasOwnProperty.call(sourceParams, 'cart_item_count') &&\n sourceParams.cart_item_count !== undefined\n ) {\n (filtered as Partial<CustomEndpointQueryParams>).cart_item_count = sourceParams.cart_item_count;\n } else if (\n Object.prototype.hasOwnProperty.call(sourceParams, 'cart_count') &&\n sourceParams.cart_count !== undefined\n ) {\n (filtered as Partial<CustomEndpointQueryParams>).cart_item_count = sourceParams.cart_count;\n }\n } else if (Object.prototype.hasOwnProperty.call(sourceParams, key)) {\n const value = (sourceParams as Record<string, unknown>)[key];\n\n if (value !== undefined) {\n (filtered as Record<string, unknown>)[key] = value;\n }\n }\n }\n\n return filtered;\n};\n", "import type { ProductCardSettings } from './types';\n\nexport const defaultProductCardSettings: ProductCardSettings = {\n layoutStyle: 'grid',\n productOptions: {\n hide_out_of_stock_variants: false,\n match_variant: false,\n match_variant_out_of_stock: false,\n show_product_description: 'hide',\n show_subscription_options: 'always',\n show_variant_options: 'always',\n show_variant_title: 'show',\n show_variants_as_products: false,\n variant_display_limit: 'product_limit',\n },\n quantityInput: {\n default_quantity: 1,\n enabled: true,\n max_value: 11,\n min_value: 1,\n },\n settingsDiscount: {\n amount: 0,\n bundle_protection: {\n allowed_removals: 0,\n disable_atc_on_incomplete: false,\n enabled: false,\n },\n discount_protection: {\n enabled: false,\n minimum_items_to_get_discount: 2,\n },\n discounted_by: 'other',\n discounted_from: 'original_price',\n message: '',\n quantity: 1,\n show_saving_amount: false,\n type: 'none',\n },\n variantSelector: 'select',\n};\n", "import { Image } from '@shopify/hydrogen';\nimport { useCallback, useMemo, useState } from 'react';\n\nimport { AddToCartBtn } from '~/components/AddToCartBtn';\nimport { defaultProductCardSettings } from '~/components/ProductCard/defaultSettings';\nimport type { ProductCardProps } from '~/components/ProductCard/types';\nimport { RebuyProductPrice } from '~/components/ProductPrice/ProductPrice';\nimport { QuantityInput } from '~/components/QuantityInput';\nimport { RebuyLink } from '~/components/RebuyLink';\nimport { VariantSelect } from '~/components/VariantSelect';\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport type { RebuyProduct } from '~/types/rebuyCustom';\nimport { Title } from '../Title';\nimport styles from './ProductCard.module.css';\n\ntype ProductInteractionStatus = 'ready' | 'selecting';\n\nexport const ProductCard = ({\n addToCartBtnText,\n addToCartCallback,\n isCrossSell,\n isHydrogenReact,\n isInPopup,\n onPopupDismiss,\n product,\n productCardTitleLevel,\n settings = defaultProductCardSettings,\n variantOptionsText,\n}: ProductCardProps) => {\n const [selectedVariant, setSelectedVariant] = useState(product.variants.nodes[0]);\n const [selectedQuantity, setSelectedQuantity] = useState<number>(settings?.quantityInput?.default_quantity || 1);\n const [interactionStatus, setInteractionStatus] = useState<ProductInteractionStatus>('ready');\n\n const { toggleCart } = useSmartCart();\n\n const displayImage = selectedVariant.image || product.featuredImage;\n\n const handleSelectedVariant = useCallback((product: RebuyProduct, variant_id: string) => {\n const updatedVariant = product.variants.nodes.find((variant) => variant.id === variant_id);\n\n if (updatedVariant) {\n setSelectedVariant(updatedVariant);\n }\n }, []);\n\n const handleSelectedQuantity = useCallback((quantity: number) => {\n setSelectedQuantity(quantity);\n }, []);\n\n const handleLinkClick = useCallback(() => {\n if (isCrossSell) {\n toggleCart();\n }\n\n if (isInPopup && onPopupDismiss) {\n onPopupDismiss();\n }\n }, [isInPopup, onPopupDismiss]);\n\n const cardLayout = settings?.layoutStyle || 'grid';\n const productOptions = settings?.productOptions;\n const showVariantOptionsSetting = productOptions?.show_variant_options || 'always';\n\n const showVariantSelect = useMemo(() => {\n if (product?.variants.nodes.length <= 1) {\n const firstVariantTitle = product.variants.nodes[0]?.title?.toLowerCase();\n\n if (firstVariantTitle === 'default title' || firstVariantTitle === 'default') {\n return false;\n }\n\n return showVariantOptionsSetting === 'always';\n }\n\n switch (showVariantOptionsSetting) {\n case 'always':\n return true;\n case 'never':\n return false;\n case 'dynamic':\n return interactionStatus === 'selecting';\n case 'default':\n default:\n if (cardLayout === 'line') {\n return interactionStatus === 'selecting';\n }\n\n return true;\n }\n }, [product?.variants.nodes, showVariantOptionsSetting, interactionStatus, cardLayout]);\n\n const isSelectionRequiredBeforeAddToCart = useMemo(() => {\n return product?.variants.nodes.length > 1 && !showVariantSelect && interactionStatus === 'ready';\n }, [product?.variants.nodes, showVariantSelect, interactionStatus]);\n\n const atcButtonLabel = useMemo(() => {\n if (isSelectionRequiredBeforeAddToCart) {\n if (product.options && product.options.length === 1) {\n return `${product.options[0].name}`;\n }\n\n return variantOptionsText || 'Options';\n }\n\n return addToCartBtnText || 'Add to Cart';\n }, [isSelectionRequiredBeforeAddToCart, product.options, variantOptionsText, addToCartBtnText]);\n\n const handlePrimaryAction = useCallback(() => {\n if (isSelectionRequiredBeforeAddToCart) {\n setInteractionStatus('selecting');\n } else {\n // If addToCartCallback exists, it will be called by the AddToCartBtn after successful Shopify add\n if (isInPopup && onPopupDismiss) {\n onPopupDismiss();\n }\n }\n }, [isSelectionRequiredBeforeAddToCart, isInPopup, onPopupDismiss]);\n\n const showVariantTitle =\n settings?.productOptions?.show_variant_title === 'show' &&\n selectedVariant.title.toLowerCase() !== 'default title';\n const showReviews = product.reviews && product?.reviews?.review_count && product?.reviews?.review_count > 0;\n const productReviewsRating = product.reviews?.star_rating;\n const showProductDescription =\n settings?.productOptions?.show_product_description === 'show' &&\n product.description !== '' &&\n product.description !== null;\n const showQuantityInput =\n settings?.quantityInput?.enabled &&\n settings?.quantityInput?.max_value !== null &&\n settings?.quantityInput?.min_value !== null;\n\n return (\n <div className={styles['rebuy-product-card__container']}>\n <div className={styles['rebuy-product-card']} data-layout={cardLayout}>\n <div>\n <RebuyLink\n ariaLabel={`View ${product.title}`}\n className={styles['rebuy-product-card__media-link']}\n handle={`/products/${product.handle}`}\n onClick={handleLinkClick}\n >\n <Image\n alt={displayImage?.altText ?? `Picture of ${product.title}`}\n className={styles['rebuy-product-card__image']}\n data={displayImage}\n sizes=\"(max-width: 320px) 280px, (max-width: 768px) 720px, 1440px\"\n />\n </RebuyLink>\n\n {settings?.layoutStyle === 'grid' && (\n <div className={styles['rebuy-product-card__content']}>\n <div className={styles['rebuy-product-card__header']}>\n {product.vendor && (\n <p className={styles['rebuy-product-card__vendor']}>{product.vendor}</p>\n )}\n <RebuyLink\n ariaLabel={`View ${product.title}`}\n className={styles['rebuy-product-card__title-link']}\n handle={`/products/${product.handle}`}\n onClick={handleLinkClick}\n >\n <Title\n className={styles['rebuy-product-card__title']}\n level={productCardTitleLevel}\n text={product.title}\n />\n </RebuyLink>\n {showVariantTitle && (\n <div className={styles['rebuy-product-card__variant-title']}>\n {selectedVariant.title}\n </div>\n )}\n </div>\n\n <RebuyProductPrice\n selectedVariant={selectedVariant}\n settingsDiscount={settings?.settingsDiscount}\n />\n\n {showReviews && (\n <div aria-label=\"product star rating\" className={styles['rebuy-product-card__review']}>\n <span className={styles['rebuy-product-card__star-rating']}>\n {productReviewsRating && (\n <span className={styles['rebuy-product-card__star-rating-value']}>\n {productReviewsRating} stars out of 5 stars\n </span>\n )}\n <span className={styles['rebuy-product-card__star-rating-background']}></span>\n <span\n className={styles['rebuy-product-card__star-rating-foreground']}\n style={\n productReviewsRating\n ? { width: (productReviewsRating / 5) * 100 + '%' }\n : {}\n }\n ></span>\n </span>\n {product.reviews?.review_count && (\n <span className={styles['rebuy-product-card__review-count']}>\n ({product.reviews.review_count})\n </span>\n )}\n </div>\n )}\n {showProductDescription && (\n <div className={styles['rebuy-product-card__description']}>\n <p>{product.description}</p>\n </div>\n )}\n </div>\n )}\n </div>\n <div className={styles['rebuy-product-card__info']}>\n {settings?.layoutStyle !== 'grid' && (\n <div className={styles['rebuy-product-card__content']}>\n <div className={styles['rebuy-product-card__header']}>\n {product.vendor && (\n <p className={styles['rebuy-product-card__vendor']}>{product.vendor}</p>\n )}\n <RebuyLink\n ariaLabel={`View ${product.title}`}\n className={styles['rebuy-product-card__title-link']}\n handle={`/products/${product.handle}`}\n onClick={handleLinkClick}\n >\n <Title\n className={styles['rebuy-product-card__title']}\n level={productCardTitleLevel}\n text={product.title}\n />\n </RebuyLink>\n {showVariantTitle && (\n <div className={styles['rebuy-product-card__variant-title']}>\n {selectedVariant.title}\n </div>\n )}\n </div>\n\n <RebuyProductPrice\n selectedVariant={selectedVariant}\n settingsDiscount={settings?.settingsDiscount}\n />\n\n {showReviews && (\n <div aria-label=\"product star rating\" className={styles['rebuy-product-card__review']}>\n <span className={styles['rebuy-product-card__star-rating']}>\n {productReviewsRating && (\n <span className={styles['rebuy-product-card__star-rating-value']}>\n {productReviewsRating} stars out of 5 stars\n </span>\n )}\n <span className={styles['rebuy-product-card__star-rating-background']}></span>\n <span\n className={styles['rebuy-product-card__star-rating-foreground']}\n style={\n productReviewsRating\n ? { width: (productReviewsRating / 5) * 100 + '%' }\n : {}\n }\n ></span>\n </span>\n {product.reviews?.review_count && (\n <span className={styles['rebuy-product-card__review-count']}>\n ({product.reviews.review_count})\n </span>\n )}\n </div>\n )}\n {showProductDescription && (\n <div className={styles['rebuy-product-card__description']}>\n <p>{product.description}</p>\n </div>\n )}\n </div>\n )}\n <div className={styles['rebuy-product-card__actions']}>\n {showVariantSelect && cardLayout !== 'line' && (\n <div\n className={styles['rebuy-product-card__actions-variant-select']}\n data-layout={cardLayout}\n >\n <VariantSelect\n handleSelectedVariant={handleSelectedVariant}\n product={product}\n selectedId={selectedVariant.id}\n style={settings?.variantSelector}\n />\n </div>\n )}\n {showQuantityInput && (\n <div className={styles['rebuy-product-card__actions-quantity']}>\n <QuantityInput\n defaultQuantity={settings?.quantityInput?.default_quantity}\n handleSelectedQuantity={handleSelectedQuantity}\n maxValue={settings?.quantityInput?.max_value}\n minValue={settings?.quantityInput?.min_value}\n />\n </div>\n )}\n <div className={styles['rebuy-product-card__actions-button']}>\n <AddToCartBtn\n addToCartBtnText={atcButtonLabel}\n addToCartCallback={addToCartCallback}\n disableShopifyAddAction={isSelectionRequiredBeforeAddToCart}\n isHydrogenReact={isHydrogenReact}\n onClickAction={handlePrimaryAction}\n quantity={selectedQuantity}\n selectedVariants={isSelectionRequiredBeforeAddToCart ? [] : [selectedVariant]}\n />\n </div>\n </div>\n </div>\n </div>\n {showVariantSelect && cardLayout === 'line' && (\n <div className={styles['rebuy-product-card__variant-select']} data-layout={cardLayout}>\n <VariantSelect\n handleSelectedVariant={handleSelectedVariant}\n product={product}\n selectedId={selectedVariant.id}\n style={settings?.variantSelector}\n />\n </div>\n )}\n </div>\n );\n};\n", "import { CartForm, Money } from '@shopify/hydrogen';\nimport { type FetcherWithComponents } from 'react-router';\n\nimport type { btnProps } from '~/components/AddToCartBtn/types';\nimport styles from './AddToCartBtn.module.css';\n\nexport const HydrogenAddToCartBtn = ({\n addToCartBtnText,\n addToCartCallback,\n disableShopifyAddAction,\n disabled,\n linesToAdd,\n moneyData,\n onClickAction,\n}: btnProps) => {\n const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {\n // First, execute the click action if provided\n if (onClickAction) {\n onClickAction();\n }\n\n // If we should disable the Shopify add action, prevent form submission\n if (disableShopifyAddAction) {\n event.preventDefault();\n\n return;\n }\n\n // Otherwise, let the form submission proceed normally\n // The addToCartCallback will be called after successful submission\n if (addToCartCallback) {\n addToCartCallback();\n }\n };\n\n return (\n <div className={styles['rebuy-cart-button__container']}>\n <CartForm\n action={CartForm.ACTIONS.LinesAdd}\n inputs={{\n lines: linesToAdd,\n }}\n route=\"/cart\"\n >\n {(fetcher: FetcherWithComponents<unknown>) => (\n <>\n <button\n className={styles['rebuy-cart-button']}\n disabled={disabled || fetcher.state !== 'idle'}\n onClick={handleClick}\n type=\"submit\"\n >\n {addToCartBtnText}\n {moneyData && (\n <>\n <span> | </span>\n <Money data={moneyData} withoutTrailingZeros />\n </>\n )}\n </button>\n </>\n )}\n </CartForm>\n </div>\n );\n};\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/components/AddToCartBtn/AddToCartBtn.css\";\n const result = {\"rebuy-cart-button\":\"AddToCartBtn_rebuy-cart-button\",\"rebuy-cart-button__container\":\"AddToCartBtn_rebuy-cart-button__container\"};\n export default result;\n ", "import { Money, useCart } from '@shopify/hydrogen-react';\n\nimport type { btnProps } from '~/components/AddToCartBtn/types';\nimport styles from './AddToCartBtn.module.css';\n\nexport const HydrogenReactAddToCartBtn = ({\n addToCartBtnText,\n addToCartCallback,\n disableShopifyAddAction,\n disabled,\n linesToAdd,\n moneyData,\n onClickAction,\n}: btnProps) => {\n const { linesAdd } = useCart();\n\n const handleAddToCart = () => {\n // First, execute the click action if provided\n if (onClickAction) {\n onClickAction();\n }\n\n // If we should disable the Shopify add action, return early\n if (disableShopifyAddAction) {\n return;\n }\n\n // Otherwise, proceed with adding to cart\n linesAdd(linesToAdd);\n\n // Call the callback after successful add\n if (addToCartCallback) {\n addToCartCallback();\n }\n };\n\n return (\n <button className={styles['rebuy-cart-button']} disabled={disabled} onClick={handleAddToCart} type=\"button\">\n {addToCartBtnText}\n {moneyData && (\n <>\n {/* Consider a BEM element class if this needs specific styling */}\n {/* e.g., styles['rebuy-add-to-cart-btn__separator'] */}\n <span> | </span>\n {/* Consider a BEM element class if this needs specific styling */}\n {/* e.g., styles['rebuy-add-to-cart-btn__price'] */}\n <Money data={moneyData} withoutTrailingZeros />\n </>\n )}\n </button>\n );\n};\n", "import type { AddToCartBtnProps } from '~/components/AddToCartBtn/types';\nimport { HydrogenAddToCartBtn } from './HydrogenAddToCartBtn';\nimport { HydrogenReactAddToCartBtn } from './HydrogenReactAddToCartBtn';\n\nexport const AddToCartBtn = ({\n addToCartBtnText,\n addToCartCallback,\n disableShopifyAddAction,\n disabled,\n isHydrogenReact,\n moneyData,\n onClickAction,\n quantity,\n selectedVariants,\n}: AddToCartBtnProps) => {\n const linesToAdd = selectedVariants.map((variant) => ({\n attributes: [\n { key: '_source', value: 'Rebuy' },\n { key: '_attribution', value: 'Rebuy Product Recommendations' },\n ],\n merchandiseId: variant.id,\n quantity: quantity || 1,\n selectedVariant: variant,\n }));\n\n if (isHydrogenReact) {\n return (\n <HydrogenReactAddToCartBtn\n addToCartBtnText={addToCartBtnText}\n addToCartCallback={addToCartCallback}\n disabled={disabled}\n disableShopifyAddAction={disableShopifyAddAction}\n linesToAdd={linesToAdd}\n moneyData={moneyData}\n onClickAction={onClickAction}\n />\n );\n }\n\n return (\n <HydrogenAddToCartBtn\n addToCartBtnText={addToCartBtnText}\n addToCartCallback={addToCartCallback}\n disabled={disabled}\n disableShopifyAddAction={disableShopifyAddAction}\n linesToAdd={linesToAdd}\n moneyData={moneyData}\n onClickAction={onClickAction}\n />\n );\n};\n", "import { Money } from '@shopify/hydrogen';\nimport type { MoneyV2 } from '@shopify/hydrogen-react/storefront-api-types';\nimport clsx from 'clsx';\nimport type { ProductPriceProps } from './types';\n\nimport styles from './ProductPrice.module.css';\n\n// TODO: Add support for settingsDiscount\nexport const RebuyProductPrice = ({ selectedVariant, settingsDiscount }: ProductPriceProps) => {\n if (!selectedVariant) return null;\n const { compareAtPriceV2: compareAtPrice, priceV2: price } = selectedVariant;\n\n const isDiscounted = (price: MoneyV2 | null, compareAtPrice: MoneyV2 | null) =>\n Number(compareAtPrice?.amount) > Number(price?.amount);\n\n const currentPriceIsOnSale = compareAtPrice && isDiscounted(price, compareAtPrice);\n\n const CompareAtPrice = ({ data: compareAtPriceData }: { data: MoneyV2 | null }) => {\n return (\n compareAtPriceData && (\n <Money\n as=\"span\"\n className={styles['rebuy-product-price__compare-at']}\n data={compareAtPriceData}\n withoutTrailingZeros\n />\n )\n );\n };\n\n return (\n price && (\n <div className={styles['rebuy-product-price']}>\n <Money\n as=\"span\"\n className={clsx(\n styles['rebuy-product-price__current'],\n currentPriceIsOnSale && styles['rebuy-product-price__current--sale']\n )}\n data={price}\n withoutTrailingZeros\n />\n {currentPriceIsOnSale && <CompareAtPrice data={compareAtPrice} />}\n </div>\n )\n );\n};\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/components/ProductPrice/ProductPrice.css\";\n const result = {\"rebuy-product-price\":\"ProductPrice_rebuy-product-price\",\"rebuy-product-price__current\":\"ProductPrice_rebuy-product-price__current\",\"rebuy-product-price__current--sale\":\"ProductPrice_rebuy-product-price__current--sale\",\"rebuy-product-price__compare-at\":\"ProductPrice_rebuy-product-price__compare-at\"};\n export default result;\n ", "import { useState } from 'react';\nimport type { QuantityInputProps } from '~/components/QuantityInput/types';\nimport styles from './QuantityInput.module.css';\n\nexport const QuantityInput = ({\n defaultQuantity = 1,\n handleSelectedQuantity,\n maxValue = 10,\n minValue = 1,\n}: QuantityInputProps) => {\n const [quantity, setQuantity] = useState<number>(defaultQuantity);\n\n const handleChange = (event: React.ChangeEvent<HTMLSelectElement>) => {\n const newValue = parseInt(event.target.value, 10);\n setQuantity(newValue);\n\n // Call the callback with new value\n if (handleSelectedQuantity) {\n handleSelectedQuantity(newValue);\n }\n };\n\n // Generate array of quantity options from minValue to maxValue\n const quantityOptions = Array.from({ length: maxValue - minValue + 1 }, (_, i) => minValue + i);\n\n return (\n <div className={styles['rebuy-quantity__container']}>\n <select\n aria-label=\"Product quantity\"\n className={styles['rebuy-quantity__select']}\n name=\"quantity\"\n onChange={handleChange}\n value={quantity}\n >\n {quantityOptions.map((value) => (\n <option key={`quantity-${value}`} value={value}>\n {value}\n </option>\n ))}\n </select>\n </div>\n );\n};\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/components/QuantityInput/QuantityInput.css\";\n const result = {\"rebuy-quantity__container\":\"QuantityInput_rebuy-quantity__container\",\"rebuy-quantity__select\":\"QuantityInput_rebuy-quantity__select\"};\n export default result;\n ", "import clsx from 'clsx';\nimport { useEffect, useState } from 'react';\nimport type { VariantSelectProps } from '~/components/VariantSelect/types';\nimport styles from './VariantSelect.module.css';\n\nexport const VariantSelect = ({ handleSelectedVariant, product, selectedId, style = 'select' }: VariantSelectProps) => {\n const [selectedVariantId, setSelectedVariantId] = useState(selectedId || product.variants.nodes[0]?.id);\n\n useEffect(() => {\n if (selectedId && selectedId !== selectedVariantId) {\n setSelectedVariantId(selectedId);\n }\n }, [selectedId, selectedVariantId]);\n\n const handleLocalVariantChange = (variantId: string) => {\n setSelectedVariantId(variantId);\n handleSelectedVariant(product, variantId);\n };\n\n if (!product?.variants?.nodes || product.variants.nodes.length <= 1) {\n return null;\n }\n\n return (\n <div className={styles['rebuy-variant__container']}>\n {style === 'select' ? (\n <select\n aria-label=\"Select variant\"\n className={styles['rebuy-variant__select']}\n onChange={(e) => handleLocalVariantChange(e.target.value)}\n value={selectedVariantId}\n >\n {product.variants.nodes.map(({ id, title }) => (\n <option\n className={styles['rebuy-variant__select-option']}\n key={`${id}-variant-option`}\n value={id}\n >\n {title}\n </option>\n ))}\n </select>\n ) : (\n <div className={styles['rebuy-variant__buttons']}>\n {product.variants.nodes.map(({ id, title }) => (\n <button\n aria-pressed={id === selectedVariantId}\n className={clsx(\n styles['rebuy-variant__button'],\n id === selectedVariantId && styles['rebuy-variant__button--selected']\n )}\n key={`${id}-variant-button`}\n onClick={() => handleLocalVariantChange(id)}\n type=\"button\"\n >\n {title}\n </button>\n ))}\n </div>\n )}\n </div>\n );\n};\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/components/VariantSelect/VariantSelect.css\";\n const result = {\"rebuy-variant__container\":\"VariantSelect_rebuy-variant__container\",\"rebuy-variant__select\":\"VariantSelect_rebuy-variant__select\",\"rebuy-variant__select-option\":\"VariantSelect_rebuy-variant__select-option\",\"rebuy-variant__buttons\":\"VariantSelect_rebuy-variant__buttons\",\"rebuy-variant__button\":\"VariantSelect_rebuy-variant__button\",\"rebuy-variant__button--selected\":\"VariantSelect_rebuy-variant__button--selected\"};\n export default result;\n ", "import clsx from 'clsx';\nimport type { TitleProps } from '~/components/Title/types';\nimport styles from './Title.module.css';\n\nexport const Title = ({ className, level, style, text }: TitleProps) => {\n const combinedClassName = clsx(styles['rebuy-title'], className);\n\n switch (level) {\n case 'h1':\n return (\n <h1 className={combinedClassName} style={style}>\n {text}\n </h1>\n );\n default:\n case 'h2':\n return (\n <h2 className={combinedClassName} style={style}>\n {text}\n </h2>\n );\n case 'h3':\n return (\n <h3 className={combinedClassName} style={style}>\n {text}\n </h3>\n );\n case 'h4':\n return (\n <h4 className={combinedClassName} style={style}>\n {text}\n </h4>\n );\n case 'h5':\n return (\n <h5 className={combinedClassName} style={style}>\n {text}\n </h5>\n );\n case 'h6':\n return (\n <h6 className={combinedClassName} style={style}>\n {text}\n </h6>\n );\n }\n};\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/components/Title/Title.css\";\n const result = {\"rebuy-title\":\"Title_rebuy-title\"};\n export default result;\n ", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/components/ProductCard/ProductCard.css\";\n const result = {\"rebuy-product-card__container\":\"ProductCard_rebuy-product-card__container\",\"rebuy-product-card\":\"ProductCard_rebuy-product-card\",\"rebuy-product-card__content\":\"ProductCard_rebuy-product-card__content\",\"rebuy-product-card__header\":\"ProductCard_rebuy-product-card__header\",\"rebuy-product-card__info\":\"ProductCard_rebuy-product-card__info\",\"rebuy-product-card__actions\":\"ProductCard_rebuy-product-card__actions\",\"rebuy-product-card__media-link\":\"ProductCard_rebuy-product-card__media-link\",\"rebuy-product-card__image\":\"ProductCard_rebuy-product-card__image\",\"rebuy-product-card__title\":\"ProductCard_rebuy-product-card__title\",\"rebuy-product-card__title-link\":\"ProductCard_rebuy-product-card__title-link\",\"rebuy-product-card__actions-variant-select\":\"ProductCard_rebuy-product-card__actions-variant-select\",\"rebuy-product-card__variant-select\":\"ProductCard_rebuy-product-card__variant-select\",\"rebuy-product-card__actions-quantity\":\"ProductCard_rebuy-product-card__actions-quantity\",\"rebuy-product-card__actions-button\":\"ProductCard_rebuy-product-card__actions-button\",\"rebuy-product-card__vendor\":\"ProductCard_rebuy-product-card__vendor\",\"rebuy-product-card__variant-title\":\"ProductCard_rebuy-product-card__variant-title\",\"rebuy-product-card__review\":\"ProductCard_rebuy-product-card__review\",\"rebuy-product-card__star-rating\":\"ProductCard_rebuy-product-card__star-rating\",\"rebuy-product-card__star-rating-value\":\"ProductCard_rebuy-product-card__star-rating-value\",\"rebuy-product-card__star-rating-background\":\"ProductCard_rebuy-product-card__star-rating-background\",\"rebuy-product-card__star-rating-foreground\":\"ProductCard_rebuy-product-card__star-rating-foreground\",\"rebuy-product-card__review-count\":\"ProductCard_rebuy-product-card__review-count\",\"rebuy-product-card__review-count-parenthesis\":\"ProductCard_rebuy-product-card__review-count-parenthesis\",\"rebuy-product-card__review-count-number\":\"ProductCard_rebuy-product-card__review-count-number\",\"rebuy-product-card__review-count-label\":\"ProductCard_rebuy-product-card__review-count-label\",\"rebuy-product-card__description\":\"ProductCard_rebuy-product-card__description\"};\n export default result;\n ", "import { useEffect, useState } from 'react';\nimport { ProductCard } from '~/components/ProductCard';\nimport type { RebuyProduct } from '~/types/rebuyCustom';\nimport type { ProductCarouselProps } from './types';\nimport styles from './ProductCarousel.module.css';\n\nexport const ProductCarousel = ({\n addToCartBtnText,\n addToCartCallback,\n columns,\n isCrossSell,\n isHydrogenReact,\n isInPopup,\n onPopupDismiss,\n productCardTitleLevel,\n products,\n settings,\n showPagination = true,\n variantOptionsText,\n}: ProductCarouselProps) => {\n const [currentSlide, setCurrentSlide] = useState(0);\n const [totalSlides, setTotalSlides] = useState(0);\n const [repeatedProducts, setRepeatedProducts] = useState<RebuyProduct[]>([]);\n\n // Create an array of repeated products to ensure all slides are fully populated\n useEffect(() => {\n if (products.length === 0) {\n setRepeatedProducts([]);\n\n return;\n }\n\n const productsNeeded = Math.ceil(products.length / columns) * columns;\n let repeated: RebuyProduct[] = [...products];\n\n while (repeated.length < productsNeeded) {\n const remaining = productsNeeded - repeated.length;\n repeated = [...repeated, ...products.slice(0, remaining)];\n }\n\n setRepeatedProducts(repeated);\n }, [products, columns]);\n\n // Calculate total number of slides based on repeated products and columns\n useEffect(() => {\n if (repeatedProducts.length && columns) {\n setTotalSlides(Math.ceil(repeatedProducts.length / columns));\n }\n }, [repeatedProducts.length, columns]);\n\n const nextSlide = () => {\n setCurrentSlide((prev) => (prev + 1) % totalSlides);\n };\n\n const prevSlide = () => {\n setCurrentSlide((prev) => (prev - 1 + totalSlides) % totalSlides);\n };\n\n const goToSlide = (slideIndex: number) => {\n setCurrentSlide(slideIndex);\n };\n\n // Group products into slides based on column count\n const slides = [];\n for (let i = 0; i < repeatedProducts.length; i += columns) {\n slides.push(repeatedProducts.slice(i, i + columns));\n }\n\n return (\n <div className={styles['rebuy-carousel']}>\n <div\n className={styles['rebuy-carousel__container']}\n style={{ transform: `translateX(-${currentSlide * 100}%)` }}\n >\n {slides.map((slideProducts, index) => (\n <div className={styles['rebuy-carousel__slide']} key={index}>\n <div className={styles['rebuy-carousel__grid']} data-columns={columns}>\n {slideProducts.map((product, productIndex) => (\n <ProductCard\n addToCartBtnText={addToCartBtnText}\n addToCartCallback={addToCartCallback}\n isCrossSell={isCrossSell}\n isHydrogenReact={isHydrogenReact}\n isInPopup={isInPopup}\n key={`${product.id}-${index}-${productIndex}`}\n onPopupDismiss={onPopupDismiss}\n product={product}\n productCardTitleLevel={productCardTitleLevel}\n settings={settings}\n variantOptionsText={variantOptionsText}\n />\n ))}\n </div>\n </div>\n ))}\n </div>\n\n {totalSlides > 1 && (\n <div className={styles['rebuy-carousel__controls']}>\n <button className={styles['rebuy-carousel__prev']} onClick={prevSlide} type=\"button\">\n \u2190\n </button>\n <button className={styles['rebuy-carousel__next']} onClick={nextSlide} type=\"button\">\n \u2192\n </button>\n </div>\n )}\n\n {showPagination && totalSlides > 1 && (\n <div className={styles['rebuy-carousel__pagination']}>\n {Array.from({ length: totalSlides }).map((_, index) => (\n <button\n className={styles['rebuy-carousel__dot']}\n data-active={index === currentSlide ? 'true' : 'false'}\n key={index}\n onClick={() => goToSlide(index)}\n type=\"button\"\n />\n ))}\n </div>\n )}\n </div>\n );\n};\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/components/ProductCarousel/ProductCarousel.css\";\n const result = {\"rebuy-carousel\":\"ProductCarousel_rebuy-carousel\",\"rebuy-carousel__container\":\"ProductCarousel_rebuy-carousel__container\",\"rebuy-carousel__slide\":\"ProductCarousel_rebuy-carousel__slide\",\"rebuy-carousel__controls\":\"ProductCarousel_rebuy-carousel__controls\",\"rebuy-carousel__prev\":\"ProductCarousel_rebuy-carousel__prev\",\"rebuy-carousel__next\":\"ProductCarousel_rebuy-carousel__next\",\"rebuy-carousel__pagination\":\"ProductCarousel_rebuy-carousel__pagination\",\"rebuy-carousel__dot\":\"ProductCarousel_rebuy-carousel__dot\",\"rebuy-carousel__grid\":\"ProductCarousel_rebuy-carousel__grid\"};\n export default result;\n ", "import clsx from 'clsx';\nimport { useCallback, useEffect, useState } from 'react';\nimport type { TimerProps } from './types';\n\nimport styles from './Timer.module.css';\n\nexport const Timer = ({ action, durationMinutes, durationSeconds, isPopup = false, onDismiss, title }: TimerProps) => {\n // Calculate total seconds from minutes and seconds\n const initialTotalSeconds = (durationMinutes || 0) * 60 + (durationSeconds || 0);\n const [totalSeconds, setTotalSeconds] = useState(initialTotalSeconds);\n const [timerActive, setTimerActive] = useState(true);\n\n // Format remaining time into minutes and seconds\n const minutes = Math.floor(totalSeconds / 60);\n const seconds = totalSeconds % 60;\n\n const formattedMinutes = String(minutes).padStart(2, '0');\n const formattedSeconds = String(seconds).padStart(2, '0');\n\n // Handle the action when the timer ends\n const handleTimerEnd = useCallback(() => {\n setTimerActive(false);\n\n switch (action) {\n case 'dismiss':\n if (isPopup && onDismiss) {\n onDismiss();\n }\n break;\n case 'checkout':\n window.location.href = '/checkout';\n break;\n case 'cart':\n window.location.href = '/cart';\n break;\n case 'stop':\n default:\n // Just stop the timer, which we've already done\n break;\n }\n }, [action, isPopup, onDismiss]);\n\n useEffect(() => {\n // Only proceed if the timer is active\n if (!timerActive) return;\n\n // Create interval to count down\n const interval = setInterval(() => {\n setTotalSeconds((prevSeconds: number) => {\n // If we're at zero, clear the interval and handle the timer action\n if (prevSeconds <= 0) {\n clearInterval(interval);\n handleTimerEnd();\n\n return 0;\n }\n\n return prevSeconds - 1;\n });\n }, 1000);\n\n // Clean up the interval\n return () => clearInterval(interval);\n }, [timerActive, handleTimerEnd]);\n\n const isUrgent = totalSeconds < 10;\n\n return (\n <div className={styles['rebuy-timer__container']}>\n <p className={styles['rebuy-timer__text']}>\n <span className={styles['rebuy-timer__title']}>{title}</span>\n <span\n className={clsx(styles['rebuy-timer__display'], isUrgent && styles['rebuy-timer__display--urgent'])}\n >\n <span className={styles['rebuy-timer__minutes']}>{formattedMinutes}</span>\n <span className={styles['rebuy-timer__separator']}>:</span>\n <span className={styles['rebuy-timer__seconds']}>{formattedSeconds}</span>\n </span>\n </p>\n </div>\n );\n};\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/components/Timer/Timer.css\";\n const result = {\"rebuy-timer__container\":\"Timer_rebuy-timer__container\",\"rebuy-timer__text\":\"Timer_rebuy-timer__text\",\"rebuy-timer__title\":\"Timer_rebuy-timer__title\",\"rebuy-timer__display\":\"Timer_rebuy-timer__display\",\"rebuy-timer__display--urgent\":\"Timer_rebuy-timer__display--urgent\",\"rebuy-timer__minutes\":\"Timer_rebuy-timer__minutes\",\"rebuy-timer__seconds\":\"Timer_rebuy-timer__seconds\",\"rebuy-timer__separator\":\"Timer_rebuy-timer__separator\"};\n export default result;\n ", "import { ProductCardTitleLevel } from '~/types/common';\n\n// Convert the string header level to enum\nexport const getTitleLevel = (level: string, decreaseLevel: boolean = false): ProductCardTitleLevel => {\n switch (level) {\n case 'h1':\n if (decreaseLevel) {\n return ProductCardTitleLevel.H2;\n }\n\n return ProductCardTitleLevel.H1;\n case 'h2':\n if (decreaseLevel) {\n return ProductCardTitleLevel.H3;\n }\n\n return ProductCardTitleLevel.H2;\n case 'h3':\n if (decreaseLevel) {\n return ProductCardTitleLevel.H4;\n }\n\n return ProductCardTitleLevel.H3;\n case 'h4':\n if (decreaseLevel) {\n return ProductCardTitleLevel.H5;\n }\n\n return ProductCardTitleLevel.H4;\n case 'h5':\n if (decreaseLevel) {\n return ProductCardTitleLevel.H6;\n }\n\n return ProductCardTitleLevel.H5;\n case 'h6':\n if (decreaseLevel) {\n return ProductCardTitleLevel.H6;\n }\n\n return ProductCardTitleLevel.H6;\n default:\n return ProductCardTitleLevel.H2;\n }\n};\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/widgets/RebuyWidget/RebuyWidget.css\";\n const result = {\"rebuy-widget__container\":\"RebuyWidget_rebuy-widget__container\",\"rebuy-widget__popup-overlay\":\"RebuyWidget_rebuy-widget__popup-overlay\",\"rebuy-widget__popup-content\":\"RebuyWidget_rebuy-widget__popup-content\",\"rebuy-widget__content\":\"RebuyWidget_rebuy-widget__content\",\"rebuy-widget__inner-content\":\"RebuyWidget_rebuy-widget__inner-content\",\"rebuy-widget__description\":\"RebuyWidget_rebuy-widget__description\",\"rebuy-widget__modal-close\":\"RebuyWidget_rebuy-widget__modal-close\",\"rebuy-widget__product-grid\":\"RebuyWidget_rebuy-widget__product-grid\"};\n export default result;\n ", "import { ProductCard } from '~/components/ProductCard';\nimport type { ProductCardSettings } from '~/components/ProductCard/types';\nimport { ProductCarousel } from '~/components/ProductCarousel';\nimport { Timer } from '~/components/Timer';\nimport { Title } from '~/components/Title';\nimport { getTitleLevel } from '~/hooks/titleLevel';\nimport { useBreakpoint } from '~/hooks/useBreakpoint';\nimport type { RebuyProduct } from '~/types/rebuyCustom';\nimport type { WidgetContentProps } from '~/widgets/RebuyWidget/types';\nimport styles from './RebuyWidget.module.css';\n\nexport const WidgetContent = ({\n addToCartCallback,\n customTitle,\n customTitleLevel,\n customTitleStyle,\n isCrossSell,\n isHydrogenReact,\n isInPopup,\n onDismiss,\n products,\n settings,\n}: WidgetContentProps) => {\n const currentBreakpoint = useBreakpoint(settings);\n const hasTimer =\n settings &&\n settings.timer.enabled &&\n settings.language.timer_title !== '' &&\n (settings.timer.duration_minutes !== null || settings.timer.duration_seconds !== null);\n const hasSuperTitle = settings?.language.super_title !== '';\n\n // Use customTitle if provided, otherwise use settings title\n const primaryTitle = customTitle || settings?.language.title || '';\n const hasPrimaryTitle = primaryTitle !== '';\n\n const hasDescription = settings?.language.description !== '';\n\n // Get layout settings based on current breakpoint\n const layoutSettings = settings?.layout?.[currentBreakpoint];\n const isCarousel = layoutSettings?.carousel || false;\n const columns = layoutSettings?.columns || 1;\n const showPagination = layoutSettings?.show_paginations || false;\n\n const productCardSettings: ProductCardSettings = {\n layoutStyle: layoutSettings?.style,\n productOptions: settings?.product_options\n ? {\n ...settings.product_options,\n // Ensure match_variant_out_of_stock is always provided since ProductCardSettings requires it\n match_variant_out_of_stock: settings.product_options.match_variant_out_of_stock ?? false,\n }\n : undefined,\n quantityInput: settings?.quantity_inputs,\n settingsDiscount: settings?.discount\n ? {\n amount:\n typeof settings.discount.amount === 'number'\n ? settings.discount.amount\n : parseFloat(settings.discount.amount) || 0,\n bundle_protection: settings.discount.bundle_protection || {\n allowed_removals: 0,\n disable_atc_on_incomplete: false,\n enabled: false,\n },\n discount_protection: settings.discount.discount_protection || {\n enabled: false,\n minimum_items_to_get_discount: 0,\n },\n discounted_by: settings.discount.discounted_by || settings.discount.discountedBy || '',\n discounted_from: settings.discount.discounted_from || settings.discount.discountedFrom || '',\n message: settings.discount.message || '',\n quantity: settings.discount.quantity || 0,\n show_saving_amount:\n settings.discount.show_saving_amount || settings.discount.showSavingAmount || false,\n type: settings.discount.type,\n }\n : undefined,\n variantSelector: settings?.view_options.variant_selector,\n };\n\n // Determine the correct title level for product cards\n const productCardTitleLevel = hasSuperTitle\n ? getTitleLevel(getTitleLevel(customTitleLevel, true), true)\n : getTitleLevel(customTitleLevel, true);\n\n // Render product listing based on layout style and carousel settings\n const renderProducts = () => {\n if (!products || products.length === 0) {\n return null;\n }\n\n if (isCarousel) {\n return (\n <ProductCarousel\n addToCartBtnText={settings?.language.add_to_cart}\n addToCartCallback={addToCartCallback}\n columns={columns}\n isCrossSell={isCrossSell}\n isHydrogenReact={isHydrogenReact}\n isInPopup={isInPopup}\n onPopupDismiss={onDismiss}\n productCardTitleLevel={productCardTitleLevel}\n products={products}\n settings={productCardSettings}\n showPagination={showPagination}\n variantOptionsText={settings?.language.variant_options}\n />\n );\n }\n\n return (\n <div className={styles['rebuy-widget__product-grid']} data-columns={columns} role=\"list\" tabIndex={0}>\n {products.map((product: RebuyProduct) => (\n <div key={product.id}>\n <ProductCard\n addToCartBtnText={settings?.language.add_to_cart}\n addToCartCallback={addToCartCallback}\n isCrossSell={isCrossSell}\n isHydrogenReact={isHydrogenReact}\n isInPopup={isInPopup}\n onPopupDismiss={onDismiss}\n product={product}\n productCardTitleLevel={productCardTitleLevel}\n settings={productCardSettings}\n variantOptionsText={settings?.language.variant_options}\n />\n </div>\n ))}\n </div>\n );\n };\n\n return (\n <div className={styles['rebuy-widget__inner-content']}>\n {hasTimer && (\n <Timer\n action={settings?.timer.action}\n durationMinutes={settings?.timer.duration_minutes}\n durationSeconds={settings?.timer.duration_seconds}\n isPopup={settings?.display_type === 'popup'}\n onDismiss={onDismiss}\n title={settings?.language.timer_title}\n />\n )}\n {hasSuperTitle && (\n <Title\n level={getTitleLevel(customTitleLevel)}\n style={{ marginBottom: '0', textAlign: 'center' }}\n text={settings.language.super_title}\n />\n )}\n {hasPrimaryTitle && (\n <Title\n level={getTitleLevel(customTitleLevel, hasSuperTitle ? true : false)}\n style={customTitleStyle || { textAlign: 'center' }}\n text={primaryTitle}\n />\n )}\n {hasDescription && <p className={styles['rebuy-widget__description']}>{settings.language.description}</p>}\n\n {renderProducts()}\n </div>\n );\n};\n", "import type { SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\nimport { RebuyWidget } from '~/widgets/RebuyWidget';\nimport './CrossSell.css';\n\ntype CrossSellProps = {\n componentConfig: Extract<SmartCartComponentConfig, { type: 'cross_sell_widget' }>;\n};\n\nexport const CrossSell = ({ componentConfig }: CrossSellProps) => {\n const widgetId = componentConfig.settings.widget_id;\n\n if (!widgetId) {\n console.warn('[CrossSell] Widget ID is missing from component configuration');\n\n return null;\n }\n\n return (\n <div data-rebuy-component=\"cross-sell-widget\" data-rebuy-component-id={widgetId}>\n <RebuyWidget isCrossSell widgetId={widgetId} />\n </div>\n );\n};\n", "// src/onsite/js/modules/SmartCartReact/components/CustomCode/CustomCodeBlock.tsx\nimport React, { useEffect, useMemo, useRef } from 'react';\nimport { DebugKey } from '~/constants/debug';\n\nimport type { SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\nimport { executeScriptsInContainer } from '~/smart-cart/utils/executeScriptsInContainer';\n\n/* eslint-disable-next-line no-restricted-imports */\n\ntype CustomCodeBlockProps = {\n /** The specific configuration object for this Custom Code Block instance. */\n componentConfig: Extract<SmartCartComponentConfig, { type: 'custom_code_block' }>;\n};\n\n/**\n * Renders arbitrary HTML and executes *all* associated <script> tags provided\n * in the component's configuration. Mirrors the legacy CustomCode feature but\n * supports multiple scripts within one block.\n *\n * ! WARNING: This component uses `dangerouslySetInnerHTML` and a script execution\n * ! helper to run user-provided code. This approach avoids `eval()` to comply with\n * ! Content Security Policies (CSP) but still carries risks (e.g., XSS).\n * ! Use with extreme caution and ensure the provided HTML/JS is trusted.\n */\nexport const CustomCodeBlock = React.memo(({ componentConfig }: CustomCodeBlockProps) => {\n const containerRef = useRef<HTMLDivElement>(null);\n const executedCodeRef = useRef<string | null>(null);\n\n const componentId = componentConfig.component_id;\n const htmlCode = useMemo(() => componentConfig.settings?.html_code ?? null, [componentConfig.settings?.html_code]);\n\n useEffect(() => {\n const container = containerRef.current;\n\n if (htmlCode && container && executedCodeRef.current !== htmlCode) {\n // Use setTimeout to defer execution until after the current render cycle.\n // This gives the browser time to ensure all DOM elements, including the\n // body tag with the nonce, are available to be queried.\n const timerId = setTimeout(() => {\n executeScriptsInContainer(\n container,\n DebugKey.SC_CUSTOM_CODE_BLOCK,\n `Custom Code Block (ID: ${componentId})`\n );\n // Mark the code as executed (fixed React Strict Mode issues)\n executedCodeRef.current = htmlCode;\n }, 0);\n\n // Cleanup the timer if the component unmounts before it fires.\n return () => {\n clearTimeout(timerId);\n };\n } else if (!htmlCode) {\n executedCodeRef.current = null;\n }\n }, [htmlCode, componentId]);\n\n // Render null if no htmlCode is configured.\n if (!htmlCode) {\n return null;\n }\n\n return (\n <div\n dangerouslySetInnerHTML={{ __html: htmlCode }}\n data-rebuy-component=\"custom_code_block\"\n data-rebuy-component-id={componentId}\n data-rebuy-custom-code={componentId} // Legacy-specific attribute\n ref={containerRef}\n />\n );\n});\n\nCustomCodeBlock.displayName = 'CustomCodeBlock';\n", "let cachedNonce: string | null | undefined = undefined;\n\n/**\n * Retrieves the CSP nonce from the DOM.\n * It reads the nonce from the `data-csp-nonce` attribute on the <body> tag,\n * then caches it for all subsequent calls during the page's lifetime.\n * This is the most robust method for client-side access.\n *\n * @returns {string | null} The found nonce, or null if none exists.\n */\nexport const getNonce = (): string | null => {\n if (cachedNonce !== undefined) {\n return cachedNonce;\n }\n\n // Query the body tag for our specific data attribute.\n const bodyElement = document.querySelector('body[data-nonce]');\n cachedNonce = bodyElement ? bodyElement.getAttribute('data-nonce') : null;\n\n return cachedNonce;\n};\n", "import type { DebugKey } from '~/constants/debug';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport { getNonce } from '~/utils/nonceManager';\n\n/**\n * Finds all <script> elements within a given container, creates new executable\n * script elements from them, and appends them to the container to trigger execution.\n * This method avoids `eval()` and is designed to work with Content Security Policies\n * that use nonces by attempting to copy a nonce from an existing script on the page.\n *\n * @param {HTMLElement} container The HTML element to search within.\n * @param {DebugKey} debugKey The debug key for logging.\n * @param {string} debugContext A string providing context for log messages (e.g., component ID).\n * @returns {void}\n */\nexport const executeScriptsInContainer = (container: HTMLElement, debugKey: DebugKey, debugContext: string) => {\n rebuyDebugLog.log(debugKey, `[executeScripts] Called for: ${debugContext}`);\n\n // Get the nonce from our reliable, cached source.\n const nonce = getNonce();\n\n rebuyDebugLog.log(debugKey, `[executeScripts] Nonce discovery result:`, {\n hasNonce: !!nonce,\n nonce: nonce ? `${nonce.substring(0, 10)}...` : 'null',\n scriptElementsWithNonce: document.querySelectorAll('script[nonce]').length,\n });\n\n if (nonce) {\n rebuyDebugLog.log(debugKey, `[executeScripts] Using CSP nonce: ${nonce.substring(0, 10)}...`);\n } else {\n rebuyDebugLog.warn(\n debugKey,\n `[executeScripts] Could not find a CSP nonce. Dynamic scripts will likely be blocked by CSP.`\n );\n console.warn(`[Rebuy] Could not find a CSP nonce. Dynamic scripts will likely be blocked by CSP.`);\n }\n\n const scriptElements = container.querySelectorAll('script');\n\n rebuyDebugLog.log(debugKey, `[executeScripts] Script elements found:`, {\n containerHtml: container.innerHTML.substring(0, 200) + '...',\n count: scriptElements.length,\n scriptContents: Array.from(scriptElements).map((el) => ({\n attributes: Array.from(el.attributes)\n .map((attr) => `${attr.name}=\"${attr.value}\"`)\n .join(' '),\n innerHTML: el.innerHTML.substring(0, 100) + '...',\n })),\n });\n\n if (scriptElements.length > 0) {\n rebuyDebugLog.log(debugKey, `Found ${scriptElements.length} script(s) in ${debugContext}. Executing...`);\n\n scriptElements.forEach((scriptElement, index) => {\n rebuyDebugLog.log(debugKey, `[executeScripts] Processing script ${index + 1}/${scriptElements.length}:`, {\n attributes: Array.from(scriptElement.attributes)\n .map((attr) => `${attr.name}=\"${attr.value}\"`)\n .join(' '),\n hasParent: !!scriptElement.parentNode,\n innerHTML: scriptElement.innerHTML.substring(0, 100) + '...',\n });\n\n const newScript = document.createElement('script');\n newScript.innerHTML = scriptElement.innerHTML;\n\n for (const attr of Array.from(scriptElement.attributes)) {\n newScript.setAttribute(attr.name, attr.value);\n }\n\n if (nonce) {\n newScript.setAttribute('nonce', nonce);\n }\n\n try {\n scriptElement.parentNode?.replaceChild(newScript, scriptElement);\n rebuyDebugLog.log(debugKey, `[executeScripts] Successfully replaced script ${index + 1}`);\n } catch (error) {\n console.error(`[Rebuy] Failed to replace script ${index + 1}:`, error);\n }\n });\n\n rebuyDebugLog.log(\n debugKey,\n `[executeScripts] Finished processing all ${scriptElements.length} scripts in ${debugContext}`\n );\n } else {\n rebuyDebugLog.log(debugKey, `[executeScripts] No script elements found in ${debugContext}`);\n }\n};\n", "// ~/smart-cart/components/DiscountCodeInput/DiscountCodeInput.tsx\nimport type { CartUserError, Cart as StorefrontCart } from '@shopify/hydrogen/storefront-api-types';\nimport clsx from 'clsx';\nimport React, { useCallback, useEffect, useMemo, useRef, useState, type FormEvent } from 'react';\nimport { useFetcher } from 'react-router';\n\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport { useDiscountManager } from '~/smart-cart/hooks/useDiscountManager';\nimport { formatMoney } from '~/smart-cart/utils/moneyUtils';\nimport type { JsonValue } from '~/types/common';\n\n/* eslint-disable-next-line no-restricted-imports */\nimport styles from './DiscountCodeInput.module.css';\n\ntype DiscountCodeInputProps = { componentConfig: { component_id: string } };\n\nexport const DiscountCodeInputComponent = ({ componentConfig }: DiscountCodeInputProps) => {\n const {\n applyDiscountCodes: hrApplyDiscountCodes,\n cartData,\n getItemCount,\n isHydrogenReact,\n isLoading: isGlobalCartLoading,\n } = useSmartCart();\n\n const discountFetcher = useFetcher<{\n cart?: StorefrontCart | null;\n errors?: CartUserError[];\n warnings?: any[]; // eslint-disable-line @typescript-eslint/no-explicit-any\n }>();\n\n const {\n appliedCodes,\n error: discountManagerError,\n prepareApplyCode,\n prepareRemoveCode,\n processActionResult,\n setCurrentError: setDiscountManagerError,\n setIsProcessing: setDiscountManagerIsProcessing,\n settings,\n } = useDiscountManager();\n\n const [inputValue, setInputValue] = useState('');\n const [isInputFocused, setIsInputFocused] = useState(false);\n const [isLocallyProcessing, setIsLocallyProcessing] = useState(false);\n const inputRef = useRef<HTMLInputElement>(null);\n const hasItems = getItemCount() > 0;\n\n const lang = useMemo(\n () => ({\n // applyingLabel: settings?.language?.discount_applying_label ?? 'Applying...',\n buttonLabel: settings?.language?.discount_button_label ?? 'Apply',\n inputLabel: settings?.language?.discount_code_label ?? 'Discount Code',\n }),\n [settings]\n );\n\n const isLoadingCombined = useMemo(() => {\n if (isHydrogenReact) return isGlobalCartLoading || isLocallyProcessing;\n\n return discountFetcher.state !== 'idle' || isLocallyProcessing;\n }, [isHydrogenReact, isGlobalCartLoading, discountFetcher.state, isLocallyProcessing]);\n\n const shouldShowTags = appliedCodes.length > 0;\n const discountTotalAmount = useMemo(() => {\n if (!cartData || !shouldShowTags || !Array.isArray(cartData.discountAllocations)) {\n return 0;\n }\n\n return cartData.discountAllocations\n .filter((alloc) => alloc.__typename === 'CartCodeDiscountAllocation') // Filter out non-code allocations\n .reduce((sum, alloc) => sum + parseFloat(alloc.discountedAmount.amount), 0);\n }, [cartData, shouldShowTags]);\n\n const _formattedDiscountTotal = useMemo(() => {\n if (discountTotalAmount <= 0) return '';\n\n const currencyCode = cartData?.cost?.totalAmount?.currencyCode ?? 'USD';\n\n return `- ${formatMoney(discountTotalAmount, undefined, currencyCode)}`;\n }, [discountTotalAmount, cartData, appliedCodes]);\n\n const handleApply = useCallback(\n (event: FormEvent) => {\n event.preventDefault();\n\n if (!inputValue.trim() || isLoadingCombined) return;\n\n const payloadFromManager = prepareApplyCode(inputValue); // This returns { codes: string[] }\n\n if (!payloadFromManager) return;\n\n setIsLocallyProcessing(true);\n setDiscountManagerIsProcessing(true);\n setDiscountManagerError(null);\n\n if (isHydrogenReact) {\n hrApplyDiscountCodes(payloadFromManager.codes);\n } else {\n discountFetcher.submit(\n {\n action: 'discountCodesUpdate',\n data: { discountCodes: payloadFromManager.codes }, // Key changed from 'codes' to 'discountCodes'\n } as JsonValue,\n {\n action: '/cart',\n encType: 'application/json',\n method: 'POST',\n }\n );\n }\n },\n [\n inputValue,\n isLoadingCombined,\n prepareApplyCode,\n isHydrogenReact,\n hrApplyDiscountCodes,\n discountFetcher,\n setDiscountManagerIsProcessing,\n setDiscountManagerError,\n ]\n );\n\n const handleRemove = useCallback(\n (code: string) => {\n if (isLoadingCombined) return;\n\n const payloadFromManager = prepareRemoveCode(code);\n setIsLocallyProcessing(true);\n setDiscountManagerIsProcessing(true);\n setDiscountManagerError(null);\n\n if (isHydrogenReact) {\n hrApplyDiscountCodes(payloadFromManager.codes);\n } else {\n discountFetcher.submit(\n {\n action: 'discountCodesUpdate',\n data: { discountCodes: payloadFromManager.codes },\n } as JsonValue,\n {\n action: '/cart',\n encType: 'application/json',\n method: 'POST',\n }\n );\n }\n },\n [\n isLoadingCombined,\n prepareRemoveCode,\n isHydrogenReact,\n hrApplyDiscountCodes,\n discountFetcher,\n setDiscountManagerIsProcessing,\n setDiscountManagerError,\n ]\n );\n\n // Effect to handle results and reset loading states\n useEffect(() => {\n if (isHydrogenReact) {\n if (!isGlobalCartLoading && isLocallyProcessing) {\n setIsLocallyProcessing(false);\n setDiscountManagerIsProcessing(false);\n\n if (cartData && inputValue) {\n const attemptedCode = inputValue.trim().toUpperCase();\n const found = cartData.discountCodes?.find(\n (dc) => dc.code.toUpperCase() === attemptedCode && dc.applicable\n );\n\n if (!found && cartData.discountCodes?.some((dc) => dc.code.toUpperCase() === attemptedCode)) {\n processActionResult(cartData, attemptedCode);\n } else if (\n cartData.discountCodes?.some((dc) => dc.code.toUpperCase() === attemptedCode && dc.applicable)\n ) {\n setInputValue('');\n }\n }\n }\n } else {\n if (discountFetcher.state === 'idle' && isLocallyProcessing) {\n setIsLocallyProcessing(false);\n setDiscountManagerIsProcessing(false);\n const fetcherData = discountFetcher.data;\n\n if (fetcherData?.errors?.length) {\n setDiscountManagerError(fetcherData.errors[0]?.message || 'Failed to apply discount.');\n } else if (fetcherData?.cart) {\n processActionResult(fetcherData.cart, inputValue.trim());\n\n if (!discountManagerError) {\n setInputValue('');\n }\n } else {\n if (!discountManagerError) {\n setInputValue('');\n }\n }\n }\n }\n }, [\n isHydrogenReact,\n isGlobalCartLoading,\n discountFetcher.state,\n discountFetcher.data,\n isLocallyProcessing,\n setDiscountManagerIsProcessing,\n processActionResult,\n inputValue,\n setDiscountManagerError,\n discountManagerError,\n cartData,\n ]);\n\n if (!hasItems) return null;\n\n return (\n <div\n className={styles['rebuy-discount-code-input']}\n data-rebuy-component=\"discount-input\"\n data-rebuy-component-id={componentConfig.component_id}\n >\n <form className={styles['rebuy-discount-code-input__form']} onSubmit={handleApply}>\n <div\n className={clsx(styles['rebuy-discount-code-input__input-wrapper'], {\n [styles['rebuy-discount-code-input__input-wrapper--show-label']]:\n !!inputValue || isInputFocused,\n })}\n >\n <input\n aria-label={lang.inputLabel}\n autoCapitalize=\"characters\"\n autoComplete=\"off\"\n className={styles['rebuy-discount-code-input__input-field']}\n disabled={isLoadingCombined}\n id={`rebuy-discount-input-${componentConfig.component_id}`}\n onBlur={() => setIsInputFocused(false)}\n onChange={(e) => {\n setInputValue(e.target.value);\n setDiscountManagerError(null);\n }}\n onFocus={() => setIsInputFocused(true)}\n placeholder={lang.inputLabel}\n ref={inputRef}\n type=\"text\"\n value={inputValue}\n />\n <label\n className={styles['rebuy-discount-code-input__input-label']}\n htmlFor={`rebuy-discount-input-${componentConfig.component_id}`}\n >\n {lang.inputLabel}\n </label>\n </div>\n <button\n className={styles['rebuy-discount-code-input__apply-button']}\n disabled={isLoadingCombined || !inputValue.trim()}\n type=\"submit\"\n >\n {/* {isLoadingCombined && isLocallyProcessing ? lang.applyingLabel : lang.buttonLabel} */}\n {lang.buttonLabel}\n </button>\n </form>\n\n {discountManagerError && (\n <div className={styles['rebuy-discount-code-input__error-message']}>{discountManagerError}</div>\n )}\n\n {shouldShowTags && (\n <div className={styles['rebuy-discount-code-input__tags-list']}>\n {appliedCodes.map((code) => (\n <div className={styles['rebuy-discount-code-input__tag']} key={code}>\n <span className={styles['rebuy-discount-code-input__tag-icon']}>\n <svg fill=\"currentColor\" height=\"14\" viewBox=\"0 0 24 24\" width=\"14\">\n <path d=\"M21.41 11.58l-9-9C12.05 2.22 11.55 2 11 2H4c-1.1 0-2 .9-2 2v7c0 .55.22 1.05.59 1.42l9 9c.36.36.86.58 1.41.58.55 0 1.05-.22 1.41-.59l7-7c.37-.36.59-.86.59-1.41 0-.55-.23-1.06-.59-1.42zM5.5 7C4.67 7 4 6.33 4 5.5S4.67 4 5.5 4 7 4.67 7 5.5 6.33 7 5.5 7z\" />\n </svg>\n </span>\n <span className={styles['rebuy-discount-code-input__tag-text']}>{code}</span>\n <button\n aria-label={`Remove discount code ${code}`}\n className={styles['rebuy-discount-code-input__tag-remove-button']}\n disabled={isLoadingCombined}\n onClick={() => handleRemove(code)}\n type=\"button\"\n >\n \u2715\n </button>\n </div>\n ))}\n </div>\n )}\n </div>\n );\n};\n\nexport const DiscountCodeInput = React.memo(DiscountCodeInputComponent);\nDiscountCodeInput.displayName = 'DiscountCodeInput';\n", "// ~/smart-cart/hooks/useDiscountManager.ts\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { DebugKey } from '~/constants/debug';\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\n\nexport type ApplyCodesPayload = { codes: string[] };\n\nconst GENERIC_ERROR_CODE_MESSAGE = '{{code}} is not valid for this cart.';\n\n/**\n * Manages discount code state and interactions for the Smart Cart (Storefront API ONLY).\n */\nexport const useDiscountManager = () => {\n const { cartData, error: cartErrorFromCtx, getComponentConfigByType } = useSmartCart();\n\n const [isProcessing, setIsProcessing] = useState(false); // Local processing for this hook\n const [currentError, setCurrentError] = useState<string | null>(null);\n const [appliedCodesState, setAppliedCodesState] = useState<string[]>([]);\n\n const componentConfig = useMemo(() => getComponentConfigByType('discount_code'), [getComponentConfigByType]);\n const settings = useMemo(() => componentConfig?.settings ?? null, [componentConfig]);\n\n useEffect(() => {\n const codesFromApi = cartData?.discountCodes?.filter((dc) => dc.applicable).map((dc) => dc.code) ?? [];\n\n if (JSON.stringify(codesFromApi) !== JSON.stringify(appliedCodesState)) {\n setAppliedCodesState(codesFromApi);\n\n // Don't clear currentError here if it came from a direct failed attempt,\n // only if the cartData sync shows the code is no longer an issue.\n // This needs careful handling based on how errors from H-React vs Fetcher are propagated.\n // For now, let's assume if codesFromApi changes, the previous local error might be stale.\n if (codesFromApi.every((code) => !currentError?.includes(code))) {\n setCurrentError(null);\n }\n rebuyDebugLog.log(DebugKey.SC_DISCOUNT_MANAGER, 'Synced codes from API cart:', codesFromApi);\n }\n }, [cartData?.discountCodes, appliedCodesState, currentError]);\n\n // Prioritize local error from an operation, then context error.\n const errorToDisplay = currentError ?? cartErrorFromCtx;\n\n const prepareApplyCode = useCallback(\n (code: string): ApplyCodesPayload | null => {\n if (!code) return null;\n const codeUpper = code.trim().toUpperCase();\n // Optimistically include it for the payload, server will validate\n const codesToApply = [...new Set([...appliedCodesState, codeUpper])];\n\n return { codes: codesToApply };\n },\n [appliedCodesState]\n );\n\n const prepareRemoveCode = useCallback(\n (codeToRemove: string): ApplyCodesPayload => {\n const codeUpper = codeToRemove.trim().toUpperCase();\n const codesToKeep = appliedCodesState.filter((c) => c.toUpperCase() !== codeUpper);\n\n return { codes: codesToKeep };\n },\n [appliedCodesState]\n );\n\n const prepareRemoveAllCodes = useCallback((): ApplyCodesPayload => {\n return { codes: [] };\n }, []);\n\n // This function is now for the component to call after a fetcher/H-React action\n // to interpret the result if it's not directly reflected in cartData yet.\n // For Remix, this might be called with fetcher.data.\n // For H-React, this might be less necessary if cartData updates promptly.\n const processActionResult = (resultCart: typeof cartData | null | undefined, attemptedCode?: string) => {\n if (!resultCart && attemptedCode) {\n const errorMsg = GENERIC_ERROR_CODE_MESSAGE.replace('{{code}}', attemptedCode.toUpperCase());\n setCurrentError(errorMsg);\n\n return;\n }\n\n if (attemptedCode && resultCart?.discountCodes) {\n const applied = resultCart.discountCodes.find(\n (dc) => dc.code.toUpperCase() === attemptedCode.toUpperCase() && dc.applicable\n );\n\n if (!applied) {\n const errorMsg = GENERIC_ERROR_CODE_MESSAGE.replace('{{code}}', attemptedCode.toUpperCase());\n setCurrentError(errorMsg);\n } else {\n setCurrentError(null); // Code was applied successfully\n }\n } else if (!attemptedCode) {\n // For removeAll or successful remove single\n setCurrentError(null);\n }\n // appliedCodesState will be updated by the useEffect watching cartData.discountCodes\n };\n\n return {\n appliedCodes: appliedCodesState,\n error: errorToDisplay,\n isProcessing, // This state will be set by the consuming component\n prepareApplyCode,\n prepareRemoveAllCodes,\n prepareRemoveCode,\n processActionResult, // For component to report results\n setCurrentError, // Allow component to set this directly too\n setIsProcessing, // Allow component to set this\n settings,\n };\n};\n\nexport type UseDiscountManagerReturn = ReturnType<typeof useDiscountManager>;\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/smart-cart/components/DiscountCodeInput/DiscountCodeInput.css\";\n const result = {\"rebuy-discount-code-input\":\"DiscountCodeInput_rebuy-discount-code-input\",\"rebuy-discount-code-input__form\":\"DiscountCodeInput_rebuy-discount-code-input__form\",\"rebuy-discount-code-input__input-wrapper\":\"DiscountCodeInput_rebuy-discount-code-input__input-wrapper\",\"rebuy-discount-code-input__input-label\":\"DiscountCodeInput_rebuy-discount-code-input__input-label\",\"rebuy-discount-code-input__input-wrapper--show-label\":\"DiscountCodeInput_rebuy-discount-code-input__input-wrapper--show-label\",\"rebuy-discount-code-input__input-field\":\"DiscountCodeInput_rebuy-discount-code-input__input-field\",\"rebuy-discount-code-input__apply-button\":\"DiscountCodeInput_rebuy-discount-code-input__apply-button\",\"rebuy-discount-code-input__error-message\":\"DiscountCodeInput_rebuy-discount-code-input__error-message\",\"rebuy-discount-code-input__tags-list\":\"DiscountCodeInput_rebuy-discount-code-input__tags-list\",\"rebuy-discount-code-input__tag\":\"DiscountCodeInput_rebuy-discount-code-input__tag\",\"rebuy-discount-code-input__tag-icon\":\"DiscountCodeInput_rebuy-discount-code-input__tag-icon\",\"rebuy-discount-code-input__tag-text\":\"DiscountCodeInput_rebuy-discount-code-input__tag-text\",\"rebuy-discount-code-input__tag-remove-button\":\"DiscountCodeInput_rebuy-discount-code-input__tag-remove-button\",\"rebuy-discount-code-input__total-discount-amount\":\"DiscountCodeInput_rebuy-discount-code-input__total-discount-amount\"};\n export default result;\n ", "// ~/smart-cart/components/LoginButton/LoginButton.tsx\nimport React from 'react';\n\nimport { RebuyLink } from '~/components/RebuyLink';\nimport { DebugKey } from '~/constants/debug';\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\n\n/* eslint-disable-next-line no-restricted-imports */\nimport styles from './LoginButton.module.css';\n\nexport const LoginButton = React.memo(() => {\n const { cartData, getComponentConfigByType } = useSmartCart();\n const componentConfig = getComponentConfigByType('login');\n\n const isLoggedInViaApi = !!cartData?.buyerIdentity?.customer?.id;\n\n rebuyDebugLog.log(DebugKey.SC_LOGIN_BUTTON, 'Login status', {\n buyerIdentity: cartData?.buyerIdentity,\n isLoggedInViaApi,\n });\n\n if (isLoggedInViaApi || !componentConfig) {\n return null;\n }\n\n const loginLabel = componentConfig?.settings?.language?.title ?? 'Login';\n const loginUrl = componentConfig?.settings?.url ?? '/account/login';\n\n return (\n <RebuyLink\n ariaLabel={loginLabel}\n className={styles['rebuy-login-button']}\n data-rebuy-component=\"login\"\n data-rebuy-component-id={componentConfig.component_id ?? 'login'}\n handle={loginUrl}\n >\n {loginLabel}\n </RebuyLink>\n );\n});\nLoginButton.displayName = 'LoginButton';\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/smart-cart/components/LoginButton/LoginButton.css\";\n const result = {\"rebuy-login-button\":\"LoginButton_rebuy-login-button\"};\n export default result;\n ", "// src/onsite/js/modules/SmartCartReact/components/SmartCartApp/SmartCartApp.tsx\nimport React, { useEffect, useMemo, useRef } from 'react';\nimport { DebugKey } from '~/constants/debug';\n\nimport { useSmartCartApps } from '~/smart-cart/hooks/useSmartCartApps';\nimport type { EnabledSmartCartApp } from '~/smart-cart/types/smart-cart-app';\nimport type { SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport { executeScriptsInContainer } from '~/smart-cart/utils/executeScriptsInContainer';\n\ntype SmartCartAppProps = {\n /** The specific configuration object for this Smart Cart App instance. */\n componentConfig: Extract<SmartCartComponentConfig, { type: 'smart_cart_app' }>;\n};\n\n/**\n * Renders a container for a specific Smart Cart App, fetching its content\n * and executing its scripts via the useSmartCartApps hook.\n *\n * ! WARNING: This component uses `dangerouslySetInnerHTML` and a script execution\n * ! helper to run code fetched from an API. This approach avoids `eval()` to comply\n * ! with Content Security Policies (CSP) but still carries risks (e.g., XSS).\n * ! Use with caution.\n */\nexport const SmartCartApp = React.memo(({ componentConfig }: SmartCartAppProps) => {\n const containerRef = useRef<HTMLDivElement>(null);\n const executedScriptRef = useRef<string | null>(null);\n\n const { enrichedApps, error: appsHookError, isLoading: appsLoading } = useSmartCartApps();\n\n const componentId = componentConfig.component_id;\n const appId = useMemo(\n () => (componentConfig.settings?.app_id ? Number(componentConfig.settings.app_id) : null),\n [componentConfig.settings?.app_id]\n );\n\n const appData = appId !== null ? enrichedApps.get(appId) : null;\n const enabledAppData = appData?.enabled ? (appData as EnabledSmartCartApp) : null;\n const scriptContent = enabledAppData?.script ?? null;\n\n useEffect(() => {\n const container = containerRef.current;\n\n if (container && scriptContent && executedScriptRef.current !== scriptContent) {\n // Use setTimeout to defer execution until after the current render cycle.\n // This gives the browser time to ensure all DOM elements, including the\n // body tag with the nonce, are available to be queried.\n const timerId = setTimeout(() => {\n executeScriptsInContainer(\n container,\n DebugKey.SC_PARTNER_APPS,\n `Smart Cart App (ID: ${componentId}, App ID: ${appId})`\n );\n // Mark as executed AFTER the script has run (fixed React Strict Mode issues)\n executedScriptRef.current = scriptContent;\n }, 0);\n\n // Cleanup the timer if the component unmounts before it fires.\n return () => {\n clearTimeout(timerId);\n };\n } else if (!scriptContent && executedScriptRef.current !== null) {\n executedScriptRef.current = null;\n }\n }, [scriptContent, appId, componentId]);\n // --- Conditional Rendering Logic (After Hooks) ---\n\n // 1. Handle Loading state from the hook\n if (appsLoading) {\n return <div data-rebuy-component-id={componentId}>Loading App ({appId ?? 'N/A'})...</div>;\n }\n\n // 2. Handle Error state from the hook (fatal error during fetch/processing)\n if (appsHookError) {\n console.error(`[SmartCartApp - ${componentId}] Hook error prevented app rendering: ${appsHookError}`);\n\n return <div data-rebuy-component-id={componentId}>Error loading app data.</div>;\n }\n\n // 3. Handle Missing Config/ID\n if (appId === null) {\n console.warn(`[SmartCartApp - ${componentId}] Missing App ID (settings.app_id) in configuration.`);\n\n return null;\n }\n\n // 4. Handle App Not Available / Disabled / No Content\n if (!enabledAppData || !scriptContent) {\n rebuyDebugLog.log(\n DebugKey.SC_PARTNER_APPS,\n `[SmartCartApp - ${componentId}] App ID ${appId} is not available, disabled, or has no script content.`\n );\n\n return null;\n }\n\n return (\n <div\n dangerouslySetInnerHTML={{ __html: scriptContent }}\n data-rebuy-app-id={appId}\n data-rebuy-component=\"smart_cart_app\"\n data-rebuy-component-id={componentId}\n ref={containerRef}\n />\n );\n});\n\nSmartCartApp.displayName = 'SmartCartApp';\n", "// src/onsite/js/modules/SmartCartReact/hooks/useSmartCartApps.ts\nimport { useEffect, useState } from 'react';\nimport { DebugKey } from '~/constants/debug';\n\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport {\n type DisabledSmartCartApp,\n type EnabledSmartCartApp,\n type EnrichedSmartCartApp,\n type SmartCartAppFromCachedEndpoint,\n type SmartCartAppMerchantConfig,\n smartCartAppFromCachedEndpointSchema,\n} from '~/smart-cart/types/smart-cart-app';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport { safeJsonParse } from '~/smart-cart/utils/safeJsonParse';\n\ntype UseSmartCartAppsResult = {\n enrichedApps: Map<number, EnrichedSmartCartApp>;\n error: string | null;\n isLoading: boolean;\n};\n\n/**\n * Represents the merchant configuration after initial processing within the hook.\n */\ntype ProcessedConfigApp = {\n // Corresponds to partner_app_id from the merchant config data\n enabled: boolean;\n id: number;\n user_inputs?: Record<string, string> | null;\n};\n\n/**\n * Hook to fetch, enrich, and manage Smart Cart App data.\n * Fetches data from the Rebuy `/smart_cart/apps` endpoint based on the\n * configured apps in the Smart Cart settings. Handles variable substitution.\n * Uses Zod to validate individual app data structures from the API.\n *\n * @returns {UseSmartCartAppsResult} Object containing enriched apps, loading state, and any fatal errors\n */\nexport const useSmartCartApps = (): UseSmartCartAppsResult => {\n const { apiKey, cacheKey, config, shopifyDomain } = useSmartCart();\n const [enrichedApps, setEnrichedApps] = useState<Map<number, EnrichedSmartCartApp>>(new Map());\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [error, setError] = useState<string | null>(null);\n\n const initialAppsConfig: SmartCartAppMerchantConfig[] | undefined = config?.apps;\n\n useEffect(() => {\n let isMounted = true;\n\n const fetchAndEnrichApps = async () => {\n // --- 0. Early exit if no apps configured ---\n if (!initialAppsConfig || initialAppsConfig.length === 0) {\n if (isMounted) {\n setEnrichedApps(new Map());\n setIsLoading(false);\n setError(null);\n }\n\n return;\n }\n\n setIsLoading(true);\n setError(null);\n\n // --- 1. Normalize initial config ---\n const processedAppsConfig: ProcessedConfigApp[] = structuredClone(initialAppsConfig).map(\n (app: SmartCartAppMerchantConfig): ProcessedConfigApp => ({\n enabled: app.enabled,\n id: app.partner_app_id,\n user_inputs: app.user_inputs,\n })\n );\n\n const enabledAppIds = processedAppsConfig.filter((app) => app.enabled).map((app) => app.id);\n\n // --- 2. Early exit if no apps are enabled ---\n if (enabledAppIds.length === 0) {\n rebuyDebugLog.log(DebugKey.SC_PARTNER_APPS, '[useSmartCartApps] No enabled apps found in config.');\n\n const disabledAppsMap = new Map<number, EnrichedSmartCartApp>();\n processedAppsConfig.forEach((configApp) => {\n const disabledApp: DisabledSmartCartApp = {\n enabled: false,\n id: configApp.id,\n user_inputs: configApp.user_inputs,\n };\n disabledAppsMap.set(configApp.id, disabledApp);\n });\n\n if (isMounted) {\n setEnrichedApps(disabledAppsMap);\n setIsLoading(false);\n }\n\n return;\n }\n\n // --- 3. Fetch from API ---\n try {\n rebuyDebugLog.log(\n DebugKey.SC_PARTNER_APPS,\n '[useSmartCartApps] Fetching app data for enabled app IDs:',\n enabledAppIds\n );\n\n if (!shopifyDomain || !apiKey || !cacheKey) {\n throw new Error(\n 'Missing required Rebuy configuration (shop domain, API key, or cache key) in SmartCartContext'\n );\n }\n\n const appsUrl = `https://cached.rebuyengine.com/api/v1/smart_cart/apps?shop=${encodeURIComponent(\n shopifyDomain\n )}&key=${encodeURIComponent(apiKey)}&cache_key=${encodeURIComponent(cacheKey)}`;\n\n const response = await fetch(appsUrl);\n\n if (!response.ok) {\n throw new Error(\n `Smart Cart apps API request failed with status ${response.status} for URL: ${appsUrl}`\n );\n }\n\n const rawJson = await response.json();\n\n // --- 4. Validate API Response Structure (Array Check) ---\n if (!Array.isArray(rawJson)) {\n throw new Error('Smart Cart apps API response was not an array.');\n }\n\n // --- 5. Parse & Validate Individual Items with Zod ---\n const validApiAppData: SmartCartAppFromCachedEndpoint[] = [];\n rawJson.forEach((item: unknown, index: number) => {\n const parseResult = smartCartAppFromCachedEndpointSchema.safeParse(item);\n\n if (parseResult.success) {\n validApiAppData.push(parseResult.data);\n } else {\n console.error(\n `[useSmartCartApps] Failed to parse API response item at index ${index}:`,\n parseResult.error.errors,\n 'Raw item:',\n item\n );\n }\n });\n\n if (!isMounted) return;\n\n rebuyDebugLog.groupCollapsed(\n DebugKey.SC_PARTNER_APPS,\n '[useSmartCartApps] API Response Items Passing Validation'\n );\n rebuyDebugLog.log(DebugKey.SC_PARTNER_APPS, validApiAppData);\n rebuyDebugLog.groupEnd();\n\n // --- 6. Enrich and Process (using only validated data) ---\n const newEnrichedApps = new Map<number, EnrichedSmartCartApp>();\n\n processedAppsConfig.forEach((configApp: ProcessedConfigApp) => {\n const apiData = validApiAppData.find((apiApp) => apiApp.id === configApp.id);\n\n if (configApp.enabled && apiData) {\n let scriptWithVars = apiData.script;\n let missingVariables = false;\n\n if (scriptWithVars && apiData.script_variable_json) {\n const variableObject = safeJsonParse<Record<string, string> | null>(\n apiData.script_variable_json\n );\n const userInputs = configApp.user_inputs ?? {};\n\n if (variableObject) {\n Object.keys(variableObject).forEach((variableName) => {\n const inputKey = Object.keys(userInputs).find(\n (key) => key.toLowerCase() === variableName.toLowerCase()\n );\n const variableValue = inputKey ? userInputs[inputKey] : undefined;\n\n if (variableValue !== undefined && variableValue !== null && variableValue !== '') {\n const regex = new RegExp(`\\\\{\\\\{${variableName}\\\\}\\\\}`, 'g');\n scriptWithVars = scriptWithVars!.replace(regex, variableValue);\n } else {\n console.warn(\n `[useSmartCartApps] Missing or empty required variable \"${variableName}\" for App ID ${configApp.id}. Variable definition: ${variableObject[variableName]}`\n );\n missingVariables = true;\n }\n });\n }\n }\n\n if (missingVariables) {\n console.warn(\n `[useSmartCartApps] Disabling App ID ${configApp.id} due to missing variables.`\n );\n\n const disabledApp: DisabledSmartCartApp = {\n enabled: false,\n id: configApp.id,\n user_inputs: configApp.user_inputs,\n };\n newEnrichedApps.set(configApp.id, disabledApp);\n } else {\n const enabledApp: EnabledSmartCartApp = {\n ...apiData,\n enabled: true,\n id: configApp.id,\n script: scriptWithVars,\n user_inputs: configApp.user_inputs,\n };\n newEnrichedApps.set(configApp.id, enabledApp);\n rebuyDebugLog.log(\n DebugKey.SC_PARTNER_APPS,\n `[useSmartCartApps] Successfully processed App ID ${configApp.id}. Enabled: true`\n );\n }\n } else if (configApp.enabled && !apiData) {\n console.warn(\n `[useSmartCartApps] App ID ${configApp.id} enabled in config but not found in validated API response (or failed validation). Disabling.`\n );\n\n const disabledApp: DisabledSmartCartApp = {\n enabled: false,\n id: configApp.id,\n user_inputs: configApp.user_inputs,\n };\n newEnrichedApps.set(configApp.id, disabledApp);\n } else {\n const disabledApp: DisabledSmartCartApp = {\n enabled: false,\n id: configApp.id,\n user_inputs: configApp.user_inputs,\n };\n newEnrichedApps.set(configApp.id, disabledApp);\n }\n });\n\n if (isMounted) {\n setEnrichedApps(newEnrichedApps);\n }\n } catch (err) {\n const message =\n err instanceof Error\n ? err.message\n : 'An unknown error occurred while fetching or processing smart cart apps.';\n console.error('[useSmartCartApps] Fatal Error:', message, err);\n\n if (isMounted) {\n setError(message);\n setEnrichedApps(new Map());\n }\n } finally {\n if (isMounted) {\n setIsLoading(false);\n }\n }\n };\n\n fetchAndEnrichApps();\n\n return () => {\n isMounted = false;\n };\n }, [initialAppsConfig, shopifyDomain, apiKey, cacheKey]);\n\n return { enrichedApps, error, isLoading };\n};\n", "import { z } from 'zod';\n\n/**\n * Smart Cart App shape from the {cached.rebuyengine.com}/api/v1/smart_cart/apps endpoint.\n * Used to enrich the Smart Cart App data for customers on the storefront\n *\n * @see https://bitbucket.org/abovemarket/rebuyengine.com/src/main/application/libraries/Cache/SmartCartApps.php#application/libraries/Cache/SmartCartApps.php-88\n */\nexport const smartCartAppFromCachedEndpointSchema = z.object({\n id: z.number(),\n name: z.string(),\n script: z.string(),\n script_variable_json: z.string().nullable(),\n});\n\n/**\n * Array of Smart Cart Apps fetched from the {cached.rebuyengine.com}/api/v1/smart_cart/apps endpoint.\n */\nexport const smartCartAppsFromCachedEndpointSchema = z.array(smartCartAppFromCachedEndpointSchema);\n\n/**\n * Smart Cart App Merchant Config Schema (stored in the Smart Cart's settings.apps array)\n * Data sampling from the smart_cart_apps DB table.\n *\n * @see https://bitbucket.org/abovemarket/rebuy-core-ci4/src/main/src/Models/SmartCart/SmartCartV2s.php#src/Models/SmartCart/SmartCartV2s.php-111\n */\nexport const smartCartAppMerchantConfigSchema = z.object({\n enabled: z.boolean(),\n partner_app_id: z.number(),\n /** @deprecated - not used for anything in V2 */\n show_in_empty_cart: z.boolean().nullish(),\n user_inputs: z.record(z.string(), z.string()).nullable(),\n});\n\n// Base type for normalized configuration\nexport type NormalizedAppConfig = {\n enabled: boolean;\n id: number;\n user_inputs?: Record<string, string> | null;\n};\n\n// Define the discriminated union for app states\n\n/**\n * Base properties common to all app entries.\n */\nexport type BaseSmartCartApp = {\n id: number;\n user_inputs?: Record<string, string> | null;\n};\n\n/**\n * Type for enabled apps that includes all required API data.\n */\nexport type EnabledSmartCartApp = BaseSmartCartApp &\n z.infer<typeof smartCartAppFromCachedEndpointSchema> & { enabled: true };\n\n/**\n * Type for disabled apps that doesn't require API data.\n */\nexport type DisabledSmartCartApp = BaseSmartCartApp & { enabled: false };\n\n/**\n * Union type for all possible app states.\n * Can be used with type guards: if (app.enabled) { ... }\n */\nexport type EnrichedSmartCartApp = EnabledSmartCartApp | DisabledSmartCartApp;\n\n/**\n * Smart Cart App From Cached Endpoint (cached.rebuyengine.com/api/v1/smart_cart/apps)\n */\nexport type SmartCartAppFromCachedEndpoint = z.infer<typeof smartCartAppFromCachedEndpointSchema>;\n\n/**\n * Smart Cart App Merchant-defined configuration (stored in the Smart Cart's settings.apps array)\n */\nexport type SmartCartAppMerchantConfig = z.infer<typeof smartCartAppMerchantConfigSchema>;\n", "// ~/smart-cart/components/TieredProgressBar/TieredProgressBar.tsx\nimport type { CartLineInput as HRCartLineInput } from '@shopify/hydrogen-react/storefront-api-types';\nimport clsx from 'clsx';\nimport React, { useCallback, useEffect, useMemo, useState } from 'react';\nimport { useFetcher } from 'react-router';\nimport { useShallow } from 'zustand/shallow';\n\nimport { DebugKey } from '~/constants/debug';\nimport {\n calculateVisualProgressBarPercentage,\n checkIsTierReached,\n getGiftAreaTitle,\n getTierFeedbackText,\n getTierIconComponent,\n getTierLabel,\n getTierMinimum,\n shouldRenderGiftArea,\n shouldRenderGiftAreaTitle,\n type TierIconImage,\n} from '~/smart-cart/components/TieredProgressBar/progressBarUtils';\nimport { TieredProgressBarGiftItem as GiftItem } from '~/smart-cart/components/TieredProgressBar/TPBGiftItem';\nimport {\n TieredProgressBarGiftStatus as GiftStatus,\n TieredProgressBarTierType,\n type TieredProgressBarQualifiedGiftState,\n type TieredProgressBarTier,\n} from '~/smart-cart/components/TieredProgressBar/types';\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport {\n useTieredProgressBarStore,\n type SelectedTieredProgressBarStore,\n type TieredProgressBarStoreState,\n} from '~/smart-cart/store/tieredProgressBarStore'; // eslint-disable-line import/order\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport * as debugStyles from '~/smart-cart/utils/debugStyles';\nimport { formatMoney } from '~/smart-cart/utils/moneyUtils';\n\n// eslint-disable-next-line no-restricted-imports\nimport type { JsonValue } from '~/types/common';\nimport styles from './TieredProgressBar.module.css';\n\n/**\n * TieredProgressBar component.\n * Displays progress towards different reward tiers (e.g., free shipping, discounts, free products)\n * based on the cart subtotal. It interacts with the `tieredProgressBarStore` for its state\n * and logic, and with `useSmartCart` for cart actions.\n * This component does not take direct props as its configuration is managed via the store,\n * initialized from settings provided in `SmartCartContext`.\n */\nexport const TieredProgressBar: React.FC = React.memo(() => {\n const { hydrogenReactCartActions, isCartBusy, isHydrogenReact } = useSmartCart();\n const tpbUserActionFetcher = useFetcher();\n const [showDebugPanel, setShowDebugPanel] = useState(false);\n const {\n _lastFetchedBarId,\n activeBarConfig,\n cartSyncError,\n currentSubtotal,\n declinedGiftMap,\n fetchedProductMap,\n giftStates,\n hasFreeShippingOnSubscription,\n isCartReady,\n isManuallyDisabled,\n productFetchError,\n productFetchStatus,\n userActionError,\n } = useTieredProgressBarStore(\n useShallow(\n (state: TieredProgressBarStoreState): SelectedTieredProgressBarStore => ({\n _lastFetchedBarId: state._lastFetchedBarId,\n activeBarConfig: state.activeBarConfig,\n cartSyncError: state.cartSyncError,\n cartSyncStatus: state.cartSyncStatus,\n currentSubtotal: state.currentSubtotal,\n declinedGiftMap: state.declinedGiftMap,\n fetchedProductMap: state.fetchedProductMap,\n giftStates: state.giftStates,\n hasFreeShippingOnSubscription: state.hasFreeShippingOnSubscription,\n initializationStatus: state.initializationStatus,\n isCartReady: state.isCartReady,\n isManuallyDisabled: state.isManuallyDisabled,\n productFetchError: state.productFetchError,\n productFetchStatus: state.productFetchStatus,\n userActionError: state.userActionError,\n userActionStatus: state.userActionStatus,\n })\n )\n );\n\n const handleSelectVariantStore = useTieredProgressBarStore((state) => state.handleSelectVariant);\n const handleAddOrReAddGiftStore = useTieredProgressBarStore((state) => state.handleAddOrReAddGift);\n const handleRemoveGiftStore = useTieredProgressBarStore((state) => state.handleRemoveGift);\n const clearUserActionError = useTieredProgressBarStore((state) => state.clearUserActionError);\n const setSubmitFunctions = useTieredProgressBarStore((state) => state.setSubmitFunctions);\n\n const shouldDisableGiftActions = useMemo(() => {\n // Disable if cart is globally busy (covers H-React, TPB gift sync/user actions)\n // OR if TPB is still fetching its own product data.\n return isCartBusy || productFetchStatus === 'loading';\n }, [isCartBusy, productFetchStatus]);\n\n useEffect(() => {\n if (isHydrogenReact) {\n const hReactLinesAdd = hydrogenReactCartActions?.linesAdd;\n const hReactLinesRemove = hydrogenReactCartActions?.linesRemove;\n\n if (hReactLinesAdd && hReactLinesRemove) {\n setSubmitFunctions(hReactLinesAdd, hReactLinesRemove);\n rebuyDebugLog.log(DebugKey.SC_TPB, 'Set H-React submit functions for TPB.');\n } else {\n rebuyDebugLog.warn(\n DebugKey.SC_TPB,\n '[TPB] Hydrogen React cart actions not available. TPB gift actions might fail.'\n );\n // Set dummy functions that log errors to prevent crashes if called\n setSubmitFunctions(\n (items: HRCartLineInput[]) =>\n console.error('[TPB] H-React linesAdd not configured for TPB.', items),\n (ids: string[]) => console.error('[TPB] H-React linesRemove not configured for TPB.', ids)\n );\n }\n } else {\n // Vanilla Hydrogen/Remix path\n const addItemsRemix = (items: HRCartLineInput[]) => {\n const plainItems = items.map((item) => ({\n attributes: item.attributes?.map((attr) => ({ key: attr.key, value: attr.value })),\n merchandiseId: item.merchandiseId,\n quantity: item.quantity,\n }));\n tpbUserActionFetcher.submit({ action: 'cartLinesAdd', data: { lines: plainItems } } as JsonValue, {\n action: '/cart',\n encType: 'application/json',\n method: 'POST',\n });\n };\n const removeItemsRemix = (lineIds: string[]) => {\n tpbUserActionFetcher.submit({ action: 'cartLinesRemove', data: { lineIds } } as JsonValue, {\n action: '/cart',\n encType: 'application/json',\n method: 'POST',\n });\n };\n setSubmitFunctions(addItemsRemix, removeItemsRemix);\n rebuyDebugLog.log(DebugKey.SC_TPB, 'Set Remix fetcher submit functions for TPB.');\n }\n }, [isHydrogenReact, hydrogenReactCartActions, tpbUserActionFetcher, setSubmitFunctions]);\n\n useEffect(() => {\n if (userActionError) {\n const timer = setTimeout(() => clearUserActionError(), 5_000);\n\n return () => clearTimeout(timer);\n }\n }, [userActionError, clearUserActionError]);\n\n const { amountToNextTier, currentTier, lastReachedTier, realPercentageComplete, visualPercentageComplete } =\n useMemo(() => {\n let calculatedAmountToNextTier = 0,\n calculatedCurrentTier: TieredProgressBarTier | null = null,\n calculatedLastReachedTier: TieredProgressBarTier | null = null,\n calculatedRealPercentageComplete = 0;\n\n if (activeBarConfig && activeBarConfig.tiers.length > 0 && isCartReady) {\n const allTiers = activeBarConfig.tiers;\n const reachedTiers = allTiers.filter((t) =>\n checkIsTierReached(t, currentSubtotal, hasFreeShippingOnSubscription)\n );\n calculatedLastReachedTier = reachedTiers[reachedTiers.length - 1] ?? null;\n calculatedCurrentTier =\n allTiers.find((t) => !checkIsTierReached(t, currentSubtotal, hasFreeShippingOnSubscription)) ??\n null;\n calculatedAmountToNextTier = calculatedCurrentTier\n ? Math.max(0, getTierMinimum(calculatedCurrentTier) - currentSubtotal)\n : 0;\n\n // \"Real\" Percentage calculation (for ARIA and internal data)\n const numericTiers = allTiers.filter((t) => t.type !== TieredProgressBarTierType.DECORATIVE);\n const highestMinimum = Math.max(0, ...numericTiers.map(getTierMinimum));\n calculatedRealPercentageComplete =\n highestMinimum <= 0\n ? currentSubtotal > 0\n ? 100\n : 0\n : currentSubtotal >= highestMinimum\n ? 100\n : currentSubtotal <= 0\n ? 0\n : (currentSubtotal / highestMinimum) * 100;\n calculatedRealPercentageComplete = Math.max(0, Math.min(100, calculatedRealPercentageComplete));\n }\n\n // \"Visual\" Percentage calculation (for UI display)\n const calculatedVisualPercentageComplete = calculateVisualProgressBarPercentage(\n activeBarConfig,\n currentSubtotal,\n hasFreeShippingOnSubscription\n );\n\n return {\n amountToNextTier: calculatedAmountToNextTier,\n currentTier: calculatedCurrentTier,\n lastReachedTier: calculatedLastReachedTier,\n realPercentageComplete: calculatedRealPercentageComplete,\n visualPercentageComplete: calculatedVisualPercentageComplete,\n };\n }, [activeBarConfig, currentSubtotal, hasFreeShippingOnSubscription, isCartReady]);\n\n const giftsForDisplay = useMemo(() => Array.from(giftStates.values()), [giftStates]);\n const feedbackText = useMemo(\n () => getTierFeedbackText(activeBarConfig, currentTier, lastReachedTier, amountToNextTier, fetchedProductMap),\n [activeBarConfig, currentTier, lastReachedTier, amountToNextTier, fetchedProductMap]\n );\n\n const handleVariantSelect = useCallback(\n (tierId: string, variantGid: string) => {\n handleSelectVariantStore(tierId, variantGid);\n },\n [handleSelectVariantStore]\n );\n const handleGiftAddOrReAdd = useCallback(\n (tierId: string) => {\n handleAddOrReAddGiftStore(tierId);\n },\n [handleAddOrReAddGiftStore]\n );\n const handleGiftRemove = useCallback(\n (tierId: string) => {\n handleRemoveGiftStore(tierId);\n },\n [handleRemoveGiftStore]\n );\n\n const lineItemMode = activeBarConfig?.use_line_item_mode ?? false;\n\n const productsToRenderInGiftArea = useMemo(\n () =>\n giftsForDisplay.filter((p: TieredProgressBarQualifiedGiftState) => {\n if (!p.isReached) return false;\n\n if (p.displayStatus === GiftStatus.UNAVAILABLE && !p.error && !p.canReAdd) return false;\n\n if (lineItemMode && p.displayStatus === GiftStatus.ADDED) return false;\n\n if (p.displayStatus === GiftStatus.IDLE && !p.error && !p.isDeclined) return false;\n\n return true;\n }),\n [giftsForDisplay, lineItemMode]\n );\n\n const renderGiftArea = useMemo(\n () => shouldRenderGiftArea(activeBarConfig, productsToRenderInGiftArea.length > 0),\n [activeBarConfig, productsToRenderInGiftArea.length]\n );\n const renderGiftAreaTitle = shouldRenderGiftAreaTitle(activeBarConfig);\n const giftAreaTitle = getGiftAreaTitle(activeBarConfig);\n\n // For loading/error UI related to user actions on TPB:\n const userActionFetcherError = !isHydrogenReact && (tpbUserActionFetcher.data as { error?: string })?.error;\n\n if (userActionFetcherError) {\n console.error('User action fetcher error:', userActionFetcherError);\n }\n\n const isContextLoading = useSmartCart().isLoading;\n\n // If no active bar (disabled, no match, no tiers configured, etc.)\n if (!activeBarConfig || activeBarConfig.tiers.length === 0) {\n return null;\n }\n\n const checkTierReachedCallback = (tier: TieredProgressBarTier | null): boolean => {\n if (!tier) return false;\n\n return checkIsTierReached(tier, currentSubtotal, hasFreeShippingOnSubscription);\n };\n\n const progressBarId = `tpb-main-${activeBarConfig.id}`;\n const feedbackId = `tpb-feedback-text-${activeBarConfig.id}`;\n const giftAreaTitleId = `tpb-giftarea-title-${activeBarConfig.id}`;\n\n return (\n <div className={styles['rebuy-tiered-progress-bar']} data-rebuy-component=\"tiered-progress-bar\">\n <div className={styles['rebuy-tiered-progress-bar__main-progress-area']} id={progressBarId}>\n <div className={styles['rebuy-tiered-progress-bar__tier-markers-list']}>\n {activeBarConfig.tiers.map((tier) => {\n const isReached = checkTierReachedCallback(tier);\n const tierLabel = getTierLabel(tier, fetchedProductMap);\n const iconRenderData = getTierIconComponent(tier, isReached, fetchedProductMap);\n let iconContainerStyle: React.CSSProperties = {};\n const configuredIconSize = tier.product_tier_element_size;\n\n if (configuredIconSize)\n iconContainerStyle = {\n height: configuredIconSize,\n width: configuredIconSize,\n };\n\n let iconElement: React.ReactNode;\n\n if (React.isValidElement(iconRenderData)) iconElement = iconRenderData;\n else if (iconRenderData.type === 'image') {\n const imageObject = iconRenderData as TierIconImage;\n iconElement = (\n <img\n alt={imageObject.alt}\n className={styles['rebuy-tiered-progress-bar__tier-icon-image']}\n src={imageObject.src}\n />\n );\n } else iconElement = null;\n\n return (\n <div\n className={clsx(styles['rebuy-tiered-progress-bar__tier-step'], {\n [styles['rebuy-tiered-progress-bar__tier-step--reached']]: isReached,\n })}\n key={tier.id}\n title={`${tierLabel} (${isReached ? 'Reached' : 'Pending'} at ${formatMoney(getTierMinimum(tier))})`}\n >\n <div\n className={styles['rebuy-tiered-progress-bar__tier-icon-wrapper']}\n style={iconContainerStyle}\n >\n {iconElement}\n </div>\n <div className={styles['rebuy-tiered-progress-bar__tier-label']}>{tierLabel}</div>\n </div>\n );\n })}\n </div>\n <div className={styles['rebuy-tiered-progress-bar__track']}>\n <div\n aria-label=\"Reward progress\"\n aria-labelledby={feedbackId}\n aria-valuemax={100}\n aria-valuemin={0}\n aria-valuenow={Math.round(realPercentageComplete)}\n className={styles['rebuy-tiered-progress-bar__fill']}\n role=\"progressbar\"\n style={{ width: `${visualPercentageComplete}%` }}\n />\n </div>\n </div>\n\n <div aria-live=\"polite\" className={styles['rebuy-tiered-progress-bar__feedback-message']} id={feedbackId}>\n {(isContextLoading || productFetchStatus === 'loading') && !feedbackText\n ? 'Loading rewards...'\n : feedbackText}\n {productFetchError && (\n <div className={styles['rebuy-tiered-progress-bar__error-message']}>\n Could not load reward info.\n {rebuyDebugLog.isKeyActive(DebugKey.SC_TPB) && ` Details: ${productFetchError}`}\n </div>\n )}\n {cartSyncError && (\n <div className={styles['rebuy-tiered-progress-bar__error-message']}>\n Could not update rewards.\n {rebuyDebugLog.isKeyActive(DebugKey.SC_TPB) && ` Details: ${cartSyncError}`}\n </div>\n )}\n {userActionError && (\n <div className={styles['rebuy-tiered-progress-bar__error-message']}>\n Error: {userActionError.message}\n </div>\n )}\n </div>\n\n {renderGiftArea && (\n <div className={styles['rebuy-tiered-progress-bar__gift-area']}>\n {renderGiftAreaTitle && (\n <h3 className={styles['rebuy-tiered-progress-bar__gift-area-title']} id={giftAreaTitleId}>\n {giftAreaTitle}\n </h3>\n )}\n {shouldDisableGiftActions && // If actions are disabled (likely loading something)\n productsToRenderInGiftArea.length === 0 &&\n !productFetchError &&\n !cartSyncError &&\n !userActionError && (\n <div\n style={{\n padding: '10px 0',\n textAlign: 'center',\n }}\n >\n Loading gifts...\n </div>\n )}\n {productsToRenderInGiftArea.length > 0 && (\n <div\n aria-labelledby={renderGiftAreaTitle ? giftAreaTitleId : undefined}\n className={styles['rebuy-tiered-progress-bar__gift-items-list']}\n >\n {productsToRenderInGiftArea.map((productState) => (\n <GiftItem\n isGloballySyncing={shouldDisableGiftActions}\n key={productState.tierId}\n onAddOrReAdd={handleGiftAddOrReAdd}\n onRemove={handleGiftRemove}\n onSelectVariant={handleVariantSelect}\n product={productState}\n />\n ))}\n </div>\n )}\n </div>\n )}\n\n {rebuyDebugLog.isKeyActive(DebugKey.SC_TPB) && (\n <button\n onClick={() => setShowDebugPanel(!showDebugPanel)}\n style={{\n ...debugStyles.toggleButton(),\n display: 'block',\n marginTop: '12px',\n }}\n >\n {showDebugPanel ? 'Hide Debug Panel' : 'Show Debug Panel'}\n </button>\n )}\n\n {rebuyDebugLog.isKeyActive(DebugKey.SC_TPB) && showDebugPanel && (\n <div\n style={{\n ...debugStyles.debugPanel,\n margin: '12px 0',\n maxHeight: '300px',\n maxWidth: 'none',\n width: '100%',\n }}\n >\n <div style={debugStyles.infoText}>\n <strong>Progress Bar Debug Info</strong>\n </div>\n <div style={debugStyles.codeBlock}>\n <div>Subtotal: {formatMoney(currentSubtotal)}</div>\n <div>Visual Progress: {visualPercentageComplete.toFixed(0)}%</div>\n <div>Actual Progress: {realPercentageComplete.toFixed(0)}%</div>\n {amountToNextTier > 0 && <div>To Next Tier: {formatMoney(amountToNextTier)}</div>}\n {currentTier && <div>Current Tier: {getTierLabel(currentTier)}</div>}\n {cartSyncError && <div style={{ color: '#f66' }}>Error: {cartSyncError}</div>}\n </div>\n {giftsForDisplay.length > 0 && (\n <div style={{ marginTop: '8px' }}>\n <div style={debugStyles.infoText}>Gift Status:</div>\n <div style={debugStyles.codeBlock}>\n {giftsForDisplay.map((gift, idx) => (\n <div key={idx} style={{ marginBottom: '4px' }}>\n Tier {gift.tierId}: {gift.displayStatus}\n {gift.isInCart && ' \u2713'}\n </div>\n ))}\n </div>\n </div>\n )}\n </div>\n )}\n </div>\n );\n});\n\nTieredProgressBar.displayName = 'TieredProgressBar';\n", "// ~/smart-cart/components/TieredProgressBar/TieredProgressBar.tsx\nimport clsx from 'clsx';\n\nimport type React from 'react';\nimport { getFreeVariantTitle } from '~/smart-cart/components/TieredProgressBar/progressBarUtils';\nimport {\n TieredProgressBarGiftStatus as GiftStatus,\n type TieredProgressBarQualifiedGiftState,\n} from '~/smart-cart/components/TieredProgressBar/types';\n\nimport { formatMoney } from '~/smart-cart/utils/moneyUtils';\n\n// eslint-disable-next-line no-restricted-imports\nimport styles from './TieredProgressBar.module.css';\n\n// --- Sub-component for rendering individual gift items ---\ntype TieredProgressBarGiftItemProps = {\n isGloballySyncing: boolean;\n onAddOrReAdd: (tierId: string) => void;\n onRemove: (tierId: string) => void;\n onSelectVariant: (tierId: string, variantGid: string) => void;\n product: TieredProgressBarQualifiedGiftState;\n};\n\n/**\n * Renders an individual gift item within the Tiered Progress Bar's gift area.\n * It displays product information, variant selection (if applicable),\n * and action buttons (add/remove/re-add).\n *\n * @param {TieredProgressBarGiftItemProps} props The props for the component.\n *\n * @returns {React.ReactElement} The rendered gift item.\n */\nexport const TieredProgressBarGiftItem: React.FC<TieredProgressBarGiftItemProps> = ({\n isGloballySyncing,\n onAddOrReAdd,\n onRemove,\n onSelectVariant,\n product,\n}) => {\n const { availableChoices, canReAdd, displayStatus, error, image, tierId, title, variantInCart } = product;\n const displayVariantTitle = getFreeVariantTitle(variantInCart);\n const handleVariantChange = (event: React.ChangeEvent<HTMLSelectElement>) => {\n if (isGloballySyncing) return;\n\n const selectedVariantGid = event.target.value;\n\n if (selectedVariantGid) onSelectVariant(String(tierId), selectedVariantGid);\n event.target.value = '';\n };\n const handleReAddClick = () => {\n if (!isGloballySyncing) onAddOrReAdd(String(tierId));\n };\n const handleRemoveClick = () => {\n if (!isGloballySyncing) onRemove(String(tierId));\n };\n const imageSrc = image?.src;\n const imageAlt = image?.altText ?? title;\n const isDisabled = isGloballySyncing || !!error;\n const itemLevelError = error;\n\n return (\n <div\n className={clsx(styles['rebuy-tiered-progress-bar__gift-item'], {\n [styles['rebuy-tiered-progress-bar__gift-item--syncing']]: isGloballySyncing,\n })}\n >\n <div className={styles['rebuy-tiered-progress-bar__gift-item-image-wrapper']}>\n {imageSrc ? (\n <img\n alt={imageAlt}\n className={styles['rebuy-tiered-progress-bar__gift-item-image']}\n loading=\"lazy\"\n src={imageSrc}\n />\n ) : (\n <div\n aria-label=\"Gift product image placeholder\"\n className={styles['rebuy-tiered-progress-bar__gift-item-image']}\n ></div>\n )}\n </div>\n <div className={styles['rebuy-tiered-progress-bar__gift-item-details']}>\n <h4 className={styles['rebuy-tiered-progress-bar__gift-item-title']} id={`tpb-gift-${tierId}-title`}>\n {title}\n </h4>\n {displayStatus === GiftStatus.ADDED && displayVariantTitle && (\n <div className={styles['rebuy-tiered-progress-bar__gift-item-variant-title']}>\n {displayVariantTitle}\n </div>\n )}\n <div className={styles['rebuy-tiered-progress-bar__gift-item-actions-wrapper']}>\n {isGloballySyncing && (\n <button className={clsx(styles['rebuy-tiered-progress-bar__gift-item-button'])} disabled>\n Updating...\n </button>\n )}\n {itemLevelError && !isGloballySyncing && (\n <div className={styles['rebuy-tiered-progress-bar__error-message']}>\n Error: {itemLevelError}\n </div>\n )}\n {!isGloballySyncing && !itemLevelError && (\n <>\n {displayStatus === GiftStatus.ADDED && (\n <button\n aria-label={`Remove ${title} gift`}\n className={clsx(\n styles['rebuy-tiered-progress-bar__gift-item-button'],\n styles['rebuy-tiered-progress-bar__gift-item-button--remove']\n )}\n disabled={isDisabled}\n onClick={handleRemoveClick}\n >\n Remove\n </button>\n )}\n {displayStatus === GiftStatus.NEEDS_SELECTION && (\n <select\n aria-label={`Select option for ${title}`}\n className={clsx(styles['rebuy-tiered-progress-bar__gift-item-select'])}\n disabled={isDisabled}\n onChange={handleVariantChange}\n value=\"\"\n >\n <option disabled value=\"\">\n Select Option\n </option>\n {availableChoices.map((variant) => {\n const variantLabel = getFreeVariantTitle(variant) || variant.title;\n\n return (\n <option key={variant.id} value={variant.id}>\n {variantLabel} ({formatMoney(variant.price.amount)})\n </option>\n );\n })}\n </select>\n )}\n {canReAdd && displayStatus === GiftStatus.DECLINED && (\n <button\n aria-label={`Re-add ${title} gift`}\n className={clsx(\n styles['rebuy-tiered-progress-bar__gift-item-button'],\n styles['rebuy-tiered-progress-bar__gift-item-button--add']\n )}\n disabled={isDisabled}\n onClick={handleReAddClick}\n >\n Re-Add Gift\n </button>\n )}\n {displayStatus === GiftStatus.UNAVAILABLE && !canReAdd && (\n <div className={styles['rebuy-tiered-progress-bar__gift-item-status-text']}>\n Unavailable\n </div>\n )}\n </>\n )}\n </div>\n </div>\n </div>\n );\n};\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/smart-cart/components/TieredProgressBar/TieredProgressBar.css\";\n const result = {\"rebuy-tiered-progress-bar\":\"TieredProgressBar_rebuy-tiered-progress-bar\",\"rebuy-tiered-progress-bar__main-progress-area\":\"TieredProgressBar_rebuy-tiered-progress-bar__main-progress-area\",\"rebuy-tiered-progress-bar__tier-markers-list\":\"TieredProgressBar_rebuy-tiered-progress-bar__tier-markers-list\",\"rebuy-tiered-progress-bar__track\":\"TieredProgressBar_rebuy-tiered-progress-bar__track\",\"rebuy-tiered-progress-bar__fill\":\"TieredProgressBar_rebuy-tiered-progress-bar__fill\",\"rebuy-tiered-progress-bar__tier-step\":\"TieredProgressBar_rebuy-tiered-progress-bar__tier-step\",\"rebuy-tiered-progress-bar__tier-icon-wrapper\":\"TieredProgressBar_rebuy-tiered-progress-bar__tier-icon-wrapper\",\"rebuy-tiered-progress-bar__tier-step--reached\":\"TieredProgressBar_rebuy-tiered-progress-bar__tier-step--reached\",\"rebuy-tiered-progress-bar__tier-icon-image\":\"TieredProgressBar_rebuy-tiered-progress-bar__tier-icon-image\",\"rebuy-tiered-progress-bar__tier-label\":\"TieredProgressBar_rebuy-tiered-progress-bar__tier-label\",\"rebuy-tiered-progress-bar__feedback-message\":\"TieredProgressBar_rebuy-tiered-progress-bar__feedback-message\",\"rebuy-tiered-progress-bar__gift-area\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-area\",\"rebuy-tiered-progress-bar__gift-area-title\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-area-title\",\"rebuy-tiered-progress-bar__gift-items-list\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-items-list\",\"rebuy-tiered-progress-bar__gift-item\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item\",\"rebuy-tiered-progress-bar__gift-item-image-wrapper\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item-image-wrapper\",\"rebuy-tiered-progress-bar__gift-item-image\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item-image\",\"rebuy-tiered-progress-bar__gift-item-details\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item-details\",\"rebuy-tiered-progress-bar__gift-item-title\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item-title\",\"rebuy-tiered-progress-bar__gift-item-variant-title\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item-variant-title\",\"rebuy-tiered-progress-bar__gift-item-status-text\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item-status-text\",\"rebuy-tiered-progress-bar__gift-item-actions-wrapper\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item-actions-wrapper\",\"rebuy-tiered-progress-bar__gift-item-button\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item-button\",\"rebuy-tiered-progress-bar__gift-item-button--remove\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item-button--remove\",\"rebuy-tiered-progress-bar__gift-item-button--add\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item-button--add\",\"rebuy-tiered-progress-bar__error-message\":\"TieredProgressBar_rebuy-tiered-progress-bar__error-message\",\"rebuy-tiered-progress-bar__gift-item--syncing\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item--syncing\",\"rebuy-tiered-progress-bar__gift-item-select\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item-select\"};\n export default result;\n ", "import type { CSSProperties } from 'react';\n\n/**\n * Centralized debug styles for Smart Cart components.\n * These styles are only applied when debug mode is active,\n * ensuring zero overhead for production users.\n */\n\n// Base colors and values\nconst debugColors = {\n background: 'rgba(0, 0, 0, 0.9)',\n border: '#666',\n error: '#f66',\n errorBg: 'rgba(255, 102, 102, 0.1)',\n primary: '#0084ff',\n secondary: '#666',\n success: '#0c6',\n text: '#fff',\n} as const;\n\n// Common style mixins\nconst buttonBase: CSSProperties = {\n border: '1px solid #666',\n borderRadius: '3px',\n cursor: 'pointer',\n fontSize: '13px',\n fontWeight: 'normal',\n padding: '6px 12px',\n};\n\n// Debug panel styles - core visual styles only\nexport const debugPanel: CSSProperties = {\n backgroundColor: debugColors.background,\n border: `1px solid ${debugColors.border}`,\n borderRadius: '3px',\n color: debugColors.text,\n fontSize: '12px',\n overflow: 'auto',\n padding: '12px',\n};\n\n// Toggle button styles - core visual styles only\nexport const toggleButton = (): CSSProperties => ({\n ...buttonBase,\n backgroundColor: debugColors.background,\n color: debugColors.text,\n});\n\n// Action button styles\nexport const actionButton = {\n primary: {\n ...buttonBase,\n backgroundColor: debugColors.primary,\n border: `1px solid ${debugColors.primary}`,\n color: 'white',\n },\n secondary: {\n ...buttonBase,\n backgroundColor: 'transparent',\n border: `1px solid ${debugColors.secondary}`,\n color: debugColors.text,\n },\n};\n\n// Status and message styles\nexport const errorMessage: CSSProperties = {\n backgroundColor: debugColors.errorBg,\n borderRadius: '3px',\n color: debugColors.error,\n fontSize: '12px',\n margin: '0 0 8px 0',\n padding: '6px',\n};\n\nexport const statusMessage: CSSProperties = {\n color: debugColors.success,\n fontSize: '12px',\n marginBottom: '6px',\n};\n\nexport const infoText: CSSProperties = {\n fontSize: '13px',\n marginBottom: '8px',\n};\n\nexport const codeBlock: CSSProperties = {\n backgroundColor: 'rgba(255, 255, 255, 0.1)',\n borderRadius: '3px',\n color: debugColors.text,\n fontFamily: 'monospace',\n fontSize: '11px',\n lineHeight: '1.4',\n padding: '6px',\n whiteSpace: 'pre-wrap',\n wordBreak: 'break-word',\n};\n\nexport const buttonGroup: CSSProperties = {\n display: 'flex',\n flexWrap: 'wrap',\n gap: '6px',\n marginBottom: '8px',\n};\n\n// Helper function to merge styles\nexport const mergeStyles = (...styles: (CSSProperties | undefined)[]): CSSProperties => {\n return Object.assign({}, ...styles.filter(Boolean));\n};\n\n// Type-safe style getter\nexport const getDebugStyle = <K extends keyof typeof debugStyles>(key: K): (typeof debugStyles)[K] => {\n return debugStyles[key];\n};\n\n// Export all styles as a single object for convenience\nexport const debugStyles = {\n actionButton,\n buttonGroup,\n codeBlock,\n colors: debugColors,\n errorMessage,\n infoText,\n panel: debugPanel,\n statusMessage,\n toggleButton,\n} as const;\n", "// ~/smart-cart/components/componentRegistry.ts\n\nimport type React from 'react';\nimport { AnnouncementBar } from '~/smart-cart/components/AnnouncementBar/AnnouncementBar';\nimport { CartItemList } from '~/smart-cart/components/CartItemList/CartItemList';\nimport { CartNoteInput } from '~/smart-cart/components/CartNoteInput/CartNoteInput';\nimport { CartSubtotal } from '~/smart-cart/components/CartSubtotal/CartSubtotal';\nimport { CartTitleBar } from '~/smart-cart/components/CartTitleBar/CartTitleBar';\nimport { CheckoutArea } from '~/smart-cart/components/CheckoutArea/CheckoutArea';\nimport { CrossSell } from '~/smart-cart/components/CrossSell/CrossSell';\nimport { CustomCodeBlock } from '~/smart-cart/components/CustomCode/CustomCodeBlock';\nimport { DiscountCodeInput } from '~/smart-cart/components/DiscountCodeInput/DiscountCodeInput';\nimport { LoginButton } from '~/smart-cart/components/LoginButton/LoginButton';\nimport { SmartCartApp } from '~/smart-cart/components/SmartCartApp/SmartCartApp';\nimport { TieredProgressBar } from '~/smart-cart/components/TieredProgressBar/TieredProgressBar';\nimport type { SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\n\nconst _StubComponent: React.FC<{\n componentConfig: SmartCartComponentConfig;\n}> = ({ componentConfig }) => (\n <div\n data-stub-anchor={componentConfig.anchor}\n data-stub-component-id={componentConfig.component_id}\n data-stub-component-type={componentConfig.type}\n style={{\n border: '1px dashed lightgrey',\n color: 'grey',\n fontSize: '12px',\n margin: '5px 0',\n padding: '10px',\n }}\n >\n Stub Component: <strong>{componentConfig.type}</strong> (ID: {componentConfig.component_id})\n <pre\n style={{\n background: '#f8f8f8',\n fontSize: '10px',\n maxHeight: '50px',\n overflow: 'auto',\n }}\n >\n {JSON.stringify(componentConfig.settings, null, 2)}\n </pre>\n </div>\n);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const componentRegistry: Record<string, React.FC<any>> = {\n // Use 'any' for props initially, refine later\n announcement_bar: AnnouncementBar,\n cart_items: CartItemList,\n cart_subtotal: CartSubtotal,\n checkout: CheckoutArea,\n cross_sell_widget: CrossSell,\n custom_code_block: CustomCodeBlock,\n discount_code: DiscountCodeInput,\n login: LoginButton,\n notes: CartNoteInput,\n smart_cart_app: SmartCartApp,\n tiered_progress_bar: TieredProgressBar,\n title_bar: CartTitleBar,\n // Add any other potential component types as stubs if needed\n};\n", "// ~/smart-cart/components/Layouts/DoubleColumnLayout.tsx\nimport clsx from 'clsx';\n\nimport { useRef } from 'react';\nimport { AnchorSlot } from '~/smart-cart/components/_Layouts/AnchorSlot';\nimport { useIsScrolled } from '~/smart-cart/hooks/useIsScrolled';\nimport type { SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\n\n/* eslint-disable-next-line no-restricted-imports */\nimport styles from './LayoutStyles.module.css';\n\ntype DoubleColumnLayoutProps = {\n components: SmartCartComponentConfig[];\n itemCount: number;\n layout: 'double' | 'double-right';\n};\n\nexport const DoubleColumnLayout: React.FC<DoubleColumnLayoutProps> = ({ components, itemCount, layout }) => {\n const scrollAreaRef = useRef<HTMLDivElement>(null);\n const isScrolled = useIsScrolled(scrollAreaRef);\n\n const layoutClass =\n layout === 'double-right'\n ? styles['rebuy-smart-cart-layout__flyout-inner--double-right']\n : styles['rebuy-smart-cart-layout__flyout-inner--double'];\n\n return (\n <div className={clsx(styles['rebuy-smart-cart-layout__flyout-inner'], layoutClass)}>\n <div className={styles['rebuy-smart-cart-layout__column--primary']}>\n <div className={styles['rebuy-smart-cart-layout__anchor-goal-box']} data-rebuy-cart-anchor=\"goalBox\">\n <AnchorSlot anchor=\"goalBox\" components={components} />\n </div>\n <div\n className={clsx(\n styles['rebuy-smart-cart-layout__scroll-area'],\n isScrolled && styles['rebuy-smart-cart-layout__scroll-area--is-scrolled']\n )}\n data-rebuy-cart-scroll-area\n ref={scrollAreaRef}\n >\n <div className={styles['rebuy-smart-cart-layout__anchor-body']} data-rebuy-cart-anchor=\"body\">\n <AnchorSlot anchor=\"body\" components={components} />\n </div>\n </div>\n <div\n className={clsx(styles['rebuy-smart-cart-layout__anchor-footer'], {\n [styles['rebuy-smart-cart-layout__anchor-footer--hidden']]: itemCount === 0,\n })}\n data-rebuy-cart-anchor=\"footer\"\n >\n <AnchorSlot anchor=\"footer\" components={components} />\n </div>\n </div>\n <div className={styles['rebuy-smart-cart-layout__column--secondary']}>\n <div\n className={styles['rebuy-smart-cart-layout__anchor-cross-sells']}\n data-rebuy-cart-anchor=\"crossSells\"\n >\n <AnchorSlot anchor=\"crossSells\" components={components} />\n </div>\n </div>\n </div>\n );\n};\n", "import { useEffect, useState, type RefObject } from 'react';\n\n/**\n * Custom hook to detect if a scrollable element has been scrolled down\n *\n * @param {RefObject<HTMLElement>} scrollElementRef - Ref to the scrollable element\n * @returns {boolean} - boolean indicating if the element has been scrolled (scrollTop > 0)\n *\n * @example\n * const scrollElementRef = useRef<HTMLDivElement>(null);\n * const isScrolled = useIsScrolled(scrollElementRef);\n *\n * return <div ref={scrollElementRef}>{isScrolled ? 'Scrolled' : 'Not scrolled'}</div>;\n */\nexport const useIsScrolled = (scrollElementRef: React.RefObject<HTMLElement>) => {\n const [isScrolled, setIsScrolled] = useState(false);\n\n useEffect(() => {\n const scrollElement = scrollElementRef.current;\n\n if (!scrollElement) return;\n\n const handleScroll = () => {\n setIsScrolled(scrollElement.scrollTop > 0);\n };\n\n // Initial check\n handleScroll();\n\n // Listen for scroll events on the scroll element\n scrollElement.addEventListener('scroll', handleScroll, { passive: true });\n\n return () => {\n scrollElement.removeEventListener('scroll', handleScroll);\n };\n }, [scrollElementRef]);\n\n return isScrolled;\n};\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/smart-cart/components/_Layouts/LayoutStyles.css\";\n const result = {\"rebuy-smart-cart-layout__anchor-goal-box\":\"LayoutStyles_rebuy-smart-cart-layout__anchor-goal-box\",\"rebuy-smart-cart-layout__scroll-area\":\"LayoutStyles_rebuy-smart-cart-layout__scroll-area\",\"rebuy-smart-cart-layout__scroll-area--is-scrolled\":\"LayoutStyles_rebuy-smart-cart-layout__scroll-area--is-scrolled\",\"rebuy-smart-cart-layout__anchor-body\":\"LayoutStyles_rebuy-smart-cart-layout__anchor-body\",\"rebuy-smart-cart-layout__anchor-footer\":\"LayoutStyles_rebuy-smart-cart-layout__anchor-footer\",\"rebuy-smart-cart-layout__anchor-footer--hidden\":\"LayoutStyles_rebuy-smart-cart-layout__anchor-footer--hidden\",\"rebuy-smart-cart-layout__anchor-cross-sells\":\"LayoutStyles_rebuy-smart-cart-layout__anchor-cross-sells\",\"rebuy-smart-cart-layout__flyout-inner\":\"LayoutStyles_rebuy-smart-cart-layout__flyout-inner\",\"rebuy-smart-cart-layout__flyout-inner--double\":\"LayoutStyles_rebuy-smart-cart-layout__flyout-inner--double\",\"rebuy-smart-cart-layout__flyout-inner--double-right\":\"LayoutStyles_rebuy-smart-cart-layout__flyout-inner--double-right\",\"rebuy-smart-cart-layout__column--primary\":\"LayoutStyles_rebuy-smart-cart-layout__column--primary\",\"rebuy-smart-cart-layout__column--secondary\":\"LayoutStyles_rebuy-smart-cart-layout__column--secondary\"};\n export default result;\n ", "// ~/smart-cart/components/Layouts/SingleColumnLayout.tsx\nimport clsx from 'clsx';\nimport { useRef } from 'react';\nimport { AnchorSlot } from '~/smart-cart/components/_Layouts/AnchorSlot';\nimport { useIsScrolled } from '~/smart-cart/hooks/useIsScrolled';\nimport type { SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\n\n/* eslint-disable-next-line no-restricted-imports */\nimport styles from './LayoutStyles.module.css';\n\ntype SingleColumnLayoutProps = {\n components: SmartCartComponentConfig[];\n itemCount: number;\n};\n\nexport const SingleColumnLayout: React.FC<SingleColumnLayoutProps> = ({ components, itemCount }) => {\n const scrollAreaRef = useRef<HTMLDivElement>(null);\n const isScrolled = useIsScrolled(scrollAreaRef);\n\n return (\n <>\n <div className={styles['rebuy-smart-cart-layout__anchor-goal-box']} data-rebuy-cart-anchor=\"goalBox\">\n <AnchorSlot anchor=\"goalBox\" components={components} />\n </div>\n <div\n className={clsx(\n styles['rebuy-smart-cart-layout__scroll-area'],\n isScrolled && styles['rebuy-smart-cart-layout__scroll-area--is-scrolled']\n )}\n data-rebuy-cart-scroll-area\n ref={scrollAreaRef}\n >\n <div className={styles['rebuy-smart-cart-layout__anchor-body']} data-rebuy-cart-anchor=\"body\">\n <AnchorSlot anchor=\"body\" components={components} />\n </div>\n </div>\n <div\n className={clsx(styles['rebuy-smart-cart-layout__anchor-footer'], {\n [styles['rebuy-smart-cart-layout__anchor-footer--hidden']]: itemCount === 0,\n })}\n data-rebuy-cart-anchor=\"footer\"\n >\n <AnchorSlot anchor=\"footer\" components={components} />\n </div>\n </>\n );\n};\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/smart-cart/components/SmartCartContainer/SmartCartContainer.css\";\n const result = {\"rebuy-smart-cart\":\"SmartCartContainer_rebuy-smart-cart\",\"rebuy-smart-cart__overlay-background\":\"SmartCartContainer_rebuy-smart-cart__overlay-background\",\"rebuy-smart-cart__overlay-background--visible\":\"SmartCartContainer_rebuy-smart-cart__overlay-background--visible\",\"rebuy-smart-cart--visible\":\"SmartCartContainer_rebuy-smart-cart--visible\",\"rebuy-smart-cart--layout-double\":\"SmartCartContainer_rebuy-smart-cart--layout-double\",\"rebuy-smart-cart__header\":\"SmartCartContainer_rebuy-smart-cart__header\",\"rebuy-smart-cart__header-top-bar\":\"SmartCartContainer_rebuy-smart-cart__header-top-bar\",\"rebuy-smart-cart__header-content\":\"SmartCartContainer_rebuy-smart-cart__header-content\",\"rebuy-smart-cart__close-button\":\"SmartCartContainer_rebuy-smart-cart__close-button\"};\n export default result;\n ", "import type React from 'react';\nimport { SmartCartContainer } from '~/smart-cart/components/SmartCartContainer/SmartCartContainer';\n\n/**\n * RebuySmartCart component\n *\n * This component renders the Smart Cart UI.\n * It assumes that SmartCartProvider is already rendered higher up in the component tree\n * by RebuyHydrogenReactContextProvider.\n */\nexport const RebuySmartCart: React.FC = () => {\n // TODO: Update this to use an optional component that can be added to pre-existing <Aside> components (ie. no backdrop overlay, etc.)\n return <SmartCartContainer />;\n};\n", "import { RebuyClient } from '@rebuy/rebuy';\nimport * as Utilities from '@rebuy/rebuy/utilities';\nimport { flattenConnection } from '@shopify/hydrogen';\nimport { type ComponentType, useContext, useEffect, useMemo, useState } from 'react';\n\nimport { useRebuyConfig } from '~/context/RebuyConfigContext';\nimport { RebuyContext } from '~/context/RebuyContext';\nimport { RebuyWidgetProvider } from '~/context/RebuyWidgetContext';\nimport type {\n RebuyProduct,\n RebuyProductVariant,\n RebuyWidgetContainerProps,\n RebuyWidgetMetadata,\n} from '~/types/rebuyCustom';\nimport type { HydrogenProduct } from '~/types/shopify';\nimport { filterContextForWidgetEndpoints } from '~/utils/filterContextUtils';\n\ntype RebuyWidgetContainerComponent = {\n (props: RebuyWidgetContainerProps): JSX.Element;\n} & ComponentType<RebuyWidgetContainerProps>;\n\nconst RebuyWidgetContainerBase = ({ children, ...props }: RebuyWidgetContainerProps) => {\n const { collection, collectionId, dataSource, limit, options, product, productId, variant, variantId } = props;\n\n const { apiKey, loadingStatus: configLoadingStatus, rebuyConfig } = useRebuyConfig();\n const rebuyContext = useContext(RebuyContext);\n\n const [rebuyApiClient, setRebuyApiClient] = useState<RebuyClient | null>(null);\n const [initialized, setInitialized] = useState(false);\n const shopifyProductId = product?.id ?? productId ?? null;\n const shopifyVariantId = variant?.id ?? variantId ?? null;\n const shopifyCollectionId = collection?.id ?? collectionId ?? null;\n const [products, setProducts] = useState<RebuyProduct[]>([]);\n const [metadata, setMetadata] = useState<RebuyWidgetMetadata>();\n\n // Initialize Rebuy API client\n useEffect(() => {\n if (!rebuyApiClient && apiKey && configLoadingStatus === 'success') {\n const client = new RebuyClient(apiKey);\n const currentEndpoint = dataSource || '/api/v1/products/recommended';\n\n if (rebuyContext?.contextParameters) {\n const filteredParams = filterContextForWidgetEndpoints(rebuyContext.contextParameters, currentEndpoint);\n client.setContextParameters(filteredParams as Record<string, unknown>);\n }\n\n if (options) {\n client.setDefaultParameters(options as Record<string, unknown>);\n }\n\n setRebuyApiClient(client);\n setInitialized(true);\n }\n }, [apiKey, rebuyApiClient, configLoadingStatus, options, rebuyContext, dataSource]);\n\n // Update context parameters if they change\n useEffect(() => {\n if (rebuyApiClient && rebuyContext?.contextParameters) {\n const currentEndpoint = dataSource || '/api/v1/products/recommended';\n const filteredParams = filterContextForWidgetEndpoints(rebuyContext.contextParameters, currentEndpoint);\n rebuyApiClient.setContextParameters(filteredParams as Record<string, unknown>);\n }\n }, [rebuyApiClient, rebuyContext, dataSource]);\n\n // Memoize request object on prop changes (e.g. product)\n const request = useMemo(() => {\n const req = {\n endpoint: dataSource || '/api/v1/products/recommended',\n params: {} as Record<string, string | number>, // Keeping this object generic to allow for custom endpoints\n };\n\n if (shopifyProductId) {\n req.params.shopify_product_ids = Utilities.getIdFromGraphUrl(shopifyProductId, 'Product') ?? '';\n }\n\n if (shopifyVariantId) {\n req.params.shopify_variant_ids = Utilities.getIdFromGraphUrl(shopifyVariantId, 'ProductVariant') ?? '';\n }\n\n if (shopifyCollectionId) {\n req.params.shopify_collection_ids = Utilities.getIdFromGraphUrl(shopifyCollectionId, 'Collection') ?? '';\n }\n\n if (limit) {\n req.params.limit = limit;\n }\n\n return req;\n }, [dataSource, shopifyProductId, shopifyVariantId, shopifyCollectionId, limit]);\n\n // Update product recommendations on cart or request change\n useEffect(() => {\n let isMounted = true;\n\n if (!rebuyApiClient || !initialized || configLoadingStatus !== 'success') return;\n\n const fetchData = async () => {\n try {\n const { data, metadata } = (await rebuyApiClient.getStorefrontData(\n request.endpoint,\n request.params\n )) as {\n data: RebuyProduct[];\n metadata: RebuyWidgetMetadata;\n };\n\n if (isMounted) {\n setProducts(\n Array.isArray(data)\n ? data.map((p) => ({\n ...p,\n variants: {\n nodes: p.variants ? flattenConnection(p.variants) : [],\n },\n }))\n : []\n );\n setMetadata(metadata);\n }\n } catch (error) {\n console.error('[RebuyWidgetContainer] Error fetching widget data:', error);\n\n if (isMounted) {\n setProducts([]);\n setMetadata(undefined);\n }\n }\n };\n\n fetchData();\n\n return () => {\n isMounted = false;\n };\n }, [rebuyApiClient, initialized, request, configLoadingStatus]);\n\n if (configLoadingStatus !== 'success' || !rebuyApiClient) {\n return null;\n }\n\n return (\n <RebuyWidgetProvider\n value={{\n apiKey: apiKey ?? undefined,\n cacheKey: rebuyConfig?.shop?.cache_key,\n dataSource: dataSource || '/api/v1/products/recommended',\n isHydrogenReact: rebuyContext?.contextParameters?.isHydrogenReact || false,\n key: product?.id || '',\n limit: limit || 0,\n metadata: metadata || ({} as RebuyWidgetMetadata),\n options: (options || {}) as Record<string, unknown>,\n product: product as HydrogenProduct | undefined,\n productId,\n products,\n variant: variant as RebuyProductVariant | undefined,\n variantId,\n }}\n >\n {children}\n </RebuyWidgetProvider>\n );\n};\n\nexport const RebuyWidgetContainer = RebuyWidgetContainerBase as RebuyWidgetContainerComponent;\n", "import { createContext, useContext } from 'react';\nimport type { RebuyWidgetMetadata } from '~/types/rebuyCustom';\nimport type { RebuyWidgetContextType } from '~/types/widgets';\n\nconst RebuyWidgetContext = createContext<RebuyWidgetContextType>({\n dataSource: '',\n isHydrogenReact: false,\n key: '',\n limit: 0,\n metadata: {} as RebuyWidgetMetadata,\n options: {},\n products: [],\n variant: undefined,\n variantId: undefined,\n});\n\nexport const useRebuyWidget = () => useContext(RebuyWidgetContext);\n\nexport const RebuyWidgetProvider: React.FC<{\n children: React.ReactNode;\n value: RebuyWidgetContextType;\n}> = ({ children, value }) => {\n return <RebuyWidgetContext.Provider value={value}>{children}</RebuyWidgetContext.Provider>;\n};\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/widgets/RebuyCompleteTheLook/RebuyCompleteTheLook.css\";\n const result = {\"container\":\"RebuyCompleteTheLook_container\",\"productGrid\":\"RebuyCompleteTheLook_productGrid\",\"productItem\":\"RebuyCompleteTheLook_productItem\"};\n export default result;\n ", "import { ProductCard } from '~/components/ProductCard';\nimport { Title } from '~/components/Title';\nimport { DebugKey } from '~/constants/debug';\nimport { useRebuyWidget } from '~/context/RebuyWidgetContext';\nimport { getTitleLevel } from '~/hooks/titleLevel';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport type { RebuyCompleteTheLookProps } from './types';\n\nimport styles from './RebuyCompleteTheLook.module.css';\n\n// Component implementation\nexport const RebuyCompleteTheLook = (props: RebuyCompleteTheLookProps) => {\n const {\n addToCartBtnText = 'Add to cart',\n addToCartCallback,\n customTitle = `These pair with {product_title}`,\n customTitleLevel = 'h2',\n customTitleStyle,\n } = props;\n\n const { isHydrogenReact, product, products } = useRebuyWidget();\n\n const productTitle = customTitle.replace('{product_title}', product?.title ?? '');\n\n if (products.length === 0) {\n rebuyDebugLog.log(DebugKey.WIDGET_COMPLETE_THE_LOOK, 'RebuyCompleteTheLook: No products found');\n\n return null;\n }\n\n return (\n <section className={styles.container}>\n <Title level={getTitleLevel(customTitleLevel)} style={customTitleStyle} text={productTitle} />\n <ul className={styles.productGrid}>\n {products.map((product) => (\n <li className={styles.productItem} key={product.id}>\n <ProductCard\n addToCartBtnText={addToCartBtnText}\n addToCartCallback={addToCartCallback}\n isHydrogenReact={isHydrogenReact}\n product={product}\n productCardTitleLevel={getTitleLevel(customTitleLevel, true)}\n />\n </li>\n ))}\n </ul>\n </section>\n );\n};\n", "import { useCallback, useEffect, useState } from 'react';\n\nimport { AddToCartBtn } from '~/components/AddToCartBtn';\nimport { Title } from '~/components/Title';\nimport { DebugKey } from '~/constants/debug';\nimport { useRebuyWidget } from '~/context/RebuyWidgetContext';\nimport { getTitleLevel } from '~/hooks/titleLevel';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport { convertToRebuyProduct } from '~/utils/convertToRebuyProduct';\nimport type { BundleProduct, RebuyDynamicBundleProductsProps } from '~/widgets/RebuyDynamicBundleProducts/types';\nimport { BundleImages } from './BundleImages';\nimport { BundlePrice } from './BundlePrice';\nimport { BundleSelection } from './BundleSelection';\nimport styles from './RebuyDynamicBundleProducts.module.css';\n\nexport const RebuyDynamicBundleProducts = (props: RebuyDynamicBundleProductsProps) => {\n const {\n addToCartBtnText = 'Add to cart',\n addToCartCallback,\n customTitle = `These pair with {product_title}`,\n customTitleLevel = 'h2',\n customTitleStyle,\n } = props;\n\n const { isHydrogenReact, product, products } = useRebuyWidget();\n\n const productTitle = customTitle.replace('{product_title}', product?.title ?? '');\n\n const [bundleProducts, setBundleProducts] = useState<BundleProduct[]>([]);\n\n // Initializiation\n useEffect(() => {\n const mainProduct: BundleProduct = convertToRebuyProduct(isHydrogenReact || false, product);\n\n const formattedProducts = products.map((product) => {\n return {\n ...product,\n selected: true,\n selectedVariant: product.variants.nodes[0],\n };\n });\n\n setBundleProducts([mainProduct, ...formattedProducts]);\n }, [product, products, isHydrogenReact]);\n\n const onToggleBundleItem = useCallback(\n (product: BundleProduct) => {\n product.selected = !product.selected;\n\n setBundleProducts([...bundleProducts]);\n },\n [bundleProducts]\n );\n\n const onSelectVariant = useCallback(\n (product: BundleProduct, variant_id: string) => {\n const variant = product.variants.nodes.find(({ id }) => id === variant_id);\n\n if (variant) {\n product.selectedVariant = variant;\n product.selected = variant.availableForSale || false;\n\n setBundleProducts([...bundleProducts]);\n }\n },\n [bundleProducts]\n );\n\n if (products.length === 0) {\n rebuyDebugLog.log(DebugKey.WIDGET_DYNAMIC_BUNDLE_PRODUCTS, 'RebuyDynamicBundleProducts: No products found');\n\n return null;\n }\n\n return (\n <section className={styles.container}>\n <Title level={getTitleLevel(customTitleLevel)} style={customTitleStyle} text={productTitle} />\n <div className={styles.bundleContainer}>\n <BundleImages products={bundleProducts} />\n <BundlePrice products={bundleProducts} />\n\n <div className={styles.addCartBtnContainer}>\n <AddToCartBtn\n addToCartBtnText={addToCartBtnText}\n addToCartCallback={addToCartCallback}\n disabled={bundleProducts.filter((product) => product.selected).length === 0}\n isHydrogenReact={isHydrogenReact}\n selectedVariants={bundleProducts\n .filter((product) => product.selected)\n .map((product) => {\n return product.selectedVariant;\n })}\n />\n </div>\n\n <BundleSelection\n onSelectVariant={onSelectVariant}\n onToggleBundleItem={onToggleBundleItem}\n products={bundleProducts}\n />\n </div>\n </section>\n );\n};\n", "import type { RebuyProductVariant } from '~/types/rebuyCustom';\nimport type { HydrogenProduct } from '~/types/shopify';\n\nexport const convertToRebuyProduct = (isHydrogenReact: boolean, product?: HydrogenProduct) => {\n const mainProductVariants: RebuyProductVariant[] = isHydrogenReact\n ? product?.variants?.nodes?.map((variant) => ({\n availableForSale: variant.availableForSale,\n compareAtPriceV2: {\n amount: variant.compareAtPrice?.amount || '',\n currencyCode: variant.compareAtPrice?.currencyCode || 'USD',\n },\n id: variant.id,\n image: variant.image\n ? {\n altText: variant.image.altText || null,\n height: variant.image.height || 100,\n id: variant.image.id || '',\n url: variant.image.url || '',\n width: variant.image.width || 100,\n }\n : undefined,\n priceV2: {\n amount: variant.price.amount,\n currencyCode: variant.price.currencyCode,\n },\n product: {\n handle: product.handle,\n id: product.id,\n title: product.title,\n vendor: product.vendor,\n },\n selectedOptions: variant.selectedOptions,\n sku: variant.sku || '',\n title: variant.title,\n })) || []\n : product?.adjacentVariants.map((variant) => {\n return {\n availableForSale: variant.availableForSale,\n compareAtPriceV2: {\n amount: variant.compareAtPrice?.amount || '',\n currencyCode: variant.compareAtPrice?.currencyCode || 'USD',\n },\n id: variant.id,\n image: {\n altText: variant.image?.altText || '',\n height: variant.image?.height || 100,\n id: variant.image?.id || '',\n url: variant.image?.url || '',\n width: variant.image?.width || 100,\n },\n priceV2: {\n amount: variant.price.amount || '',\n currencyCode: variant.price.currencyCode || 'USD',\n },\n product: {\n handle: product.handle,\n id: product.id,\n title: product.title,\n vendor: product.vendor,\n },\n selectedOptions: variant.selectedOptions,\n sku: variant.sku || '',\n title: variant.title || '',\n };\n }) || [];\n\n return isHydrogenReact\n ? {\n collections: {\n nodes:\n product?.collections.nodes.map((collection) => {\n return {\n handle: collection.handle,\n };\n }) || [],\n },\n compareAtPriceRange: {\n maxVariantCompareAtPrice: null,\n minVariantCompareAtPrice: null,\n },\n description: product?.description || '',\n descriptionHtml: product?.descriptionHtml || '',\n featuredImage: {\n altText: product?.featuredImage?.altText || '',\n height: product?.featuredImage?.height || 100,\n id: product?.featuredImage?.id || '',\n url: product?.featuredImage?.url || '',\n width: product?.featuredImage?.width || 100,\n },\n handle: product?.handle || '',\n id: product?.id || '',\n images: [{ altText: '', height: 100, id: '', url: '', width: 100 }],\n media: [],\n metafields: [],\n options: [],\n priceRange: product?.priceRange || {\n maxVariantPrice: { amount: '0', currencyCode: 'USD' },\n minVariantPrice: { amount: '0', currencyCode: 'USD' },\n },\n selected: true,\n selectedOptions:\n product?.selectedVariant?.selectedOptions?.reduce((acc, option) => {\n return { ...acc, [option.name]: option.value };\n }, {}) ||\n product?.variants?.nodes[0]?.selectedOptions?.reduce((acc, option) => {\n return { ...acc, [option.name]: option.value };\n }, {}) ||\n {},\n selectedSellingPlan: {},\n selectedSellingPlanAllocation: {},\n selectedVariant: {\n availableForSale:\n product?.selectedVariant?.availableForSale ||\n product?.variants?.nodes[0]?.availableForSale ||\n false,\n compareAtPriceV2: {\n amount:\n product?.selectedVariant?.compareAtPrice?.amount ||\n product?.variants?.nodes[0]?.compareAtPrice?.amount ||\n '',\n currencyCode:\n product?.selectedVariant?.compareAtPrice?.currencyCode ||\n product?.variants?.nodes[0]?.compareAtPrice?.currencyCode ||\n 'USD',\n },\n id: product?.selectedVariant?.id || '',\n image: {\n altText:\n product?.selectedVariant?.image?.altText || product?.variants?.nodes[0]?.image?.altText || '',\n height:\n product?.selectedVariant?.image?.height || product?.variants?.nodes[0]?.image?.height || 100,\n id: product?.selectedVariant?.image?.id || product?.variants?.nodes[0]?.image?.id || '',\n url: product?.selectedVariant?.image?.url || product?.variants?.nodes[0]?.image?.url || '',\n width: product?.selectedVariant?.image?.width || product?.variants?.nodes[0]?.image?.width || 100,\n },\n priceV2: {\n amount: product?.selectedVariant?.price.amount || product?.variants?.nodes[0]?.price.amount || '',\n currencyCode:\n product?.selectedVariant?.price.currencyCode ||\n product?.variants?.nodes[0]?.price.currencyCode ||\n 'USD',\n },\n product: {\n handle: product?.handle || '',\n id: product?.id || '',\n title: product?.title || '',\n vendor: product?.vendor || '',\n },\n selectedOptions:\n product?.selectedVariant?.selectedOptions || product?.variants?.nodes[0]?.selectedOptions || [],\n sku: product?.selectedVariant?.sku || product?.variants?.nodes[0]?.sku || '',\n title: product?.selectedVariant?.title || product?.variants?.nodes[0]?.title || '',\n },\n sellingPlanGroups: [],\n seo: {\n description: product?.seo?.description || '',\n title: product?.seo?.title || '',\n },\n title: product?.title || '',\n variants: {\n nodes: mainProductVariants,\n },\n vendor: product?.vendor || '',\n }\n : {\n collections: {\n nodes: [],\n },\n compareAtPriceRange: {\n maxVariantCompareAtPrice: null,\n minVariantCompareAtPrice: null,\n },\n description: product?.description || '',\n descriptionHtml: product?.descriptionHtml || '',\n featuredImage: {\n altText: product?.selectedOrFirstAvailableVariant?.image?.altText || '',\n height: product?.selectedOrFirstAvailableVariant?.image?.height || 100,\n id: product?.selectedOrFirstAvailableVariant?.image?.id || '',\n url: product?.selectedOrFirstAvailableVariant?.image?.url || '',\n width: product?.selectedOrFirstAvailableVariant?.image?.width || 100,\n },\n handle: product?.handle || '',\n id: product?.id || '',\n images: [\n {\n altText: product?.selectedOrFirstAvailableVariant?.image?.altText || '',\n height: product?.selectedOrFirstAvailableVariant?.image?.height || 100,\n id: product?.selectedOrFirstAvailableVariant?.image?.id || '',\n url: product?.selectedOrFirstAvailableVariant?.image?.url || '',\n width: product?.selectedOrFirstAvailableVariant?.image?.width || 100,\n },\n ],\n media: [],\n metafields: [],\n options: [],\n priceRange: product?.priceRange || {\n maxVariantPrice: { amount: '0', currencyCode: 'USD' },\n minVariantPrice: { amount: '0', currencyCode: 'USD' },\n },\n selected: true,\n selectedOptions:\n product?.selectedOrFirstAvailableVariant?.selectedOptions?.reduce((acc, option) => {\n return { ...acc, [option.name]: option.value };\n }, {}) || {},\n selectedSellingPlan: {},\n selectedSellingPlanAllocation: {},\n selectedVariant: {\n availableForSale: product?.selectedOrFirstAvailableVariant?.availableForSale || false,\n compareAtPriceV2: {\n amount: product?.selectedOrFirstAvailableVariant?.compareAtPrice?.amount || '',\n currencyCode: product?.selectedOrFirstAvailableVariant?.compareAtPrice?.currencyCode || 'USD',\n },\n id: product?.selectedOrFirstAvailableVariant?.id || '',\n image: {\n altText: product?.selectedOrFirstAvailableVariant?.image?.altText || '',\n height: product?.selectedOrFirstAvailableVariant?.image?.height || 100,\n id: product?.selectedOrFirstAvailableVariant?.image?.id || '',\n url: product?.selectedOrFirstAvailableVariant?.image?.url || '',\n width: product?.selectedOrFirstAvailableVariant?.image?.width || 100,\n },\n priceV2: {\n amount: product?.selectedOrFirstAvailableVariant?.price.amount || '',\n currencyCode: product?.selectedOrFirstAvailableVariant?.price.currencyCode || 'USD',\n },\n product: {\n handle: product?.handle || '',\n id: product?.id || '',\n title: product?.title || '',\n vendor: product?.vendor || '',\n },\n selectedOptions: product?.selectedOrFirstAvailableVariant?.selectedOptions || [],\n sku: product?.selectedOrFirstAvailableVariant?.sku || '',\n title: product?.selectedOrFirstAvailableVariant?.title || '',\n },\n sellingPlanGroups: [],\n seo: {\n description: null,\n title: null,\n },\n title: product?.title || '',\n variants: {\n nodes: [\n {\n availableForSale: product?.selectedOrFirstAvailableVariant?.availableForSale || false,\n compareAtPriceV2: {\n amount: product?.selectedOrFirstAvailableVariant?.compareAtPrice?.amount || '',\n currencyCode:\n product?.selectedOrFirstAvailableVariant?.compareAtPrice?.currencyCode || 'USD',\n },\n id: product?.selectedOrFirstAvailableVariant?.id || '',\n image: {\n altText: product?.selectedOrFirstAvailableVariant?.image?.altText || '',\n height: product?.selectedOrFirstAvailableVariant?.image?.height || 100,\n id: product?.selectedOrFirstAvailableVariant?.image?.id || '',\n url: product?.selectedOrFirstAvailableVariant?.image?.url || '',\n width: product?.selectedOrFirstAvailableVariant?.image?.width || 100,\n },\n priceV2: {\n amount: product?.selectedOrFirstAvailableVariant?.price.amount || '',\n currencyCode: product?.selectedOrFirstAvailableVariant?.price.currencyCode || 'USD',\n },\n product: {\n handle: product?.handle || '',\n id: product?.id || '',\n title: product?.title || '',\n vendor: product?.vendor || '',\n },\n selectedOptions: product?.selectedOrFirstAvailableVariant?.selectedOptions || [],\n sku: product?.selectedOrFirstAvailableVariant?.sku || '',\n title: product?.selectedOrFirstAvailableVariant?.title || '',\n },\n ...mainProductVariants,\n ],\n },\n vendor: product?.vendor || '',\n };\n};\n", "import { Image } from '@shopify/hydrogen';\nimport { Fragment } from 'react';\nimport { RebuyLink } from '~/components/RebuyLink';\n\nimport type { BundleProduct } from '~/widgets/RebuyDynamicBundleProducts/types';\n\nimport styles from './RebuyDynamicBundleProducts.module.css';\n\nexport const BundleImages = ({ products }: { products: BundleProduct[] }) => {\n const selected = products.filter((product) => product.selected);\n\n return (\n <ul className={styles.bundleImages}>\n {products.map((product, index) => {\n const image = product.selectedVariant?.image;\n const productImage = image ? (\n <Image\n alt={image.altText || `Picture of ${product.title}`}\n className={styles.bundleImage}\n data={image}\n height={80}\n title={product.title}\n width={80}\n />\n ) : (\n // No image defined\n product.title\n );\n // Hide delimiter for first selected item\n const showDelimiter = selected[0]?.id !== product.id;\n\n return (\n <Fragment key={product.id + '-BundleImages-' + index}>\n {product.selected && (\n <>\n {showDelimiter && (\n <li className={styles.bundleImageDelimiter}>\n <span>+</span>\n </li>\n )}\n <li className=\"flex items-center\">\n {product.default ? (\n // Already on product page\n productImage\n ) : (\n // Link to product\n <RebuyLink\n ariaLabel={`View ${product.title}`}\n handle={`/products/${product.handle}`}\n >\n {productImage}\n </RebuyLink>\n )}\n </li>\n </>\n )}\n </Fragment>\n );\n })}\n </ul>\n );\n};\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/widgets/RebuyDynamicBundleProducts/RebuyDynamicBundleProducts.css\";\n const result = {\"container\":\"RebuyDynamicBundleProducts_container\",\"addCartBtnContainer\":\"RebuyDynamicBundleProducts_addCartBtnContainer\",\"bundleContainer\":\"RebuyDynamicBundleProducts_bundleContainer\",\"select\":\"RebuyDynamicBundleProducts_select\",\"bundleItemRowContainer\":\"RebuyDynamicBundleProducts_bundleItemRowContainer\",\"unselected\":\"RebuyDynamicBundleProducts_unselected\",\"bundleItemRow\":\"RebuyDynamicBundleProducts_bundleItemRow\",\"bundleItemInput\":\"RebuyDynamicBundleProducts_bundleItemInput\",\"bundleItemLabel\":\"RebuyDynamicBundleProducts_bundleItemLabel\",\"bundleImages\":\"RebuyDynamicBundleProducts_bundleImages\",\"bundleImage\":\"RebuyDynamicBundleProducts_bundleImage\",\"bundleImageDelimiter\":\"RebuyDynamicBundleProducts_bundleImageDelimiter\",\"compareAtPrice\":\"RebuyDynamicBundleProducts_compareAtPrice\"};\n export default result;\n ", "import { Money } from '@shopify/hydrogen';\n\nimport type { CurrencyCode, MoneyV2 } from '@shopify/hydrogen-react/storefront-api-types';\nimport type { BundleProduct } from '~/widgets/RebuyDynamicBundleProducts/types';\nimport styles from './RebuyDynamicBundleProducts.module.css';\n\nexport const BundlePrice = ({ products }: { products: BundleProduct[] }) => {\n const isDisabled = products.filter((product) => product.selected).length < 1;\n\n const totalBundlePrice = () => {\n let total = 0;\n let currencyCode = 'USD' as CurrencyCode;\n\n for (const product of products) {\n if (product.selected && product.selectedVariant) {\n const { priceV2: price } = product.selectedVariant;\n\n total += Number(price?.amount);\n currencyCode = (price?.currencyCode || 'USD') as CurrencyCode;\n }\n }\n\n return {\n amount: String(total),\n currencyCode,\n };\n };\n\n const totalBundleCompareAtPrice = () => {\n let compareAtTotal = 0;\n let currencyCode = 'USD' as CurrencyCode;\n\n for (const product of products) {\n if (product.selected && product.selectedVariant) {\n const { compareAtPriceV2: compareAtPrice, priceV2: price } = product.selectedVariant;\n\n currencyCode = (price?.currencyCode || 'USD') as CurrencyCode;\n compareAtTotal += Number((compareAtPrice || price)?.amount);\n }\n }\n\n return {\n amount: String(compareAtTotal),\n currencyCode,\n };\n };\n const isDiscounted = (\n price: { amount: string; currencyCode: string } | null,\n compareAtPrice: { amount: string; currencyCode: string } | null\n ) => Number(compareAtPrice?.amount) > Number(price?.amount);\n\n const price = totalBundlePrice();\n const compareAtPrice = totalBundleCompareAtPrice();\n\n const CompareAtPrice = ({ data: compareAtPrice }: { data: MoneyV2 | null }) => {\n return (\n compareAtPrice && (\n <Money as=\"span\" className={styles.compareAtPrice} data={compareAtPrice} withoutTrailingZeros />\n )\n );\n };\n\n return (\n products.length > 0 && (\n <div className=\"flex items-center flex-col\">\n {!isDisabled && (\n <p className=\"flex items-center gap-2 mb-2\">\n <span>Total Price:</span>\n <Money as=\"span\" data={price} withoutTrailingZeros />\n {isDiscounted(price, compareAtPrice) && <CompareAtPrice data={compareAtPrice} />}\n </p>\n )}\n </div>\n )\n );\n};\n", "import clsx from 'clsx';\nimport { RebuyProductPrice } from '~/components/ProductPrice';\nimport { Select } from '~/widgets/RebuyDynamicBundleProducts/Select';\nimport type { BundleSelectionProps } from '~/widgets/RebuyDynamicBundleProducts/types';\n\nimport styles from './RebuyDynamicBundleProducts.module.css';\n\nexport const BundleSelection = ({ onSelectVariant, onToggleBundleItem, products }: BundleSelectionProps) => {\n return (\n <ul>\n {products.map((product, index) => {\n const { availableForSale } = product.selectedVariant;\n const isOutOfStock = !availableForSale;\n\n return (\n <li\n className={clsx(styles.bundleItemRowContainer, !product.selected && styles.unselected)}\n key={product.id + '-BundleSelection' + index}\n >\n <div className={styles.bundleItemRow}>\n <input\n checked={product.selected && availableForSale}\n className=\"mt-1 rounded-sm accent-black cursor-pointer\"\n disabled={isOutOfStock}\n id={`${product.id}-toggle`}\n onChange={() => onToggleBundleItem(product)}\n type=\"checkbox\"\n value={product.id}\n />\n <div className={styles.bundleItemInput}>\n <label className={styles.bundleItemLabel} htmlFor={`${product.id}-toggle`}>\n {isOutOfStock && <b>SOLD OUT</b>}\n {product.default && <b>This item:</b>}\n {product.title}\n\n <RebuyProductPrice selectedVariant={product.selectedVariant} />\n </label>\n\n {product.variants.nodes.length > 1 && (\n <Select onSelectVariant={onSelectVariant} product={product} />\n )}\n </div>\n </div>\n </li>\n );\n })}\n </ul>\n );\n};\n", "import type { BundleProduct, BundleSelectProps } from '~/widgets/RebuyDynamicBundleProducts/types';\n\nimport styles from './RebuyDynamicBundleProducts.module.css';\n\nexport const Select = ({ onSelectVariant, product }: BundleSelectProps) => {\n const getOptionsLabel = (product: BundleProduct) => {\n const options = product.variants.nodes[0].selectedOptions;\n const optionsFromKeys = options ? Object.keys(options[0]) : [];\n const optionsFromValues = options ? options.map((option) => option.name) : [];\n const useValues = optionsFromKeys.every((key) => ['name', 'value'].includes(key));\n\n // Return delimited label for available option(s) e.g. Color / Size, Scent, etc\n return (useValues ? optionsFromValues : optionsFromKeys).join(' / ');\n };\n\n return (\n product && (\n <select\n aria-label=\"select variant\"\n className={styles.select}\n onChange={(e) => onSelectVariant(product, e.target.value)}\n value={product.selectedVariant.id}\n >\n <optgroup label={getOptionsLabel(product)}>\n {product.variants.nodes.map(({ id, title }) => (\n <option key={id + '-BundleVariant'} value={id}>\n {title}\n </option>\n ))}\n </optgroup>\n </select>\n )\n );\n};\n", "import { Money } from '@shopify/hydrogen-react';\nimport type { CurrencyCode, MoneyV2 } from '@shopify/hydrogen-react/storefront-api-types';\nimport { useCallback, useEffect, useState } from 'react';\n\nimport { AddToCartBtn } from '~/components/AddToCartBtn';\nimport { Title } from '~/components/Title';\nimport { DebugKey } from '~/constants/debug';\nimport { useRebuyWidget } from '~/context/RebuyWidgetContext';\nimport { getTitleLevel } from '~/hooks/titleLevel';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport type { RebuyProduct } from '~/types/rebuyCustom';\nimport { convertToRebuyProduct } from '~/utils/convertToRebuyProduct';\nimport type { RebuyProductAddOnProps } from '~/widgets/RebuyProductAddOns/types';\nimport { RebuyProductAddOnCard } from './RebuyProductAddOnCard';\nimport styles from './RebuyProductAddOns.module.css';\n\nexport const RebuyProductAddOns = (props: RebuyProductAddOnProps) => {\n const {\n addToCartBtnText = 'Add to cart',\n addToCartCallback,\n customTitle = `These pair with {product_title}`,\n customTitleLevel = 'h2',\n customTitleStyle,\n includeMainProduct = false,\n learnMoreText = 'Learn more',\n outOfStockText = 'Out of stock',\n subtotalText = 'Add-ons Subtotal: ',\n withProductText = `With {product_title}: `,\n } = props;\n\n const { isHydrogenReact, product, products } = useRebuyWidget();\n\n const productTitleClean = customTitle.replace('{product_title}', product?.title ?? '');\n const withProductTextClean = withProductText.replace('{product_title}', product?.title ?? '');\n\n const [addedItems, setAddedItems] = useState<RebuyProduct[]>(products);\n\n const [subtotalWithProduct, setSubtotalWithProduct] = useState<MoneyV2>();\n const [subtotalWithOutProduct, setSubtotalWithOutProduct] = useState<MoneyV2>();\n\n const convertedProduct = convertToRebuyProduct(isHydrogenReact || false, product);\n\n useEffect(() => {\n let initialTotal = 0;\n let currencyCode = 'USD' as CurrencyCode;\n\n products.map((product) => {\n product.selectedVariant = product.variants.nodes[0];\n product.selected = true;\n\n if (product.selectedVariant?.priceV2) {\n initialTotal += Number(product.selectedVariant.priceV2.amount);\n currencyCode = (product.selectedVariant.priceV2.currencyCode || 'USD') as CurrencyCode;\n }\n });\n\n setSubtotalWithProduct({\n amount: String(initialTotal),\n currencyCode,\n });\n\n setSubtotalWithOutProduct({\n amount: String(\n initialTotal -\n Number(\n isHydrogenReact\n ? convertedProduct?.selectedVariant?.priceV2?.amount\n : product?.selectedOrFirstAvailableVariant?.price.amount\n )\n ),\n currencyCode,\n });\n setAddedItems(products);\n\n if (includeMainProduct) {\n setAddedItems([convertedProduct, ...products]);\n } else {\n setAddedItems(products);\n }\n }, [products, product, isHydrogenReact, includeMainProduct]);\n\n const handleChange = useCallback(\n (event: React.ChangeEvent<HTMLInputElement>, product: RebuyProduct) => {\n const newProducts = [...products];\n const productIndex = newProducts.findIndex((p) => p.id === product.id);\n\n if (productIndex !== -1) {\n newProducts[productIndex] = {\n ...newProducts[productIndex],\n selected: event.target.checked,\n };\n\n product.selected = event.target.checked;\n\n if (event.target.checked) {\n setAddedItems((prev) => [...prev, product]);\n } else {\n setAddedItems((prev) => prev.filter((item) => item.id !== product.id));\n }\n }\n },\n [products]\n );\n\n useEffect(() => {\n let total = 0;\n let currencyCode = 'USD' as CurrencyCode;\n\n addedItems.forEach((item) => {\n if (item.selected && item.selectedVariant?.priceV2) {\n total += Number(item.selectedVariant.priceV2.amount);\n currencyCode = (item.selectedVariant.priceV2.currencyCode || 'USD') as CurrencyCode;\n }\n });\n\n setSubtotalWithProduct({\n amount: String(total),\n currencyCode,\n });\n\n setSubtotalWithOutProduct({\n amount: String(\n total -\n Number(\n isHydrogenReact\n ? convertedProduct?.selectedVariant?.priceV2?.amount\n : product?.selectedOrFirstAvailableVariant?.price.amount\n )\n ),\n currencyCode,\n });\n }, [addedItems, product, isHydrogenReact]);\n\n if (products.length === 0) {\n rebuyDebugLog.log(DebugKey.WIDGET_PRODUCT_ADD_ONS, 'RebuyProductAddOns: No products found');\n\n return null;\n }\n\n return (\n <div className={styles.container}>\n <Title level={getTitleLevel(customTitleLevel)} style={customTitleStyle} text={productTitleClean} />\n <ul className={styles.productAddOnsList}>\n {products.map((product) => (\n <li key={product.id}>\n <RebuyProductAddOnCard\n handleChange={handleChange}\n learnMoreText={learnMoreText}\n outOfStockText={outOfStockText}\n product={product}\n titleLevel={getTitleLevel(customTitleLevel, true)}\n />\n </li>\n ))}\n </ul>\n <div className={styles.productAddOnsFooter}>\n <div className={styles.moneyContainer}>\n {subtotalText}\n {subtotalWithOutProduct && <Money data={subtotalWithOutProduct} withoutTrailingZeros />}\n </div>\n {includeMainProduct && (\n <div className={styles.moneyContainer}>\n {withProductTextClean}\n {subtotalWithProduct && <Money data={subtotalWithProduct} withoutTrailingZeros />}\n </div>\n )}\n <div className={styles.addCartBtnContainer}>\n {includeMainProduct ? (\n <AddToCartBtn\n addToCartBtnText={addToCartBtnText}\n addToCartCallback={addToCartCallback}\n disabled={addedItems.length === 0}\n isHydrogenReact={isHydrogenReact}\n moneyData={subtotalWithProduct}\n selectedVariants={addedItems.map((item) => item.selectedVariant)}\n />\n ) : (\n <AddToCartBtn\n addToCartBtnText={addToCartBtnText}\n addToCartCallback={addToCartCallback}\n disabled={addedItems.length === 0}\n isHydrogenReact={isHydrogenReact}\n moneyData={subtotalWithOutProduct}\n selectedVariants={addedItems.map((item) => item.selectedVariant)}\n />\n )}\n </div>\n </div>\n </div>\n );\n};\n", "import { Image } from '@shopify/hydrogen';\n\nimport { RebuyProductPrice } from '~/components/ProductPrice';\nimport { RebuyLink } from '~/components/RebuyLink';\nimport { Title } from '~/components/Title';\nimport type { RebuyProductAddOnCardProps } from './types';\nimport styles from './RebuyProductAddOns.module.css';\n\nexport const RebuyProductAddOnCard = ({\n handleChange,\n learnMoreText,\n outOfStockText,\n product,\n titleLevel,\n}: RebuyProductAddOnCardProps) => {\n const { availableForSale, image } = product.selectedVariant || {};\n\n return (\n <label className={styles.addOnCard} htmlFor={product.id}>\n <div className={styles.addOnCardContent}>\n <input\n checked={Boolean(product.selected)}\n className={styles.addOnCardInput}\n disabled={!product.variants.nodes[0].availableForSale}\n id={product.id}\n name={product.title}\n onChange={(event) => handleChange(event, product)}\n type=\"checkbox\"\n value=\"\"\n />\n <div className={styles.addOnCardContentImage}>\n {image && (\n <Image\n alt={image.altText || `Picture of ${product.title}`}\n data={image}\n height={150}\n width={300}\n />\n )}\n </div>\n\n <div className={styles.addOnCardTextContent}>\n {!availableForSale && <p className={styles.addOnCardOutOfStock}>{outOfStockText}</p>}\n\n <Title level={titleLevel} text={product.title} />\n\n <RebuyProductPrice selectedVariant={product.selectedVariant} />\n <RebuyLink\n ariaLabel={`View ${product.title}`}\n className={styles.addOnCardLearnMore}\n handle={`/products/${product.handle}`}\n >\n {learnMoreText}\n </RebuyLink>\n </div>\n </div>\n </label>\n );\n};\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/widgets/RebuyProductAddOns/RebuyProductAddOns.css\";\n const result = {\"container\":\"RebuyProductAddOns_container\",\"productAddOnsList\":\"RebuyProductAddOns_productAddOnsList\",\"addOnCard\":\"RebuyProductAddOns_addOnCard\",\"addOnCardContent\":\"RebuyProductAddOns_addOnCardContent\",\"addOnCardInput\":\"RebuyProductAddOns_addOnCardInput\",\"addOnCardContentImage\":\"RebuyProductAddOns_addOnCardContentImage\",\"addOnCardOutOfStock\":\"RebuyProductAddOns_addOnCardOutOfStock\",\"addOnCardTextContent\":\"RebuyProductAddOns_addOnCardTextContent\",\"addOnCardLearnMore\":\"RebuyProductAddOns_addOnCardLearnMore\",\"addCartBtnContainer\":\"RebuyProductAddOns_addCartBtnContainer\",\"productAddOnsFooter\":\"RebuyProductAddOns_productAddOnsFooter\",\"moneyContainer\":\"RebuyProductAddOns_moneyContainer\"};\n export default result;\n ", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/widgets/RebuyProductRecommendations/RebuyProductRecommendations.css\";\n const result = {\"container\":\"RebuyProductRecommendations_container\",\"productGrid\":\"RebuyProductRecommendations_productGrid\"};\n export default result;\n ", "import { ProductCard } from '~/components/ProductCard';\nimport { Title } from '~/components/Title';\nimport { DebugKey } from '~/constants/debug';\nimport { useRebuyWidget } from '~/context/RebuyWidgetContext';\nimport { getTitleLevel } from '~/hooks/titleLevel';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport type { RebuyProductRecommendationsProps } from './types';\n\nimport styles from './RebuyProductRecommendations.module.css';\n\nexport const RebuyProductRecommendations = (props: RebuyProductRecommendationsProps) => {\n const {\n addToCartBtnText = 'Add to cart',\n addToCartCallback,\n customTitle = `These pair with {product_title}`,\n customTitleLevel = 'h2',\n customTitleStyle,\n } = props;\n\n const { isHydrogenReact, product, products } = useRebuyWidget();\n\n const productTitle = customTitle.replace('{product_title}', product?.title ?? '');\n\n if (products.length === 0) {\n rebuyDebugLog.log(DebugKey.WIDGET_PRODUCT_RECOMMENDATIONS, 'RebuyProductRecommendations: No products found');\n\n return null;\n }\n\n return (\n <section className={styles.container}>\n <Title level={getTitleLevel(customTitleLevel)} style={customTitleStyle} text={productTitle} />\n <ul className={styles.productGrid}>\n {products.map((product) => (\n <li key={product.id}>\n <ProductCard\n addToCartBtnText={addToCartBtnText}\n addToCartCallback={addToCartCallback}\n isHydrogenReact={isHydrogenReact}\n product={product}\n productCardTitleLevel={getTitleLevel(customTitleLevel, true)}\n />\n </li>\n ))}\n </ul>\n </section>\n );\n};\n", "import { RebuyClient } from '@rebuy/rebuy';\nimport * as Utilities from '@rebuy/rebuy/utilities';\nimport { useEffect, useMemo, useState } from 'react';\nimport { useRebuyConfig } from '~/context/RebuyConfigContext';\n\nimport type { ProductViewedRequest } from '~/types/common';\nimport type { RebuyProductViewedProps } from '~/widgets/RebuyProductViewed/types';\nimport { useProductViewedStore } from '~/zustandStores/productViewed';\n\nexport const RebuyProductViewed = ({ ...props }: RebuyProductViewedProps) => {\n const { apiKey: apiKeyFromContext } = useRebuyConfig();\n const { customerId, product, productHandle, productId } = props;\n\n // eslint-disable-next-line no-unused-vars\n const [event, setEvent] = useState(null);\n const [Rebuy, setRebuy] = useState<RebuyClient | null>(null);\n const shopifyProductId = product?.id ?? productId ?? null;\n const [initialized, setInitialized] = useState(false);\n const { setCustomerId, setUuid } = useProductViewedStore();\n\n const request = useMemo(() => {\n const request: ProductViewedRequest = {\n parameters: {},\n };\n\n if (shopifyProductId) {\n const productNumericId = Utilities.getIdFromGraphUrl(shopifyProductId, 'Product');\n\n if (productNumericId !== null) {\n request.parameters.shopify_product_id = productNumericId.toString();\n }\n } else if (productHandle) {\n request.parameters.shopify_product_handle = productHandle;\n }\n\n return request;\n }, [productHandle, shopifyProductId]);\n\n useEffect(() => {\n const recordView = async () => {\n if (!Rebuy) {\n return;\n }\n\n try {\n const response = await Rebuy.trackProductViewed(request.parameters);\n setEvent(response.data);\n\n if (response.data === 'Received' && request.parameters.uuid) {\n setUuid(request.parameters.uuid);\n\n if (customerId && customerId !== '') {\n setCustomerId(customerId);\n }\n }\n } catch (error) {\n console.error('Error tracking product view:', error);\n }\n };\n\n if (!initialized && apiKeyFromContext) {\n const client = new RebuyClient(apiKeyFromContext);\n\n setRebuy(client);\n setInitialized(true);\n\n return;\n }\n\n recordView();\n }, [request.parameters, initialized, apiKeyFromContext, Rebuy]);\n\n if (Object.keys(request.parameters).length === 0) {\n console.warn('No parameters!');\n\n return;\n }\n\n return null;\n};\n", "import { create } from 'zustand';\n\ntype ProductViewedStore = {\n customerId: string | null;\n setCustomerId: (customerId: string) => void;\n setUuid: (uuid: string) => void;\n uuid: string | null;\n};\n\nexport const useProductViewedStore = create<ProductViewedStore>((set) => ({\n customerId: null,\n setCustomerId: (customerId) => set({ customerId }),\n setUuid: (uuid) => set({ uuid }),\n uuid: null,\n}));\n", "import { RebuyClient } from '@rebuy/rebuy';\nimport { flattenConnection } from '@shopify/hydrogen';\nimport { useContext, useEffect, useMemo, useState } from 'react';\nimport { ProductCard } from '~/components/ProductCard';\nimport { Title } from '~/components/Title';\nimport { DebugKey } from '~/constants/debug';\nimport { useRebuyConfig } from '~/context/RebuyConfigContext';\nimport { RebuyContext } from '~/context/RebuyContext';\nimport { getTitleLevel } from '~/hooks/titleLevel';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport type { RebuyProduct, RebuyWidgetMetadata } from '~/types/rebuyCustom';\nimport { filterContextForWidgetEndpoints } from '~/utils/filterContextUtils';\nimport { useProductViewedStore } from '~/zustandStores/productViewed';\nimport type { RebuyRecentlyViewedProductsProps } from './types';\nimport styles from './RebuyRecentlyViewedProducts.module.css';\n\nexport const RebuyRecentlyViewedProducts = (props: RebuyRecentlyViewedProductsProps) => {\n const {\n addToCartBtnText = 'Add to cart',\n addToCartCallback,\n customTitle = `Your recently viewed products`,\n customTitleLevel = 'h2',\n customTitleStyle,\n limit,\n options,\n productId,\n } = props;\n const { customerId, uuid } = useProductViewedStore();\n\n const { apiKey, loadingStatus: configLoadingStatus, rebuyConfig } = useRebuyConfig();\n const rebuyContext = useContext(RebuyContext);\n\n const [rebuyApiClient, setRebuyApiClient] = useState<RebuyClient | null>(null);\n const [initialized, setInitialized] = useState(false);\n const [products, setProducts] = useState<RebuyProduct[]>([]);\n const [metadata, setMetadata] = useState<RebuyWidgetMetadata>();\n const rebuyConfigKey = rebuyConfig?.shop?.cache_key;\n\n const endpoint =\n customerId && customerId !== ''\n ? `/api/v1/products/viewed?key=${rebuyConfigKey}&customer_id=${customerId}`\n : `/api/v1/products/viewed?key=${rebuyConfigKey}&uuid=${uuid}`;\n\n // const filtered = products?.filter((recent) => recent.id !== product?.id);\n // Initialize Rebuy API client\n useEffect(() => {\n if (!rebuyApiClient && apiKey && configLoadingStatus === 'success') {\n const client = new RebuyClient(apiKey);\n\n if (rebuyContext?.contextParameters) {\n const filteredParams = filterContextForWidgetEndpoints(rebuyContext.contextParameters, endpoint);\n client.setContextParameters(filteredParams as Record<string, unknown>);\n }\n\n if (options) {\n client.setDefaultParameters(options as Record<string, unknown>);\n }\n\n setRebuyApiClient(client);\n setInitialized(true);\n }\n }, [apiKey, rebuyApiClient, configLoadingStatus, options, rebuyContext, uuid, endpoint]);\n\n // Update context parameters if they change\n useEffect(() => {\n if (rebuyApiClient && rebuyContext?.contextParameters) {\n const filteredParams = filterContextForWidgetEndpoints(rebuyContext.contextParameters, endpoint);\n rebuyApiClient.setContextParameters(filteredParams as Record<string, unknown>);\n }\n }, [rebuyApiClient, rebuyContext, uuid, endpoint]);\n\n // Memoize request object on prop changes (e.g. product)\n const request = useMemo(() => {\n const req = {\n endpoint,\n params: {} as Record<string, string | number>, // Keeping this object generic to allow for custom endpoints\n };\n\n if (limit) {\n req.params.limit = limit;\n }\n\n return req;\n }, [limit, uuid, endpoint]);\n\n // Update product recommendations on cart or request change\n useEffect(() => {\n let isMounted = true;\n\n if (!rebuyApiClient || !initialized || configLoadingStatus !== 'success') return;\n\n const fetchData = async () => {\n try {\n const { data, metadata } = (await rebuyApiClient.getStorefrontData(\n request.endpoint,\n request.params\n )) as {\n data: RebuyProduct[];\n metadata: RebuyWidgetMetadata;\n };\n\n if (isMounted) {\n setProducts(\n Array.isArray(data)\n ? data\n .filter((p) => p.id !== productId)\n .map((p) => ({\n ...p,\n variants: {\n nodes: p.variants ? flattenConnection(p.variants) : [],\n },\n }))\n : []\n );\n setMetadata(metadata);\n }\n } catch (error) {\n console.error('[RebuyWidgetContainer] Error fetching widget data:', error);\n\n if (isMounted) {\n setProducts([]);\n setMetadata(undefined);\n }\n }\n };\n\n fetchData();\n\n return () => {\n isMounted = false;\n };\n }, [rebuyApiClient, initialized, request, configLoadingStatus, productId]);\n\n if (products.length === 0) {\n rebuyDebugLog.log(DebugKey.WIDGET_RECENTLY_VIEWED_PRODUCTS, 'RebuyRecentlyViewedProducts: No products found');\n\n return null;\n }\n\n return (\n <div className={styles['rebuy-recently-viewed-products-container']}>\n <Title level={getTitleLevel(customTitleLevel)} style={customTitleStyle} text={customTitle} />\n <ul className={styles['product-grid']}>\n {products?.map((product) => (\n <li key={product.id}>\n <ProductCard\n addToCartBtnText={addToCartBtnText}\n addToCartCallback={addToCartCallback}\n key={product.id}\n product={product}\n productCardTitleLevel={getTitleLevel('h2')}\n />\n </li>\n ))}\n </ul>\n </div>\n );\n};\n", "\n import \"/tmp/tmp-165-4MNxpOR0FLRl/opt/atlassian/pipelines/agent/build/src/widgets/RebuyRecentlyViewedProducts/RebuyRecentlyViewedProducts.css\";\n const result = {\"rebuy-recently-viewed-products-container\":\"RebuyRecentlyViewedProducts_rebuy-recently-viewed-products-container\",\"product-grid\":\"RebuyRecentlyViewedProducts_product-grid\"};\n export default result;\n ", "export const REBUY_THEME_STYLES_BASE_URL = 'https://rebuyengine.com/api/v1/theme-styles';\n", "import { REBUY_THEME_STYLES_BASE_URL } from '~/constants/api';\n\n/**\n * Generates a link object for the Rebuy theme stylesheet.\n * Suitable for Remix's static `links` export.\n *\n * Requires API key to be passed directly or available as an environment variable\n * that this function can access (if it were running in a Node.js server environment\n * where process.env is available before React rendering).\n * For Remix, it's best to pass the apiKey explicitly if it's not a universally available env var.\n *\n * @param {object} options - The options for the Rebuy theme stylesheet link.\n * @param {string} options.apiKey - The API key for the Rebuy theme stylesheet.\n * @returns {Array<{ href: string; rel: string }>}\n */\nexport const getRebuyThemeStylesLink = (options: { apiKey: string }): { href: string; rel: string }[] => {\n const { apiKey } = options;\n\n if (!apiKey) {\n // This function is often called in a context where React isn't fully set up (like Remix links)\n // so console.warn might be the best side effect.\n console.warn('[getRebuyThemeStylesLink] API key is missing. Stylesheet link will not be generated.');\n\n return [];\n }\n\n // TODO: use rebuy client to generate domain\n const stylesheetUrl = `${REBUY_THEME_STYLES_BASE_URL}?key=${apiKey}`;\n\n return [{ href: stylesheetUrl, rel: 'stylesheet' }];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AAgB,GAAG,2BAA2B,QAAQ,MAAM;AAElE,SAAO,CAAC,EAAE,MAAM,eAAe,KAAK,aAAa,CAAC;AACtD;",
6
- "names": ["Utilities", "useMemo", "useRef", "errorMessage", "createContext", "isEqual", "createContext", "useContext", "useEffect", "useMemo", "useRef", "useState", "flattenConnection", "jsx", "jsx", "flattenConnection", "jsx", "createContext", "useContext", "useState", "useMemo", "useRef", "isEqual", "useEffect", "jsx", "jsxs", "warningLogged", "useRef", "useMemo", "Utilities", "useEffect", "useMemo", "useRef", "useLocation", "Fragment", "jsx", "jsxs", "warningLogged", "useRef", "useLocation", "useMemo", "useEffect", "clsx", "React", "useCallback", "useEffect", "useMemo", "useRef", "useMemo", "useCallback", "useEffect", "useMemo", "useRef", "useState", "jsx", "jsx", "jsxs", "useState", "useRef", "useMemo", "useCallback", "useEffect", "useCallback", "useEffect", "useMemo", "useState", "jsx", "useCallback", "useMemo", "useState", "useState", "useMemo", "useCallback", "bmsmTiers", "result", "Fragment", "jsx", "jsxs", "useState", "useMemo", "useCallback", "useEffect", "result", "jsx", "result", "jsx", "clsx", "React", "useCallback", "useEffect", "useMemo", "useRef", "useState", "useFetcher", "result", "jsx", "jsxs", "React", "useFetcher", "useRef", "useState", "useMemo", "useEffect", "useCallback", "clsx", "clsx", "React", "useCallback", "useMemo", "useState", "result", "Fragment", "jsx", "jsxs", "useState", "useMemo", "useCallback", "clsx", "React", "DOMPurify", "React", "useMemo", "result", "jsx", "React", "useMemo", "DOMPurify", "React", "useCallback", "useEffect", "useMemo", "useState", "useFetcher", "result", "jsx", "jsxs", "React", "useFetcher", "useState", "useEffect", "useMemo", "useCallback", "RebuyClient", "Utilities", "flattenConnection", "useContext", "useEffect", "useMemo", "useRef", "useState", "jsx", "useEffect", "useState", "useCallback", "useEffect", "elements", "useCallback", "useMemo", "useState", "result", "Fragment", "jsx", "jsxs", "Money", "useCart", "Fragment", "jsx", "jsxs", "useCart", "Money", "jsx", "Money", "clsx", "result", "jsx", "jsxs", "price", "compareAtPrice", "Money", "clsx", "useState", "result", "jsx", "useState", "clsx", "useEffect", "useState", "result", "jsx", "useState", "useEffect", "clsx", "clsx", "result", "jsx", "clsx", "result", "jsx", "jsxs", "useState", "useCallback", "product", "useMemo", "useEffect", "useState", "result", "jsx", "jsxs", "useState", "useEffect", "clsx", "useCallback", "useEffect", "useState", "result", "jsx", "jsxs", "useState", "useCallback", "useEffect", "clsx", "result", "jsx", "jsxs", "Fragment", "jsx", "jsxs", "useState", "useRef", "useContext", "useEffect", "RebuyClient", "useMemo", "flattenConnection", "jsx", "React", "useEffect", "useMemo", "useRef", "jsx", "React", "useRef", "useMemo", "useEffect", "clsx", "React", "useCallback", "useEffect", "useMemo", "useRef", "useState", "useFetcher", "useCallback", "useEffect", "useMemo", "useState", "useState", "useMemo", "useEffect", "useCallback", "result", "jsx", "jsxs", "useFetcher", "useState", "useRef", "useMemo", "useCallback", "useEffect", "clsx", "React", "React", "result", "jsx", "React", "React", "useEffect", "useMemo", "useRef", "useEffect", "useState", "z", "useState", "useEffect", "jsx", "jsxs", "React", "useRef", "useMemo", "useEffect", "clsx", "React", "useCallback", "useEffect", "useMemo", "useState", "useFetcher", "useShallow", "clsx", "result", "Fragment", "jsx", "jsxs", "clsx", "jsx", "jsxs", "React", "useFetcher", "useState", "useShallow", "useMemo", "useEffect", "useCallback", "clsx", "jsx", "jsxs", "Fragment", "jsx", "useMemo", "clsx", "useRef", "useEffect", "useState", "result", "jsx", "jsxs", "useRef", "clsx", "clsx", "useRef", "Fragment", "jsx", "jsxs", "useRef", "clsx", "result", "jsx", "jsxs", "useRef", "useMemo", "useCallback", "useEffect", "clsx", "React", "jsx", "RebuyClient", "Utilities", "flattenConnection", "useContext", "useEffect", "useMemo", "useState", "createContext", "useContext", "jsx", "jsx", "useContext", "useState", "useEffect", "RebuyClient", "useMemo", "metadata", "flattenConnection", "result", "jsx", "jsxs", "product", "useCallback", "useEffect", "useState", "Image", "Fragment", "result", "Fragment", "jsx", "jsxs", "Image", "Money", "jsx", "jsxs", "price", "compareAtPrice", "Money", "clsx", "jsx", "product", "jsx", "jsxs", "clsx", "jsx", "jsxs", "useState", "useEffect", "product", "useCallback", "Money", "useCallback", "useEffect", "useState", "Image", "result", "jsx", "jsxs", "Image", "jsx", "jsxs", "useState", "useEffect", "product", "useCallback", "Money", "result", "jsx", "jsxs", "product", "RebuyClient", "Utilities", "useEffect", "useMemo", "useState", "create", "useState", "useMemo", "request", "useEffect", "RebuyClient", "RebuyClient", "flattenConnection", "useContext", "useEffect", "useMemo", "useState", "result", "jsx", "jsxs", "useContext", "useState", "useEffect", "RebuyClient", "useMemo", "metadata", "flattenConnection"]
3
+ "sources": ["../src/providers/RebuyHydrogenContextProvider.tsx", "../src/context/RebuyConfigContext.tsx", "../src/smart-cart/utils/debugLog.ts", "../src/utils/getRebuyConfig.ts", "../src/context/RebuyContext.tsx", "../src/hooks/useBFCacheReset.ts", "../src/smart-cart/context/SmartCartContext.tsx", "../src/smart-cart/store/tieredProgressBarStore.ts", "../src/smart-cart/components/TieredProgressBar/progressBarUtils.tsx", "../src/smart-cart/components/TieredProgressBar/Icons.tsx", "../src/smart-cart/constants.ts", "../src/smart-cart/utils/moneyUtils.ts", "../src/smart-cart/utils/cartItemUtils.ts", "../src/smart-cart/utils/safeJsonParse.ts", "../src/smart-cart/utils/mapHydrogenCartToStorefrontCartData.ts", "../src/utils/createContextParameters.ts", "../src/utils/getEncodedAttributes.ts", "../src/providers/RebuyHydrogenReactContextProvider.tsx", "../src/queries/cart.queries.ts", "../src/smart-cart/components/SmartCartContainer/SmartCartContainer.tsx", "../src/smart-cart/components/_Layouts/AnchorSlot.tsx", "../src/smart-cart/components/AnnouncementBar/AnnouncementBar.tsx", "../src/smart-cart/components/ScreenReaderText/ScreenReaderText.tsx", "../src/smart-cart/components/AnnouncementBar/AnnouncementBar.module.css", "../src/smart-cart/components/CartItem/CartItem.tsx", "../src/components/RebuyLink/RebuyLink.tsx", "../src/smart-cart/hooks/useCartItemFeatures.ts", "../src/smart-cart/utils/imageUtils.ts", "../src/smart-cart/components/CartItem/CartItem.module.css", "../src/smart-cart/components/EmptyCart/EmptyCart.module.css", "../src/smart-cart/components/EmptyCart/EmptyCart.tsx", "../src/smart-cart/components/CartItemList/CartItemList.module.css", "../src/smart-cart/components/CartItemList/CartItemList.tsx", "../src/smart-cart/components/CartNoteInput/CartNoteInput.tsx", "../src/smart-cart/components/CartNoteInput/CartNoteInput.module.css", "../src/smart-cart/components/CartSubtotal/CartSubtotal.tsx", "../src/smart-cart/components/CartSubtotal/CartSubtotal.module.css", "../src/smart-cart/components/CartTitleBar/CartTitleBar.tsx", "../src/smart-cart/components/CartTitleBar/CartTitleBar.module.css", "../src/smart-cart/components/CheckoutArea/CheckoutArea.tsx", "../src/smart-cart/components/CheckoutArea/CheckoutArea.module.css", "../src/widgets/RebuyWidget/RebuyWidget.tsx", "../src/assets/Close.tsx", "../src/hooks/useBreakpoint.ts", "../src/hooks/usePopupTrigger.tsx", "../src/types/widgets.ts", "../src/utils/filterContextUtils.ts", "../src/components/ProductCard/defaultSettings.ts", "../src/components/ProductCard/ProductCard.tsx", "../src/components/AddToCartBtn/HydrogenAddToCartBtn.tsx", "../src/components/AddToCartBtn/AddToCartBtn.module.css", "../src/components/AddToCartBtn/HydrogenReactAddToCartBtn.tsx", "../src/components/AddToCartBtn/AddToCartBtn.tsx", "../src/components/ProductPrice/ProductPrice.tsx", "../src/components/ProductPrice/ProductPrice.module.css", "../src/components/QuantityInput/QuantityInput.tsx", "../src/components/QuantityInput/QuantityInput.module.css", "../src/components/VariantSelect/VariantSelect.tsx", "../src/components/VariantSelect/VariantSelect.module.css", "../src/components/Title/Title.tsx", "../src/components/Title/Title.module.css", "../src/components/ProductCard/ProductCard.module.css", "../src/components/ProductCarousel/ProductCarousel.tsx", "../src/components/ProductCarousel/ProductCarousel.module.css", "../src/components/Timer/Timer.tsx", "../src/components/Timer/Timer.module.css", "../src/hooks/titleLevel.tsx", "../src/widgets/RebuyWidget/RebuyWidget.module.css", "../src/widgets/RebuyWidget/WidgetContent.tsx", "../src/smart-cart/components/CrossSell/CrossSell.tsx", "../src/smart-cart/components/CustomCode/CustomCodeBlock.tsx", "../src/utils/nonceManager.ts", "../src/smart-cart/utils/executeScriptsInContainer.ts", "../src/smart-cart/components/DiscountCodeInput/DiscountCodeInput.tsx", "../src/smart-cart/hooks/useDiscountManager.ts", "../src/smart-cart/components/DiscountCodeInput/DiscountCodeInput.module.css", "../src/smart-cart/components/LoginButton/LoginButton.tsx", "../src/smart-cart/components/LoginButton/LoginButton.module.css", "../src/smart-cart/components/SmartCartApp/SmartCartApp.tsx", "../src/smart-cart/hooks/useSmartCartApps.ts", "../src/smart-cart/types/smart-cart-app.ts", "../src/smart-cart/components/TieredProgressBar/TieredProgressBar.tsx", "../src/smart-cart/components/TieredProgressBar/TPBGiftItem.tsx", "../src/smart-cart/components/TieredProgressBar/TieredProgressBar.module.css", "../src/smart-cart/utils/debugStyles.ts", "../src/smart-cart/components/componentRegistry.tsx", "../src/smart-cart/components/_Layouts/DoubleColumnLayout.tsx", "../src/smart-cart/hooks/useIsScrolled.ts", "../src/smart-cart/components/_Layouts/LayoutStyles.module.css", "../src/smart-cart/components/_Layouts/SingleColumnLayout.tsx", "../src/smart-cart/components/SmartCartContainer/SmartCartContainer.module.css", "../src/smart-cart/RebuySmartCart.tsx", "../src/widgetContainer/RebuyWidgetContainer.tsx", "../src/context/RebuyWidgetContext.tsx", "../src/widgets/RebuyCompleteTheLook/RebuyCompleteTheLook.module.css", "../src/widgets/RebuyCompleteTheLook/RebuyCompleteTheLook.tsx", "../src/widgets/RebuyDynamicBundleProducts/RebuyDynamicBundleProducts.tsx", "../src/utils/convertToRebuyProduct.tsx", "../src/widgets/RebuyDynamicBundleProducts/BundleImages.tsx", "../src/widgets/RebuyDynamicBundleProducts/RebuyDynamicBundleProducts.module.css", "../src/widgets/RebuyDynamicBundleProducts/BundlePrice.tsx", "../src/widgets/RebuyDynamicBundleProducts/BundleSelection.tsx", "../src/widgets/RebuyDynamicBundleProducts/Select.tsx", "../src/widgets/RebuyProductAddOns/RebuyProductAddOns.tsx", "../src/widgets/RebuyProductAddOns/RebuyProductAddOnCard.tsx", "../src/widgets/RebuyProductAddOns/RebuyProductAddOns.module.css", "../src/widgets/RebuyProductRecommendations/RebuyProductRecommendations.module.css", "../src/widgets/RebuyProductRecommendations/RebuyProductRecommendations.tsx", "../src/widgets/RebuyProductViewed/RebuyProductViewed.tsx", "../src/zustandStores/productViewed.ts", "../src/widgets/RebuyRecentlyViewedProducts/RebuyRecentlyViewedProducts.tsx", "../src/widgets/RebuyRecentlyViewedProducts/RebuyRecentlyViewedProducts.module.css", "../src/constants/api.ts", "../src/utils/theme.ts"],
4
+ "sourcesContent": ["import * as Utilities from '@rebuy/rebuy/utilities';\nimport type { Cart as HydrogenStorefrontApiCart } from '@shopify/hydrogen/storefront-api-types';\nimport { useMemo, useRef } from 'react';\nimport { Await, useLocation } from 'react-router';\nimport { RebuyConfigProvider, useRebuyConfig } from '~/context/RebuyConfigContext';\nimport { RebuyContext, type RebuyContextType } from '~/context/RebuyContext';\nimport { useBFCacheReset } from '~/hooks/useBFCacheReset';\nimport type { RebuyHydrogenContextProps, RebuyHydrogenContextProviderProps } from '~/providers/types';\nimport { SmartCartProvider as RebuySmartCartProvider } from '~/smart-cart/context/SmartCartContext';\nimport { createContextParameters } from '~/utils/createContextParameters';\n\nconst RebuyHydrogenContext = ({\n children,\n enableSmartCart,\n publicStorefrontToken,\n shop,\n sourceHydrogenCart,\n}: RebuyHydrogenContextProps) => {\n const resetKey = useBFCacheReset();\n\n const {\n apiKey,\n fetchError: configFetchError,\n loadingStatus: configLoadingStatus,\n rebuyConfig,\n shopDomain: configShopDomain,\n smartCartConfig,\n } = useRebuyConfig();\n\n const warningLogged = useRef(false);\n const location = useLocation();\n const queryObject = Utilities.queryStringToObject(location.search);\n const windowUrl = `${shop}${location.pathname}${location.search}`;\n\n // --- Context Parameters Memoization ---\n const contextParameters = useMemo(\n () =>\n createContextParameters({\n cacheKey: rebuyConfig?.shop?.cache_key,\n isHydrogenReact: false,\n queryObject,\n sourceHydrogenCart: sourceHydrogenCart as HydrogenStorefrontApiCart | null,\n windowUrl,\n }),\n [rebuyConfig?.shop?.cache_key, windowUrl, queryObject, sourceHydrogenCart]\n );\n\n const defaultContextValue = useMemo(() => null as unknown as RebuyContextType, []);\n const contextValue = useMemo(\n () => (configLoadingStatus === 'success' && rebuyConfig ? { contextParameters } : defaultContextValue),\n [configLoadingStatus, rebuyConfig, contextParameters, defaultContextValue]\n );\n\n // --- Smart Cart Prerequisites Calculation ---\n const cacheKey = rebuyConfig?.shop?.cache_key || '';\n const shopifyDomainForSmartCart = configShopDomain || rebuyConfig?.shop?.domain || '';\n const storefrontAccessToken = publicStorefrontToken || rebuyConfig?.shop?.storefront_access_token || '';\n\n const hasAllSmartCartPrerequisites =\n enableSmartCart &&\n configLoadingStatus === 'success' &&\n !!rebuyConfig &&\n !!(smartCartConfig && apiKey && shopifyDomainForSmartCart && storefrontAccessToken);\n\n return (\n <RebuyContext.Provider value={contextValue}>\n {configLoadingStatus === 'success' && rebuyConfig ? (\n enableSmartCart && hasAllSmartCartPrerequisites ? (\n <RebuySmartCartProvider\n apiKey={apiKey!}\n cacheKey={cacheKey}\n config={smartCartConfig!}\n hydrogenCart={sourceHydrogenCart as HydrogenStorefrontApiCart}\n key={`smart-cart-${resetKey}`}\n shopifyDomain={shopifyDomainForSmartCart}\n storefrontAccessToken={storefrontAccessToken}\n >\n {children}\n </RebuySmartCartProvider>\n ) : (\n <>\n {enableSmartCart &&\n !hasAllSmartCartPrerequisites &&\n !warningLogged.current &&\n (() => {\n console.warn(\n `[RebuyHydrogenContextProvider] Rebuy config loaded, but Smart Cart prerequisites NOT met for ${configShopDomain}. Smart Cart UI won't render. Check Rebuy Admin/env vars. Missing:`,\n {\n apiKey: !!apiKey,\n shopifyDomain: !!shopifyDomainForSmartCart,\n smartCartConfig: !!smartCartConfig,\n storefrontAccessToken: !!storefrontAccessToken,\n }\n );\n warningLogged.current = true;\n\n return null;\n })()}\n {children}\n </>\n )\n ) : configLoadingStatus === 'error' ? (\n <>\n {(() => {\n console.error(\n `[RebuyHydrogenContextProvider] Failed to load Rebuy configuration for ${configShopDomain}. Rebuy Smart Cart features unavailable. Error:`,\n configFetchError instanceof Error ? configFetchError.message : configFetchError\n );\n\n return null;\n })()}\n {children}\n </>\n ) : null}\n </RebuyContext.Provider>\n );\n};\n\n// --- Outer Provider (RebuyHydrogenContextProvider) ---\nexport const RebuyHydrogenContextProvider = ({\n cart,\n children,\n enableSmartCart = false,\n overrideApiKey,\n publicStoreDomain,\n publicStorefrontToken,\n shop,\n}: RebuyHydrogenContextProviderProps) => {\n if (!publicStoreDomain || !shop) {\n console.warn('[Rebuy Provider Wrapper] Waiting for \"publicStoreDomain\" and \"shop\" props.');\n\n return <>{children}</>;\n }\n\n return (\n <Await resolve={cart}>\n {(resolvedCart) => {\n const hydrogenCartFromRemix = resolvedCart as HydrogenStorefrontApiCart | null;\n\n return (\n <RebuyConfigProvider initialShopDomain={publicStoreDomain} overrideApiKey={overrideApiKey}>\n <RebuyHydrogenContext\n enableSmartCart={enableSmartCart}\n publicStorefrontToken={publicStorefrontToken}\n shop={shop}\n sourceHydrogenCart={hydrogenCartFromRemix}\n >\n {children}\n </RebuyHydrogenContext>\n </RebuyConfigProvider>\n );\n }}\n </Await>\n );\n};\n", "import { createContext, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';\nimport { DebugKey } from '~/constants/debug';\nimport type { SmartCartConfig } from '~/smart-cart/types/smart-cart';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport type { RebuyConfig } from '~/types/rebuyCustom';\nimport { getRebuyConfig } from '~/utils/getRebuyConfig';\n\nexport type RebuyConfigLoadingStatus = 'idle' | 'loading' | 'success' | 'error';\n\nexport type RebuyConfigContextType = {\n apiKey: string | null;\n fetchError: Error | string | null;\n fetchRebuyConfig: (domain: string) => Promise<void>;\n loadingStatus: RebuyConfigLoadingStatus;\n rebuyConfig: RebuyConfig | null;\n shopDomain: string | null;\n smartCartConfig: SmartCartConfig | null;\n};\n\nconst RebuyConfigContext = createContext<RebuyConfigContextType | undefined>(undefined);\n\nexport type RebuyConfigProviderProps = {\n children: ReactNode;\n /** The Shopify store domain (e.g., example-brand.myshopify.com) used to fetch the config. */\n initialShopDomain?: string;\n /** Optional API key to override environment variable or config-derived one. */\n overrideApiKey?: string;\n};\n\nexport const RebuyConfigProvider = ({ children, initialShopDomain, overrideApiKey }: RebuyConfigProviderProps) => {\n const [rebuyConfig, setRebuyConfig] = useState<RebuyConfig | null>(null);\n const [smartCartConfig, setSmartCartConfig] = useState<SmartCartConfig | null>(null);\n const [apiKey, setApiKey] = useState<string | null>(overrideApiKey || null);\n const [loadingStatus, setLoadingStatus] = useState<RebuyConfigLoadingStatus>('idle');\n const [fetchError, setFetchError] = useState<Error | string | null>(null);\n const [currentShopDomain, setCurrentShopDomain] = useState<string | null>(initialShopDomain || null);\n const isMounted = useRef(true);\n\n const fetchRebuyConfig = async (domainToFetch: string) => {\n if (!domainToFetch) {\n console.warn('[RebuyConfigProvider] No shop domain provided to fetchRebuyConfig.');\n setLoadingStatus('error');\n setFetchError('Shop domain is required to fetch Rebuy config.');\n\n return;\n }\n\n rebuyDebugLog.log(\n DebugKey.REBUY_CONFIG_CONTEXT,\n '[RebuyConfigProvider] Attempting to fetch Rebuy config for domain:',\n domainToFetch\n );\n setCurrentShopDomain(domainToFetch);\n setLoadingStatus('loading');\n setFetchError(null);\n\n try {\n const config = await getRebuyConfig(domainToFetch);\n rebuyDebugLog.log(DebugKey.REBUY_CONFIG_CONTEXT, '[RebuyConfigProvider] Fetched Rebuy config:', config);\n\n if (isMounted.current) {\n setRebuyConfig(config);\n // Prioritize overrideApiKey, then env var, then config's api_key\n setApiKey(overrideApiKey || config?.shop?.api_key || null);\n setSmartCartConfig(config?.smart_cart);\n setLoadingStatus('success');\n }\n } catch (error: unknown) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n console.error('[RebuyConfigProvider] Error fetching Rebuy config:', errorMessage, error);\n\n if (isMounted.current) {\n setFetchError(error instanceof Error ? error : errorMessage);\n setLoadingStatus('error');\n setRebuyConfig(null); // Clear previous config on error\n // Do not clear apiKey if it was from override or env, it might still be valid for some uses\n // If apiKey was solely from a previous config, it might be stale.\n // Consider if apiKey should be reset here if not from override/env.\n // For now, let's keep it simple: only update from new config if successful.\n }\n }\n };\n\n useEffect(() => {\n isMounted.current = true;\n\n if (initialShopDomain && loadingStatus === 'idle') {\n // Fetch on mount if domain provided and not already fetching/fetched\n fetchRebuyConfig(initialShopDomain);\n }\n\n return () => {\n isMounted.current = false;\n };\n // Rerun if initialShopDomain changes and we haven't started fetching yet.\n }, [initialShopDomain]);\n\n const contextValue = useMemo(\n () => ({\n apiKey,\n fetchError,\n fetchRebuyConfig,\n loadingStatus,\n rebuyConfig,\n shopDomain: currentShopDomain,\n smartCartConfig,\n }),\n [rebuyConfig, apiKey, loadingStatus, fetchError, currentShopDomain, smartCartConfig]\n );\n\n return <RebuyConfigContext.Provider value={contextValue}>{children}</RebuyConfigContext.Provider>;\n};\n\nexport const useRebuyConfig = (): RebuyConfigContextType => {\n const context = useContext(RebuyConfigContext);\n\n if (context === undefined) {\n throw new Error('useRebuyConfig must be used within a RebuyConfigProvider');\n }\n\n return context;\n};\n", "// ~/smart-cart/utils/debugLog.ts\n\n// TODO: Move this to npm-rebuy as a shared utility\n\n// Ensure window.REBUY_DEBUG_MODE can be augmented\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Window {\n REBUY_DEBUG_MODE?: boolean | string | string[];\n }\n}\n\nconst REBUY_DEBUG_GLOBAL_PREFIX = '[Rebuy Debug]';\nconst REBUY_DEBUG_KEYS_SEPARATOR = ',';\nconst LOCAL_STORAGE_DEBUG_KEY = 'REBUY_DEBUG_MODE';\n\ntype DebugSettings = {\n enabledKeys: Set<string>;\n globalEnable: boolean;\n};\n\nconst getDebugSettings = (): DebugSettings => {\n let settingsValue: boolean | string | string[] | null | undefined = undefined;\n\n // Prioritize window flag if set, allows runtime override\n if (typeof window !== 'undefined' && typeof window.REBUY_DEBUG_MODE !== 'undefined') {\n settingsValue = window.REBUY_DEBUG_MODE;\n } else {\n // localStorage, only if window flag not present\n try {\n if (typeof window !== 'undefined' && typeof localStorage !== 'undefined') {\n settingsValue = localStorage.getItem(LOCAL_STORAGE_DEBUG_KEY);\n }\n } catch (e) {\n // localStorage might be unavailable (e.g., SSR, security restrictions).\n // Silently fail, settingsValue remains undefined, will fall to default disabled state.\n // console.warn(`${REBUY_DEBUG_GLOBAL_PREFIX} Could not access localStorage for debug settings.`, e);\n }\n }\n\n if (settingsValue === true || settingsValue === 'true') {\n return { enabledKeys: new Set(), globalEnable: true };\n }\n\n if (settingsValue === false || settingsValue === 'false') {\n return { enabledKeys: new Set(), globalEnable: false };\n }\n\n if (typeof settingsValue === 'string' && settingsValue.length > 0) {\n const keys = settingsValue\n .split(REBUY_DEBUG_KEYS_SEPARATOR)\n .map((k) => k.trim())\n .filter(Boolean);\n\n return { enabledKeys: new Set(keys), globalEnable: false };\n }\n\n if (Array.isArray(settingsValue)) {\n const keys = settingsValue.map((k) => String(k).trim()).filter(Boolean);\n\n return { enabledKeys: new Set(keys), globalEnable: false };\n }\n\n return { enabledKeys: new Set(), globalEnable: false }; // Default: disabled\n};\n\nconst _isFeatureDebugActive = (key: string): boolean => {\n const { enabledKeys, globalEnable } = getDebugSettings();\n\n if (globalEnable) return true;\n\n return enabledKeys.has(key);\n};\n\nconst _isAnyDebugActive = (): boolean => {\n const { enabledKeys, globalEnable } = getDebugSettings();\n\n return globalEnable || enabledKeys.size > 0;\n};\n\n// Helper to generate consistent log prefixes for labels\nconst makeLabelWithPrefix = (baseKeyPrefix: string, subContext?: unknown): string => {\n if (typeof subContext === 'string' && subContext.trim() !== '') {\n return `${baseKeyPrefix}: ${subContext.trim()}`;\n }\n\n return baseKeyPrefix; // Only base key prefix if subContext is not a useful string\n};\n\n// --- Logger method factories ---\n\n// For: log, warn, error, info, debug, dir, dirxml, trace\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst createKeyedLogger = (consoleMethod: (...args: any[]) => void) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (key: string, ...args: any[]): void => {\n if (_isFeatureDebugActive(key)) {\n const baseKeyPrefix = `${REBUY_DEBUG_GLOBAL_PREFIX} (${key})`;\n consoleMethod(baseKeyPrefix, ...args);\n }\n };\n};\n\n// For: table\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst createKeyedTableLogger = () => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (key: string, data: any, properties?: readonly string[]): void => {\n if (_isFeatureDebugActive(key)) {\n const baseKeyPrefix = `${REBUY_DEBUG_GLOBAL_PREFIX} (${key})`;\n console.groupCollapsed(makeLabelWithPrefix(baseKeyPrefix, 'Table'));\n console.table(data, properties);\n console.groupEnd();\n }\n };\n};\n\n// For: group, groupCollapsed\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst createKeyedGroupLogger = (consoleMethod: (label?: any, ...data: any[]) => void) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (key: string, groupLabelArg?: any, ...data: any[]): void => {\n if (_isFeatureDebugActive(key)) {\n const baseKeyPrefix = `${REBUY_DEBUG_GLOBAL_PREFIX} (${key})`;\n\n if (typeof groupLabelArg === 'string' || typeof groupLabelArg === 'undefined' || groupLabelArg === null) {\n const finalGroupLabel = makeLabelWithPrefix(baseKeyPrefix, groupLabelArg as string | undefined);\n consoleMethod(finalGroupLabel, ...data);\n } else {\n // groupLabelArg is not a string (e.g. an object), pass it as a subsequent argument\n consoleMethod(baseKeyPrefix, groupLabelArg, ...data);\n }\n }\n };\n};\n\n// For: groupEnd, clear\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst createParameterlessLogger = (consoleMethod: () => void) => {\n return (): void => {\n if (_isAnyDebugActive()) {\n consoleMethod();\n }\n };\n};\n\n// For: count, countReset, time, timeEnd\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst createKeyedLabelLogger = (consoleMethod: (label?: string) => void, baseMethodName: string) => {\n return (key: string, label?: string): void => {\n if (_isFeatureDebugActive(key)) {\n const baseKeyPrefix = `${REBUY_DEBUG_GLOBAL_PREFIX} (${key})`;\n const fullLabel = makeLabelWithPrefix(baseKeyPrefix, label || baseMethodName);\n consoleMethod(fullLabel);\n }\n };\n};\n\n// For: timeLog\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst createKeyedTimeLogLogger = (consoleMethod: (label: string, ...data: any[]) => void) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (key: string, timerName: string, ...data: any[]): void => {\n if (_isFeatureDebugActive(key)) {\n const baseKeyPrefix = `${REBUY_DEBUG_GLOBAL_PREFIX} (${key})`;\n const fullTimerName = makeLabelWithPrefix(baseKeyPrefix, timerName);\n consoleMethod(fullTimerName, ...data);\n }\n };\n};\n\n// For: assert\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst createKeyedAssertLogger = (consoleMethod: (assertion: boolean, ...data: any[]) => void) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (key: string, assertion: boolean, ...messageArgs: any[]): void => {\n if (_isFeatureDebugActive(key)) {\n const baseKeyPrefix = `${REBUY_DEBUG_GLOBAL_PREFIX} (${key})`;\n const assertionContextMessage = makeLabelWithPrefix(baseKeyPrefix, 'Assertion');\n consoleMethod(assertion, assertionContextMessage, ...messageArgs);\n }\n };\n};\n\n/**\n * The main Rebuy debug logger object.\n * Provides familiar console methods, but conditional on Rebuy debug settings and feature keys.\n *\n * How to enable debugging:\n * 1. Global: Set `window.REBUY_DEBUG_MODE = true` or in localStorage `REBUY_DEBUG_MODE` to `'true'`.\n * This enables all logs from `rebuyDebugLog` regardless of key.\n * 2. Key-specific: Set `window.REBUY_DEBUG_MODE = ['cart', 'api']` (array of strings) or\n * in localStorage `REBUY_DEBUG_MODE` to `'cart,api'` (comma-separated string).\n * This enables logs only for the specified keys (e.g., `rebuyDebugLog.log('cart', ...)`).\n *\n * To disable, set the corresponding value to `false` or remove the localStorage item.\n */\nexport const rebuyDebugLog = {\n assert: createKeyedAssertLogger(console.assert),\n clear: createParameterlessLogger(console.clear),\n count: createKeyedLabelLogger(console.count, 'count'),\n countReset: createKeyedLabelLogger(console.countReset, 'countReset'),\n debug: createKeyedLogger(console.debug),\n\n dir: createKeyedLogger(console.dir),\n dirxml: createKeyedLogger(console.dirxml),\n error: createKeyedLogger(console.error),\n\n /**\n * Retrieves the current parsed debug settings.\n *\n * @returns {DebugSettings} An object containing `globalEnable` (boolean) and `enabledKeys` (Set<string>).\n */\n\n getSettings: (): DebugSettings => getDebugSettings(),\n\n group: createKeyedGroupLogger(console.group),\n groupCollapsed: createKeyedGroupLogger(console.groupCollapsed),\n groupEnd: createParameterlessLogger(console.groupEnd),\n\n info: createKeyedLogger(console.info),\n\n /**\n * Checks if any Rebuy debugging (global or any key) is active.\n * Useful for controlling parameter-less debug actions or general checks.\n *\n * @returns {boolean} True if any form of Rebuy debugging is active.\n */\n\n isAnyActive: (): boolean => _isAnyDebugActive(),\n\n /**\n * Checks if debugging is active for a specific feature key.\n * Considers both global debug mode and key-specific settings.\n *\n * @param {string} key - The debug key for the feature.\n * @returns {boolean} True if debugging is active for this key.\n */\n isKeyActive: (key: string): boolean => _isFeatureDebugActive(key),\n\n log: createKeyedLogger(console.log),\n table: createKeyedTableLogger(),\n time: createKeyedLabelLogger(console.time, 'time'),\n\n timeEnd: createKeyedLabelLogger(console.timeEnd, 'timeEnd'),\n timeLog: createKeyedTimeLogLogger(console.timeLog),\n trace: createKeyedLogger(console.trace),\n warn: createKeyedLogger(console.warn),\n};\n\n/**\n * Returns true if Rebuy debug mode is active.\n *\n * @deprecated Prefer using `rebuyDebugLog.isKeyActive(key)`, `rebuyDebugLog.isAnyActive()`, or `rebuyDebugLog.getSettings().globalEnable`.\n * Checks if Rebuy debug mode is active.\n * - If a `key` is provided, checks if that key is enabled OR if global debug is on.\n * - If no `key` is provided, checks ONLY if global debug mode is on (to maintain some backward compatibility with original intent).\n * @param {string} [key] - Optional. The debug key for a specific feature.\n * @returns {boolean} True if debug mode is enabled for the context.\n */\nexport const isRebuyDebugMode = (key?: string): boolean => {\n const { enabledKeys, globalEnable } = getDebugSettings();\n\n if (globalEnable) {\n return true;\n }\n\n // If a key is provided, check if it's in the enabled set (globalEnable is false here)\n if (key && enabledKeys.has(key)) {\n return true;\n }\n\n // If no key is provided and global debug is not on, return false.\n // This makes `isRebuyDebugMode()` without arguments specific to the global flag.\n return false;\n};\n", "import { RebuyClient } from '@rebuy/rebuy';\nimport type { RebuyConfig, RebuyResponse } from '~/types/rebuyCustom';\n\nexport const getRebuyConfig = async (storeDomain: string): Promise<RebuyConfig> => {\n try {\n const request = {\n parameters: { shop: storeDomain },\n url: `/api/v1/user/config`,\n };\n\n const { data: rebuy, ...response } = (await new RebuyClient('', undefined, storeDomain).getShieldedAsset(\n request.url,\n request.parameters\n )) as RebuyResponse;\n\n if (!rebuy?.shop) {\n throw new Error('Rebuy configuration is not properly set up - missing shop', { cause: response });\n }\n\n return rebuy;\n } catch (error: unknown) {\n const err = error as Error;\n console.warn('Error fetching Rebuy shop config');\n console.error(err, err.cause);\n throw err;\n }\n};\n", "import { createContext } from 'react';\n\nimport { type ContextParameters } from '~/types/rebuyCustom';\n\nexport type RebuyContextType = {\n contextParameters: ContextParameters;\n};\n\nexport const RebuyContext = createContext<RebuyContextType | null>(null);\n", "import { useEffect, useState } from 'react';\n\n/**\n * Hook to detect B/F (Back/Forward) cache restoration and provide a reset key\n * When the browser restores a page from B/F cache, this hook updates the reset key\n * which can be used to force remount components and reset their state\n */\nexport const useBFCacheReset = () => {\n const [resetKey, setResetKey] = useState(() => Date.now());\n\n useEffect(() => {\n const handlePageShow = (event: PageTransitionEvent) => {\n if (event.persisted) {\n // Page was restored from B/F cache - trigger reset\n console.log('[useBFCacheReset] B/F cache detected, triggering reset');\n setResetKey(Date.now());\n }\n };\n\n window.addEventListener('pageshow', handlePageShow);\n\n return () => window.removeEventListener('pageshow', handlePageShow);\n }, []);\n\n return resetKey;\n};\n", "// ~/smart-cart/context/SmartCartContext.tsx\nimport type {\n // Alias Storefront types to Hydrogen types from H-React for clarity where actions are concerned\n AttributeInput as HRAttributeInput,\n CartLineInput as HRCartLineInput,\n CartLineUpdateInput as HRCartLineUpdateInput,\n} from '@shopify/hydrogen-react/storefront-api-types';\n// eslint-disable-next-line import/order\nimport type { Cart as HydrogenStorefrontApiCart } from '@shopify/hydrogen/storefront-api-types';\nimport { isEqual } from 'lodash-es';\nimport { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';\nimport { useShallow } from 'zustand/react/shallow';\nimport { DebugKey } from '~/constants/debug';\n\nimport { RebuyContext } from '~/context/RebuyContext';\nimport { useTieredProgressBarStore, type TieredProgressBarStore } from '~/smart-cart/store/tieredProgressBarStore';\nimport type {\n StorefrontAttribute,\n StorefrontCartData,\n StorefrontCartItemInput,\n StorefrontCartLineUpdateInput,\n} from '~/smart-cart/types/rebuy-storefront-cart';\nimport type { SmartCartConfig } from '~/smart-cart/types/smart-cart';\nimport type { SmartCartComponentConfig, TieredProgressBarSettings } from '~/smart-cart/types/smart-cart-component';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport { mapHydrogenCartToStorefrontCartData } from '~/smart-cart/utils/mapHydrogenCartToStorefrontCartData';\nimport type { HydrogenReactCartActions } from '~/types/rebuyCustom';\n\n/*\n Considerations for Vanilla Hydrogen/Remix Path:\n\n - Fetcher Necessity: Since cart actions in Remix typically involve form submissions handled by action functions, components initiating these actions (CartItem, DiscountCodeInput, etc.) will likely need their own useFetcher() instance.\n - Context Actions Role: The context actions (addItem, updateItem, etc.) in the !isHydrogenReact path cannot directly perform the fetch. They serve mainly as placeholders or could potentially throw an error indicating a fetcher is required.\n - Shared Fetcher (Complex): Managing a single, shared fetcher within the SmartCartProvider is complex because multiple components might trigger actions concurrently or need different submission data/methods. This approach is generally discouraged.\n - UI State (isLoading, error): The UI should still react to isLoading and error from the context. In a Remix setup, the SmartCartProvider would need to get the fetcher.state and fetcher.data (for errors) from somewhere. This could involve:\n - Passing the fetcher down via context (possible but couples context tightly to Remix).\n - Having the RebuyProvider (consuming the root loader data and potentially a root fetcher) provide loading/error status to SmartCartProvider.\n - Recommendation: Prioritize the component-level useFetcher pattern for Remix actions. The SmartCartProvider would focus on providing cartData (from loader), config, and UI state (isVisible), while global isLoading/error might need to be sourced from a higher-level provider or context aware of the root layout's fetcher state.\n*/\n\n// --- Define the Combined Context Value Type ---\n// Note: Action return types are unions for potential Remix path flexibility,\n// but H-React implementations behave as void.\nexport type SmartCartContextValue = {\n addItem: (\n variantId: string,\n attributes?: StorefrontAttribute[],\n quantity?: number\n ) => void | Promise<StorefrontCartData | null>;\n addItems: (items: StorefrontCartItemInput[]) => void | Promise<StorefrontCartData | null>;\n apiKey: string;\n applyDiscountCodes: (codes: string[]) => void | Promise<StorefrontCartData | null>;\n cacheKey: string;\n cartData: StorefrontCartData | null;\n checkout: () => void;\n config: SmartCartConfig;\n /* Global Error State */\n error: string | null;\n getCartSubtotal: () => string;\n getComponentConfigById: (id: string) => SmartCartComponentConfig | undefined;\n getComponentConfigByType: <T extends SmartCartComponentConfig['type']>(\n type: T\n ) => Extract<SmartCartComponentConfig, { type: T }> | undefined;\n getItemCount: () => number;\n getTpbStore: () => TieredProgressBarStore;\n hideCart: () => void;\n hydrogenReactCartActions?: HydrogenReactCartActions;\n /** Indicates if the cart is busy (loading, updating, etc.) via H-React ops or TPB sync actions. */\n isCartBusy: boolean;\n /** Indicates if the cart is ready to be used initially. */\n isCartReady: boolean;\n isHydrogenReact: boolean;\n /** Global loading state */\n isLoading: boolean;\n isProgressBarLineItemMode: boolean;\n isVisible: boolean;\n removeItem: (lineId: string) => void | Promise<StorefrontCartData | null>;\n removeItems: (lineIds: string[]) => void | Promise<StorefrontCartData | null>;\n shopifyDomain: string;\n showCart: () => void;\n storefrontAccessToken: string;\n toggleCart: () => void;\n updateCartAttributes: (attributes: StorefrontAttribute[]) => void | Promise<StorefrontCartData | null>;\n updateCartNote: (note: string | null) => void | Promise<StorefrontCartData | null>;\n updateItem: (\n lineId: string,\n updates: Partial<Omit<StorefrontCartLineUpdateInput, 'id'> & { sellingPlanId?: string | null }>\n ) => void | Promise<StorefrontCartData | null>;\n updateItems: (\n updates: (StorefrontCartLineUpdateInput & { sellingPlanId?: string | null })[]\n ) => void | Promise<StorefrontCartData | null>;\n};\n\nconst SmartCartContext = createContext<SmartCartContextValue | null>(null);\n\nexport type SmartCartProviderProps = {\n apiKey: string;\n cacheKey: string;\n children?: ReactNode;\n config: SmartCartConfig;\n hydrogenCart: HydrogenStorefrontApiCart;\n shopifyDomain: string;\n storefrontAccessToken: string;\n};\n\n// Helper to map StorefrontAttribute[] to HRAttributeInput[]\nconst mapStorefrontAttributesToHRAttributes = (attributes?: StorefrontAttribute[] | null): HRAttributeInput[] => {\n if (!attributes) return [];\n\n return attributes\n .filter((attr): attr is { key: string; value: string } => typeof attr.key === 'string' && attr.value !== null) // Ensure key/value are strings (value can be empty string)\n .map((attr) => ({\n key: attr.key,\n value: attr.value, // Value is now confirmed string\n }));\n};\n\nexport const SmartCartProvider: React.FC<SmartCartProviderProps> = ({\n apiKey,\n cacheKey,\n children,\n config,\n hydrogenCart,\n shopifyDomain,\n storefrontAccessToken,\n}) => {\n const rebuyContext = useContext(RebuyContext);\n\n const [isVisible, setIsVisible] = useState(false);\n const showCart = useCallback(() => setIsVisible(true), []);\n const hideCart = useCallback(() => setIsVisible(false), []);\n const toggleCart = useCallback(() => setIsVisible((prev) => !prev), []);\n\n // --- Consume RebuyContext ---\n const { contextParameters, isHydrogenReact } = useMemo(() => {\n if (!rebuyContext) {\n return { contextParameters: null, isHydrogenReact: false };\n }\n\n return {\n contextParameters: rebuyContext.contextParameters,\n isHydrogenReact: rebuyContext.contextParameters.isHydrogenReact ?? false,\n };\n }, [rebuyContext]);\n\n const hReactActions = contextParameters?.hydrogenReactCartActions;\n const hReactStatus = contextParameters?.hydrogenReactCartStatus;\n const hReactError = contextParameters?.hydrogenReactCartError;\n\n // --- Reactive State Derivation ---\n const prevCartData = useRef<StorefrontCartData | null>(null);\n const mappedStorefrontCartData = useMemo(() => {\n const cartSource = hydrogenCart ?? contextParameters?.hydrogenCart;\n\n if (!cartSource) {\n rebuyDebugLog.log(\n DebugKey.SC_CTX,\n 'No cart source (direct prop or context.hydrogenCart) available for mapping.'\n );\n\n return null;\n }\n\n const cartData = mapHydrogenCartToStorefrontCartData(cartSource, contextParameters);\n\n if (!isEqual(prevCartData.current, cartData)) {\n rebuyDebugLog.groupCollapsed(\n DebugKey.SC_CTX,\n '%cCart data updated in SmartCartContext',\n 'color: white; background: purple'\n );\n rebuyDebugLog.log(DebugKey.SC_CTX, {\n newCartData: cartData,\n oldCartData: prevCartData.current,\n source: hydrogenCart ? 'direct_prop' : 'rebuy_context.hydrogenCart',\n });\n rebuyDebugLog.groupEnd();\n }\n\n prevCartData.current = cartData;\n\n return cartData;\n }, [hydrogenCart, contextParameters]);\n const isLoading = useMemo(() => {\n if (isHydrogenReact && hReactStatus) {\n // Hydrogen React provides status for ongoing operations\n return ['fetching', 'creating', 'updating'].includes(hReactStatus);\n }\n\n // Fallback: If context isn't ready, consider it loading\n return !rebuyContext || !contextParameters;\n }, [isHydrogenReact, hReactStatus, rebuyContext, contextParameters]);\n\n const error = useMemo(() => {\n if (isHydrogenReact && hReactError) {\n // Handle different error shapes from Hydrogen React\n if (typeof hReactError === 'string') return hReactError;\n\n if (hReactError instanceof Error) return hReactError.message;\n // Attempt to stringify other potential error objects/values\n try {\n return JSON.stringify(hReactError);\n } catch {\n return 'An unknown Hydrogen React cart error occurred.';\n }\n }\n\n // No error if not H-React or no error present\n return null;\n }, [isHydrogenReact, hReactError]);\n\n const isCartReady = useMemo(() => !!mappedStorefrontCartData, [mappedStorefrontCartData]);\n\n // --- Tiered Progress Bar Setup ---\n const tpbStoreInstance = useTieredProgressBarStore();\n const {\n activeBarConfig,\n cartData: tpbInternalCartData,\n cartSyncStatus,\n init: tpbInit,\n isCartReady: isTpbInternalCartReady,\n isManuallyDisabled,\n productFetchStatus,\n setCartData: tpbSetCartData,\n syncCartGifts: tpbSyncCartGifts,\n userActionStatus,\n } = tpbStoreInstance;\n\n // Subscribe to specific TPB states for isProcessingTPBGifts\n const { tpbCartSyncStatus, tpbUserActionStatus } = useTieredProgressBarStore(\n useShallow((state) => {\n // Log whenever this selector runs and what it sees\n rebuyDebugLog.log(DebugKey.SC_CTX_TPB_SELECTOR, 'SmartCartContext TPB Selector:', {\n cartSyncStatus: state.cartSyncStatus,\n userActionStatus: state.userActionStatus,\n });\n\n return {\n tpbCartSyncStatus: state.cartSyncStatus,\n tpbUserActionStatus: state.userActionStatus,\n };\n })\n );\n rebuyDebugLog.log(\n DebugKey.SC_CTX_TPB_SELECTOR,\n `tpbCartSyncStatus: ${tpbCartSyncStatus}, tpbUserActionStatus: ${tpbUserActionStatus}`\n );\n\n const isProcessingTPBGifts = useMemo(() => {\n return (\n tpbCartSyncStatus === 'syncing' ||\n tpbCartSyncStatus === 'awaiting_cart_update' ||\n tpbUserActionStatus === 'pending'\n );\n }, [tpbCartSyncStatus, tpbUserActionStatus]);\n\n const isCartBusy = useMemo(() => {\n return isLoading || isProcessingTPBGifts;\n }, [isLoading, isProcessingTPBGifts]);\n\n rebuyDebugLog.log(DebugKey.SC_CTX, 'isCartBusy state:', isCartBusy);\n\n const progressBarSettings = useMemo((): TieredProgressBarSettings | null => {\n const tpbComponentConfig = config?.components?.find((comp) => comp.type === 'tiered_progress_bar');\n\n return tpbComponentConfig?.settings ?? null;\n }, [config]);\n\n // TPB Init Effect\n useEffect(() => {\n if (progressBarSettings && isCartReady && shopifyDomain && storefrontAccessToken) {\n tpbInit(progressBarSettings, shopifyDomain, storefrontAccessToken);\n }\n }, [progressBarSettings, isCartReady, shopifyDomain, storefrontAccessToken, tpbInit]);\n\n // TPB Cart Data Sync Effect\n useEffect(() => {\n const currentTpbState = useTieredProgressBarStore.getState();\n const newTpbIsCartReady = isCartReady;\n\n if (\n !isEqual(currentTpbState.cartData, mappedStorefrontCartData) ||\n currentTpbState.isCartReady !== newTpbIsCartReady\n ) {\n rebuyDebugLog.log(DebugKey.SC_CTX, 'Updating TPB store with cart data:', {\n cartData: mappedStorefrontCartData,\n isCartReady: newTpbIsCartReady,\n });\n tpbSetCartData(mappedStorefrontCartData, newTpbIsCartReady);\n }\n }, [mappedStorefrontCartData, isCartReady, tpbSetCartData]);\n\n const isProgressBarLineItemMode = useTieredProgressBarStore(\n (state) => state.activeBarConfig?.use_line_item_mode ?? false\n );\n\n // --- Cart Actions Implementation (Refactored for Reactivity) ---\n const logRemixWarning = (actionName: string) => {\n rebuyDebugLog.warn(\n DebugKey.SC_CTX,\n `${actionName} called in non-Hydrogen React context. Requires component-level fetcher implementation.`\n );\n\n // Return a resolved promise to satisfy the union type, though behavior is warning only.\n return Promise.resolve(null);\n };\n\n // --- ACTION: addItems ---\n const addItems = useCallback(\n (items: StorefrontCartItemInput[]) => {\n if (isHydrogenReact && hReactActions?.linesAdd) {\n const linesToAdd: HRCartLineInput[] = items.map((item) => ({\n // Map attributes within the item before passing to H-React\n attributes: mapStorefrontAttributesToHRAttributes(item.attributes),\n merchandiseId: item.merchandiseId,\n quantity: item.quantity,\n }));\n rebuyDebugLog.log(DebugKey.SC_CTX_H_REACT, 'Dispatching H-React linesAdd:', linesToAdd);\n hReactActions.linesAdd(linesToAdd); // Fire-and-forget\n // VOID return for H-React path\n } else if (!isHydrogenReact) {\n // Needs fetcher in consuming component\n return logRemixWarning('addItems');\n }\n },\n [isHydrogenReact, hReactActions]\n );\n\n // --- ACTION: addItem ---\n const addItem = useCallback(\n (variantId: string, attributes?: StorefrontAttribute[], quantity = 1) => {\n // Map input attributes immediately\n const mappedAttributes = mapStorefrontAttributesToHRAttributes(attributes);\n\n // Create the item object using the correctly typed attributes\n const item: StorefrontCartItemInput = {\n attributes: mappedAttributes, // Use mapped attributes\n merchandiseId: variantId,\n quantity,\n };\n\n // Call the refactored addItems\n // The return type handling (void | Promise) is managed within addItems\n return addItems([item]);\n },\n [addItems] // Dependency is the refactored addItems\n );\n\n // --- ACTION: updateItems ---\n const updateItems = useCallback(\n (updates: (StorefrontCartLineUpdateInput & { sellingPlanId?: string | null })[]) => {\n if (isHydrogenReact && hReactActions?.linesUpdate) {\n const linesToUpdate: HRCartLineUpdateInput[] = updates.map((update) => ({\n attributes: mapStorefrontAttributesToHRAttributes(update.attributes),\n id: update.id,\n merchandiseId: update.merchandiseId,\n quantity: update.quantity,\n sellingPlanId: update.sellingPlanId,\n }));\n rebuyDebugLog.log(DebugKey.SC_CTX_H_REACT, 'Dispatching H-React linesUpdate:', linesToUpdate);\n hReactActions.linesUpdate(linesToUpdate); // Fire-and-forget\n // VOID return for H-React path\n } else if (!isHydrogenReact) {\n return logRemixWarning('updateItems');\n }\n },\n [isHydrogenReact, hReactActions]\n );\n\n // --- ACTION: updateItem ---\n const updateItem = useCallback(\n (\n lineId: string,\n updates: Partial<Omit<StorefrontCartLineUpdateInput, 'id'> & { sellingPlanId?: string | null }>\n ) => {\n const updatePayload: StorefrontCartLineUpdateInput & { sellingPlanId?: string | null } = {\n id: lineId,\n ...updates,\n };\n\n // Call the refactored updateItems\n return updateItems([updatePayload]);\n },\n [updateItems]\n );\n\n // --- ACTION: removeItems ---\n const removeItems = useCallback(\n (lineIds: string[]) => {\n if (isHydrogenReact && hReactActions?.linesRemove) {\n rebuyDebugLog.log(DebugKey.SC_CTX_H_REACT, 'Dispatching H-React linesRemove:', lineIds);\n hReactActions.linesRemove(lineIds); // Fire-and-forget\n // VOID return for H-React path\n } else if (!isHydrogenReact) {\n return logRemixWarning('removeItems');\n }\n },\n [isHydrogenReact, hReactActions]\n );\n\n // --- ACTION: removeItem ---\n const removeItem = useCallback((lineId: string) => removeItems([lineId]), [removeItems]);\n\n // --- ACTION: applyDiscountCodes ---\n const applyDiscountCodes = useCallback(\n (codes: string[]) => {\n if (isHydrogenReact && hReactActions?.discountCodesUpdate) {\n rebuyDebugLog.log(DebugKey.SC_CTX_H_REACT, 'Dispatching H-React discountCodesUpdate:', codes);\n hReactActions.discountCodesUpdate(codes); // Fire-and-forget\n // VOID return for H-React path\n } else if (!isHydrogenReact) {\n return logRemixWarning('applyDiscountCodes');\n }\n },\n [isHydrogenReact, hReactActions]\n );\n\n // --- ACTION: updateCartAttributes ---\n const updateCartAttributes = useCallback(\n (attributes: StorefrontAttribute[]) => {\n if (isHydrogenReact && hReactActions?.cartAttributesUpdate) {\n const attrsToUpdate: HRAttributeInput[] = mapStorefrontAttributesToHRAttributes(attributes);\n rebuyDebugLog.log(DebugKey.SC_CTX_H_REACT, 'Dispatching H-React cartAttributesUpdate:', attrsToUpdate);\n hReactActions.cartAttributesUpdate(attrsToUpdate); // Fire-and-forget\n // VOID return for H-React path\n } else if (!isHydrogenReact) {\n return logRemixWarning('updateCartAttributes');\n }\n },\n [isHydrogenReact, hReactActions]\n );\n\n // --- ACTION: updateCartNote ---\n const updateCartNote = useCallback(\n (note: string | null) => {\n if (isHydrogenReact && hReactActions?.noteUpdate) {\n const noteToUpdate = note ?? '';\n rebuyDebugLog.log(DebugKey.SC_CTX_H_REACT, 'Dispatching H-React noteUpdate:', noteToUpdate);\n hReactActions.noteUpdate(noteToUpdate); // Fire-and-forget\n // VOID return for H-React path\n } else if (!isHydrogenReact) {\n return logRemixWarning('updateCartNote');\n }\n },\n [isHydrogenReact, hReactActions]\n );\n\n // --- ACTION: checkout ---\n const checkout = useCallback(() => {\n const checkoutUrl = mappedStorefrontCartData?.checkoutUrl;\n\n if (checkoutUrl) {\n window.location.href = checkoutUrl;\n } else {\n rebuyDebugLog.error(\n DebugKey.SC_CTX,\n 'Checkout failed: Checkout URL not available.',\n mappedStorefrontCartData\n );\n }\n }, [mappedStorefrontCartData]);\n\n // --- TPB Gift Sync Effect ---\n useEffect(() => {\n const conditions = {\n activeBarConfigPresent: !!activeBarConfig,\n cartDataIsEqual: isEqual(tpbInternalCartData, mappedStorefrontCartData),\n cartSyncStatusIsIdle: cartSyncStatus === 'idle',\n isTpbInternalCartReady,\n notIsManuallyDisabled: !isManuallyDisabled,\n productFetchStatusIsSuccess: productFetchStatus === 'success',\n tpbInternalCartDataNotNull: tpbInternalCartData !== null,\n userActionStatusIsIdle: userActionStatus === 'idle',\n };\n const allConditionsMet = Object.values(conditions).every(Boolean);\n\n if (allConditionsMet) {\n rebuyDebugLog.log(\n DebugKey.SC_CTX_TPB_SYNC,\n 'syncCartGifts trigger: Conditions MET. Calling tpbSyncCartGifts(). Conditions:',\n conditions\n );\n tpbSyncCartGifts();\n } else {\n rebuyDebugLog.log(\n DebugKey.SC_CTX_TPB_SYNC,\n 'syncCartGifts trigger: SKIPPING. Conditions NOT MET. Conditions:',\n conditions\n );\n }\n }, [\n isTpbInternalCartReady,\n productFetchStatus,\n activeBarConfig,\n isManuallyDisabled,\n tpbInternalCartData,\n cartSyncStatus,\n userActionStatus,\n tpbSyncCartGifts,\n mappedStorefrontCartData,\n ]);\n // --- Helper Functions ---\n const getItemCount = useCallback(() => mappedStorefrontCartData?.totalQuantity ?? 0, [mappedStorefrontCartData]);\n const getCartSubtotal = useCallback(\n () => mappedStorefrontCartData?.cost?.subtotalAmount?.amount ?? '0.00',\n [mappedStorefrontCartData]\n );\n const getComponentConfigByType = useCallback(\n <T extends SmartCartComponentConfig['type']>(type: T) =>\n config?.components?.find((comp) => comp.type === type) as\n | Extract<SmartCartComponentConfig, { type: T }>\n | undefined,\n [config?.components]\n );\n const getComponentConfigById = useCallback(\n (id: string) => config?.components?.find((comp) => comp.component_id === id),\n [config?.components]\n );\n\n // --- Provide Combined Context Value ---\n const combinedValue = useMemo<SmartCartContextValue>(\n () => ({\n addItem,\n addItems,\n apiKey,\n applyDiscountCodes,\n cacheKey,\n cartData: mappedStorefrontCartData,\n checkout,\n config,\n error,\n getCartSubtotal,\n getComponentConfigById,\n getComponentConfigByType,\n getItemCount,\n getTpbStore: () => tpbStoreInstance,\n hideCart,\n hydrogenReactCartActions: hReactActions,\n isCartBusy,\n isCartReady,\n isHydrogenReact,\n isLoading,\n isProgressBarLineItemMode,\n isVisible,\n removeItem,\n removeItems,\n shopifyDomain,\n showCart,\n storefrontAccessToken,\n toggleCart,\n updateCartAttributes,\n updateCartNote,\n updateItem,\n updateItems,\n }),\n [\n addItem,\n addItems,\n apiKey,\n applyDiscountCodes,\n cacheKey,\n mappedStorefrontCartData,\n checkout,\n config,\n error,\n getCartSubtotal,\n getComponentConfigById,\n getComponentConfigByType,\n getItemCount,\n tpbStoreInstance,\n hideCart,\n hReactActions,\n isCartBusy,\n isCartReady,\n isHydrogenReact,\n isLoading,\n isProgressBarLineItemMode,\n isVisible,\n removeItem,\n removeItems,\n shopifyDomain,\n showCart,\n storefrontAccessToken,\n toggleCart,\n updateCartAttributes,\n updateCartNote,\n updateItem,\n updateItems,\n ]\n );\n\n return <SmartCartContext.Provider value={combinedValue}>{children}</SmartCartContext.Provider>;\n};\n\n// Keep track if warning was logged to avoid spamming console\nlet warningLogged = false;\n\n// --- The Combined Hook for Consumption ---\nexport const useSmartCart = (): SmartCartContextValue => {\n const context = useContext(SmartCartContext);\n\n // Check if the context value is the default/undefined value\n if (context === undefined || context === null) {\n if (!warningLogged) {\n console.warn(\n 'useSmartCart hook called, but the SmartCartProvider is not available in the component tree. ' +\n 'This might happen if \"enableSmartCart\" is set to false or if prerequisites were not met. ' +\n 'Smart Cart features will be disabled for this component.'\n );\n warningLogged = true; // Log only once\n }\n\n // Return a \"null\" or default version of the context shape\n // so components using the hook don't crash when destructuring\n const warn = () =>\n console.warn(\n 'SmartCart operation attempted, but no SmartCartProvider was found in the component hierarchy. ' +\n 'This may occur if \"enableSmartCart\" is disabled or if required configuration is missing. ' +\n 'Smart Cart functionality is unavailable for this component.'\n );\n\n return {\n addItem: () => warn(),\n addItems: () => warn(),\n apiKey: '',\n applyDiscountCodes: () => warn(),\n cacheKey: '',\n cartData: null,\n checkout: () => warn(),\n config: null,\n error: null,\n getCartSubtotal: () => '0.00',\n getComponentConfigById: () => undefined,\n getComponentConfigByType: () => undefined,\n getItemCount: () => 0,\n getTpbStore: () => null,\n hideCart: () => warn(),\n isCartBusy: false,\n isCartReady: false,\n isHydrogenReact: false,\n isLoading: false,\n isProgressBarLineItemMode: false,\n isVisible: false,\n removeItem: () => warn(),\n removeItems: () => warn(),\n shopifyDomain: '',\n showCart: () => warn(),\n storefrontAccessToken: '',\n toggleCart: () => warn(),\n updateCartAttributes: () => warn(),\n updateCartNote: () => warn(),\n updateItem: () => warn(),\n updateItems: () => warn(),\n } as unknown as SmartCartContextValue;\n }\n\n return context;\n};\n", "// ~/smart-cart/store/tieredProgressBarStore.ts\nimport { flattenConnection } from '@shopify/hydrogen';\nimport type { CartLineInput as HRCartLineInput } from '@shopify/hydrogen-react/storefront-api-types';\nimport type { CartLine } from '@shopify/hydrogen/storefront-api-types'; // eslint-disable-line import/order\nimport { isEqual } from 'lodash-es';\nimport { create } from 'zustand';\nimport { DebugKey } from '~/constants/debug';\n\nimport {\n calculateCurrentProgressBarSubtotal,\n checkHasFreeShippingOnSubscription,\n checkIsTierReached,\n getDeclineKey,\n getNumericIdFromGid,\n updateDeclinedCache,\n} from '~/smart-cart/components/TieredProgressBar/progressBarUtils';\nimport {\n TieredProgressBarGiftStatus as GiftStatus,\n type TieredProgressBar,\n type TieredProgressBarCachedGiftData,\n type TieredProgressBarFetchedProductData,\n type TieredProgressBarQualifiedGiftState,\n type TieredProgressBarSettings,\n TieredProgressBarTierType,\n} from '~/smart-cart/components/TieredProgressBar/types';\nimport { RebuyLineItemAttribution, SessionStorageKey } from '~/smart-cart/constants';\nimport type { StorefrontAttribute, StorefrontCartData } from '~/smart-cart/types/rebuy-storefront-cart';\nimport { isTieredProgressBarGiftItem } from '~/smart-cart/utils/cartItemUtils';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport { safeJsonParse } from '~/smart-cart/utils/safeJsonParse';\n\nexport type TieredProgressBarStoreState = {\n _addItemsImpl: ((items: HRCartLineInput[]) => void) | null;\n _lastFetchedBarId: string | null;\n _removeItemsImpl: ((lineIds: string[]) => void) | null;\n _shopifyDomain: string;\n _storefrontAccessToken: string;\n activeBarConfig: TieredProgressBar | null;\n cartData: StorefrontCartData | null;\n cartSyncError: string | null;\n cartSyncStatus: 'idle' | 'syncing' | 'success' | 'error' | 'awaiting_cart_update';\n currentSubtotal: number;\n declinedGiftMap: Record<string, boolean>;\n fetchedProductMap: Map<number, TieredProgressBarFetchedProductData>;\n giftStates: Map<string, TieredProgressBarQualifiedGiftState>;\n hasFreeShippingOnSubscription: boolean;\n initializationStatus: 'idle' | 'pending' | 'complete';\n isCartReady: boolean;\n isManuallyDisabled: boolean;\n lastErrorTimestamp: number;\n productFetchError: string | null;\n productFetchStatus: 'idle' | 'loading' | 'success' | 'error';\n settings: TieredProgressBarSettings | null;\n userActionError: { message: string; tierId: string } | null;\n /* Prevent fetching the same bar multiple times */\n userActionStatus: 'idle' | 'pending' | 'error';\n};\n\nexport type TieredProgressBarStoreActions = {\n /** Clears any active user action error. */\n clearUserActionError: () => void;\n /** Manually disables the progress bar. */\n disableBar: () => void;\n /** Manually enables the progress bar if it was disabled. */\n enableBar: () => void;\n /** Fetches product data for gift tiers from Shopify Storefront API. Caches results in session storage. */\n fetchProducts: () => Promise<void>;\n /**\n * Handles user action to add or re-add a gift (if previously declined).\n * For single-variant gifts, adds to cart. For multi-variant, undeclines and shows selector.\n */\n handleAddOrReAddGift: (tierId: string) => void;\n /**\n * Handles user action to remove a gift from the cart and mark it as declined for the current tier.\n */\n handleRemoveGift: (tierId: string) => void;\n /**\n * Handles user selection of a gift variant.\n * Adds the selected variant to the cart and removes any existing gift from the same tier.\n */\n handleSelectVariant: (tierId: string, variantGid: string) => void;\n /** Initializes the store with settings and Shopify connection details. */\n init: (settings: TieredProgressBarSettings, shopifyDomain: string, storefrontAccessToken: string) => Promise<void>;\n /**\n * Recalculates derived state based on current cart data, settings, and fetched products.\n * This includes subtotal, tier statuses, gift states, etc.\n * Typically called internally after cart updates or product fetches.\n */\n recalculateState: () => void;\n /** Sets the cart data and readiness state, usually called when the main cart context updates. */\n setCartData: (cartData: StorefrontCartData | null, isCartReady: boolean) => void;\n /** Sets the internal submit functions for cart actions. */\n setSubmitFunctions: (\n addItemsImpl: (items: HRCartLineInput[]) => void,\n removeItemsImpl: (lineIds: string[]) => void\n ) => void;\n /**\n * Synchronizes gifts in the cart with the calculated qualified gifts.\n * Automatically adds/removes gift items based on tier reachability and availability.\n */\n syncCartGifts: () => Promise<void>;\n};\n\nexport type TieredProgressBarStore = TieredProgressBarStoreState & TieredProgressBarStoreActions;\n\n// --- Initial State ---\nconst initialStoreState: TieredProgressBarStoreState = {\n _addItemsImpl: null,\n _lastFetchedBarId: null,\n _removeItemsImpl: null,\n _shopifyDomain: '',\n _storefrontAccessToken: '',\n activeBarConfig: null,\n cartData: null,\n cartSyncError: null,\n cartSyncStatus: 'idle',\n currentSubtotal: 0,\n declinedGiftMap: {},\n fetchedProductMap: new Map(),\n giftStates: new Map(),\n hasFreeShippingOnSubscription: false,\n initializationStatus: 'idle',\n isCartReady: false,\n isManuallyDisabled: false,\n lastErrorTimestamp: 0,\n productFetchError: null,\n productFetchStatus: 'idle',\n settings: null,\n userActionError: null,\n userActionStatus: 'idle',\n};\n\n// --- Store Creation ---\nexport const useTieredProgressBarStore = create<TieredProgressBarStore>((set, get) => ({\n ...initialStoreState,\n clearUserActionError: () => {\n const currentState = get();\n\n if (currentState.userActionError || currentState.userActionStatus !== 'idle') {\n set({ userActionError: null, userActionStatus: 'idle' });\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, 'User action error cleared.');\n }\n },\n\n disableBar: () => {\n const currentState = get();\n const updates: Partial<TieredProgressBarStoreState> = {};\n let hasChanges = false;\n\n if (!currentState.isManuallyDisabled) {\n updates.isManuallyDisabled = true;\n hasChanges = true;\n }\n\n if (currentState.giftStates.size > 0) {\n updates.giftStates = new Map();\n hasChanges = true;\n }\n\n if (currentState.currentSubtotal !== 0) {\n updates.currentSubtotal = 0;\n hasChanges = true;\n }\n\n if (hasChanges) {\n set(updates);\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[disableBar] Bar disabled. Relevant states cleared/reset.');\n } else {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n '[disableBar] Bar already effectively disabled or no state changes needed.'\n );\n }\n get().recalculateState();\n },\n\n enableBar: () => {\n if (get().isManuallyDisabled) {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[enableBar] Enabling bar.');\n set({ isManuallyDisabled: false });\n\n if (\n get().activeBarConfig &&\n get().productFetchStatus !== 'success' &&\n get()._lastFetchedBarId !== get().activeBarConfig?.id\n ) {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[enableBar] Triggering product fetch as bar is enabled.');\n get().fetchProducts();\n } else {\n get().recalculateState();\n }\n } else {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[enableBar] Bar already enabled.');\n }\n },\n\n fetchProducts: async () => {\n const { _lastFetchedBarId, _shopifyDomain, _storefrontAccessToken, activeBarConfig, isManuallyDisabled } =\n get();\n\n if (get().productFetchStatus === 'loading') {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[fetchProducts] Already loading. Skipping.');\n\n return;\n }\n\n if (!activeBarConfig || isManuallyDisabled || !_shopifyDomain || !_storefrontAccessToken) {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[fetchProducts] Preconditions not met. Skipping.');\n\n return;\n }\n\n if (_lastFetchedBarId === activeBarConfig.id && get().productFetchStatus === 'success') {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[fetchProducts] Products already fetched for bar ID: ${activeBarConfig.id}.`\n );\n\n if (get().isCartReady) get().recalculateState();\n\n return;\n }\n const giftTiers = activeBarConfig.tiers.filter((t) => t.type === TieredProgressBarTierType.PRODUCT);\n const neededLegacyIds = Array.from(\n new Set(giftTiers.flatMap((t) => t.products?.map((p) => p.product_id) ?? []))\n );\n\n if (neededLegacyIds.length === 0) {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[fetchProducts] No gift products to fetch for bar ID: ${activeBarConfig.id}.`\n );\n\n set({\n _lastFetchedBarId: activeBarConfig.id,\n declinedGiftMap: {},\n fetchedProductMap: new Map(),\n productFetchStatus: 'success',\n });\n\n if (get().isCartReady) get().recalculateState();\n\n return;\n }\n set({ productFetchError: null, productFetchStatus: 'loading' });\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[fetchProducts] Starting product fetch for Bar ID: ${activeBarConfig.id}, Product IDs:`,\n neededLegacyIds\n );\n let combinedProductData: TieredProgressBarFetchedProductData[] = [];\n let loadedDeclinedMap: Record<string, boolean> = {};\n let idsToFetch = [...neededLegacyIds];\n let fetchError: string | null = null;\n try {\n const CACHE_DURATION_MS = 15 * 60 * 1000;\n const cachedDataString = sessionStorage.getItem(SessionStorageKey.TIERED_PROGRESS_BAR_GIFT_DATA);\n const cachedStoreData: TieredProgressBarCachedGiftData | null = safeJsonParse(cachedDataString);\n const isCacheValid = cachedStoreData && Date.now() - cachedStoreData.timestamp < CACHE_DURATION_MS;\n\n if (isCacheValid && cachedStoreData) {\n const cachedMap = new Map(cachedStoreData.products.map((p) => [getNumericIdFromGid(p.id), p]));\n idsToFetch = neededLegacyIds.filter((id) => !cachedMap.has(id));\n combinedProductData = cachedStoreData.products.filter((p) =>\n neededLegacyIds.includes(getNumericIdFromGid(p.id))\n );\n loadedDeclinedMap = cachedStoreData.declined ?? {};\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[fetchProducts] Cache ${idsToFetch.length === 0 ? 'hit for all products.' : `hit for some products. Fetching remaining: ${idsToFetch.join(', ')}`}`\n );\n } else {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[fetchProducts] Cache invalid or empty. Fetching all: ${idsToFetch.join(', ')}`\n );\n }\n\n if (idsToFetch.length > 0) {\n const productGids = idsToFetch.map((id) => `gid://shopify/Product/${id}`);\n const graphqlQuery = `query getProductsByIds($ids: [ID!]!) { nodes(ids: $ids) { ... on Product { id title handle tags images(first: 1) { edges { node { url altText } } } variants(first: 30) { edges { node { id title sku availableForSale price { amount currencyCode } compareAtPrice { amount currencyCode } selectedOptions { name value } image { url altText } } } } } } }`;\n const response = await fetch(`https://${_shopifyDomain}/api/2025-01/graphql.json`, {\n body: JSON.stringify({ query: graphqlQuery, variables: { ids: productGids } }),\n headers: {\n 'Content-Type': 'application/json',\n 'X-Shopify-Storefront-Access-Token': _storefrontAccessToken,\n },\n method: 'POST',\n });\n\n if (!response.ok) throw new Error(`GraphQL fetch failed: ${response.status} ${response.statusText}`);\n const json = await response.json();\n\n if (json.errors) throw new Error(`GraphQL errors: ${JSON.stringify(json.errors)}`);\n const fetchedNodes = (json.data?.nodes ?? []).filter(Boolean) as TieredProgressBarFetchedProductData[];\n const fetchedMap = new Map(fetchedNodes.map((p) => [getNumericIdFromGid(p.id), p]));\n const existingMap = new Map(combinedProductData.map((p) => [getNumericIdFromGid(p.id), p]));\n fetchedMap.forEach((value, key) => existingMap.set(key, value));\n combinedProductData = Array.from(existingMap.values());\n }\n sessionStorage.setItem(\n SessionStorageKey.TIERED_PROGRESS_BAR_GIFT_DATA,\n JSON.stringify({ declined: loadedDeclinedMap, products: combinedProductData, timestamp: Date.now() })\n );\n } catch (err) {\n fetchError = err instanceof Error ? err.message : 'Unknown product fetch error.';\n }\n const currentStoreState = get();\n\n if (fetchError) {\n if (\n currentStoreState.productFetchStatus !== 'error' ||\n currentStoreState.productFetchError !== fetchError\n ) {\n set({ _lastFetchedBarId: null, productFetchError: fetchError, productFetchStatus: 'error' });\n }\n } else {\n const finalProductMapCandidate = new Map(combinedProductData.map((p) => [getNumericIdFromGid(p.id), p]));\n const mergedDeclinedMapCandidate = { ...loadedDeclinedMap, ...currentStoreState.declinedGiftMap };\n const updates: Partial<TieredProgressBarStoreState> = { productFetchStatus: 'success' };\n let hasChanges = currentStoreState.productFetchStatus !== 'success';\n\n if (!isEqual(currentStoreState.fetchedProductMap, finalProductMapCandidate)) {\n updates.fetchedProductMap = finalProductMapCandidate;\n hasChanges = true;\n }\n\n if (!isEqual(currentStoreState.declinedGiftMap, mergedDeclinedMapCandidate)) {\n updates.declinedGiftMap = mergedDeclinedMapCandidate;\n hasChanges = true;\n }\n\n if (currentStoreState._lastFetchedBarId !== activeBarConfig.id) {\n updates._lastFetchedBarId = activeBarConfig.id;\n hasChanges = true;\n }\n\n if (hasChanges) set(updates);\n\n if (get().isCartReady) get().recalculateState();\n }\n },\n\n handleAddOrReAddGift: (tierId) => {\n const state = get();\n const { _addItemsImpl, userActionStatus: initialUserActionStatus } = state;\n\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] BEGIN for tier ${tierId}. Initial userActionStatus: ${initialUserActionStatus}`\n );\n\n if (!_addItemsImpl) {\n rebuyDebugLog.error(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] _addItemsImpl not set. Cannot add gift for tier ${tierId}.`\n );\n\n return;\n }\n\n if (state.userActionStatus === 'pending' || state.productFetchStatus !== 'success') {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] Action blocked (userActionStatus: ${state.userActionStatus}, productFetchStatus: ${state.productFetchStatus}) for tier ${tierId}`\n );\n\n return;\n }\n const giftState = state.giftStates.get(tierId);\n\n if (!giftState || !giftState.isReached || giftState.availableChoices.length === 0) {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] Gift not available or tier not reached for ${tierId}. State:`,\n giftState\n );\n set({\n lastErrorTimestamp: Date.now(),\n userActionError: { message: 'Gift unavailable or tier not reached', tierId },\n userActionStatus: 'error',\n });\n\n return;\n }\n\n // Set to pending for all cases initially\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] BEFORE setting userActionStatus to 'pending'. Current: ${get().userActionStatus}`\n );\n set({ userActionError: null, userActionStatus: 'pending' });\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] AFTER setting userActionStatus to 'pending'. Current: ${get().userActionStatus}`\n );\n\n const declineKey = getDeclineKey(tierId, giftState.legacyProductId);\n const wasDeclined = state.declinedGiftMap[declineKey] ?? false;\n\n if (wasDeclined) {\n const nextDeclinedMap = { ...state.declinedGiftMap };\n delete nextDeclinedMap[declineKey];\n set({ declinedGiftMap: nextDeclinedMap }); // This set can be batched\n updateDeclinedCache(nextDeclinedMap);\n\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] Undeclined gift for tier ${tierId}. Current userActionStatus: ${get().userActionStatus}`\n );\n }\n\n // --- Multi-variant path ---\n if (giftState.availableChoices.length > 1) {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] Multi-variant gift for tier ${tierId}. Undeclined. Recalculating state to show select. Setting userActionStatus back to 'idle'.`\n );\n // For multi-variant, the \"action\" is just to undecline and show the selector.\n // No Shopify cart operation is dispatched yet.\n // So, we can reset userActionStatus to 'idle' here to allow selection.\n // recalculateState() will update the gift's displayStatus to NEEDS_SELECTION.\n get().recalculateState();\n set({ userActionStatus: 'idle' }); // Reset to idle as the immediate \"re-add\" action is complete (it was just an undecline)\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] Multi-variant gift flow complete. userActionStatus is now: ${get().userActionStatus}`\n );\n\n return;\n }\n\n // --- Single variant gift path ---\n // (If it wasn't declined, and it's single-variant, this implies it's a fresh add,\n // though syncCartGifts usually handles fresh adds. This path mostly covers re-adding a declined single-variant gift.)\n if (giftState.availableChoices.length === 1) {\n const variantToAdd = giftState.availableChoices[0];\n const itemToAdd: HRCartLineInput = {\n attributes: [\n { key: '_source', value: 'Rebuy' },\n { key: '_attribution', value: RebuyLineItemAttribution.TIERED_PROGRESS_BAR },\n { key: '_tier', value: tierId },\n ],\n merchandiseId: variantToAdd.id,\n quantity: 1,\n };\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] BEFORE _addItemsImpl for single-variant gift. Current userActionStatus: ${get().userActionStatus}`\n );\n _addItemsImpl([itemToAdd]); // Fire-and-forget H-React action\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] AFTER _addItemsImpl. Dispatched addItems. Current userActionStatus: ${get().userActionStatus}. Waiting for cart update to reset userActionStatus via setCartData.`\n );\n\n // userActionStatus remains 'pending' and will be reset by setCartData when the Shopify update arrives.\n return;\n }\n\n // Fallback: Should not be reached if availableChoices checks are correct\n // but if it does, reset status if nothing happened.\n rebuyDebugLog.warn(\n DebugKey.SC_TPB_STORE,\n `[handleAddOrReAddGift] Reached end of function unexpectedly for tier ${tierId}. Resetting userActionStatus to 'idle'.`\n );\n set({ userActionStatus: 'idle' });\n },\n\n handleRemoveGift: (tierId) => {\n const state = get();\n const { _removeItemsImpl, userActionStatus: initialUserActionStatus } = state;\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleRemoveGift] BEGIN for tier ${tierId}. Initial userActionStatus: ${initialUserActionStatus}`\n );\n\n if (!_removeItemsImpl) {\n rebuyDebugLog.error(\n DebugKey.SC_TPB_STORE,\n `[handleRemoveGift] _removeItemsImpl not set. Cannot remove gift for tier ${tierId}.`\n );\n\n return;\n }\n\n if (state.userActionStatus === 'pending' || state.productFetchStatus !== 'success') {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleRemoveGift] Action blocked (userActionStatus: ${state.userActionStatus}, productFetchStatus: ${state.productFetchStatus}) for tier ${tierId}`\n );\n\n return;\n }\n\n const giftState = state.giftStates.get(tierId);\n\n if (!giftState?.legacyProductId) {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleRemoveGift] No gift state or legacyProductId for tier ${tierId}`\n );\n set({\n lastErrorTimestamp: Date.now(),\n userActionError: { message: 'Gift state invalid', tierId },\n userActionStatus: 'error',\n });\n\n return;\n }\n\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleRemoveGift] BEFORE setting userActionStatus to 'pending'. Current: ${get().userActionStatus}`\n );\n set({ userActionError: null, userActionStatus: 'pending' });\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleRemoveGift] AFTER setting userActionStatus to 'pending'. Current: ${get().userActionStatus}`\n );\n\n const declineKey = getDeclineKey(tierId, giftState.legacyProductId);\n\n if (!(state.declinedGiftMap[declineKey] ?? false)) {\n const nextDeclinedMap = { ...state.declinedGiftMap, [declineKey]: true };\n set({ declinedGiftMap: nextDeclinedMap });\n updateDeclinedCache(nextDeclinedMap);\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleRemoveGift] Declined gift for tier ${tierId}. Current userActionStatus: ${get().userActionStatus}`\n );\n }\n\n const cartLines = state.cartData?.lines ? flattenConnection(state.cartData.lines) : [];\n const lineToRemoveId = cartLines.find((line) =>\n line.attributes?.some((attr) => attr.key === '_tier' && attr.value === tierId)\n )?.id;\n\n if (lineToRemoveId) {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleRemoveGift] BEFORE _removeItemsImpl. Current userActionStatus: ${get().userActionStatus}`\n );\n _removeItemsImpl([lineToRemoveId]);\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleRemoveGift] AFTER _removeItemsImpl. Dispatched. Current userActionStatus: ${get().userActionStatus}. Waiting for cart update.`\n );\n } else {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleRemoveGift] No cart line to remove for tier ${tierId}. Gift declined (if not already). Recalculating. Current userActionStatus: ${get().userActionStatus}`\n );\n }\n get().recalculateState();\n },\n\n handleSelectVariant: (tierId, variantGid) => {\n const state = get();\n const { _addItemsImpl, _removeItemsImpl, userActionStatus: initialUserActionStatus } = state;\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleSelectVariant] BEGIN for tier ${tierId}, variant ${variantGid}. Initial userActionStatus: ${initialUserActionStatus}`\n );\n\n if (!_addItemsImpl || !_removeItemsImpl) {\n rebuyDebugLog.error(\n DebugKey.SC_TPB_STORE,\n `[handleSelectVariant] Submit functions not set. Cannot select variant for tier ${tierId}.`\n );\n\n return;\n }\n\n if (state.userActionStatus === 'pending' || state.productFetchStatus !== 'success') {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleSelectVariant] Action blocked (userActionStatus: ${state.userActionStatus}, productFetchStatus: ${state.productFetchStatus})`\n );\n\n return;\n }\n\n const giftState = state.giftStates.get(tierId);\n const selectedVariant = giftState?.availableChoices.find((v) => v.id === variantGid);\n\n if (!giftState || !selectedVariant) {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleSelectVariant] No gift state for tier ${tierId} or variant not available`\n );\n set({\n lastErrorTimestamp: Date.now(),\n userActionError: { message: 'Invalid gift state or variant selection', tierId },\n userActionStatus: 'error',\n });\n\n return;\n }\n\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleSelectVariant] BEFORE setting userActionStatus to 'pending'. Current: ${get().userActionStatus}`\n );\n set({ userActionError: null, userActionStatus: 'pending' });\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleSelectVariant] AFTER setting userActionStatus to 'pending'. Current: ${get().userActionStatus}`\n );\n\n const declineKey = getDeclineKey(tierId, giftState.legacyProductId);\n const wasDeclined = state.declinedGiftMap[declineKey] ?? false;\n\n if (wasDeclined) {\n const nextDeclinedMap = { ...state.declinedGiftMap };\n delete nextDeclinedMap[declineKey];\n set({ declinedGiftMap: nextDeclinedMap });\n updateDeclinedCache(nextDeclinedMap);\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, `[handleSelectVariant] Undeclined gift for tier ${tierId}`);\n }\n\n const cartLines = state.cartData?.lines ? flattenConnection(state.cartData.lines) : [];\n const lineToRemoveId = cartLines.find((line) =>\n line.attributes?.some((attr) => attr.key === '_tier' && attr.value === tierId)\n )?.id;\n\n if (lineToRemoveId) {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleSelectVariant] BEFORE _removeItemsImpl. Current userActionStatus: ${get().userActionStatus}`\n );\n _removeItemsImpl([lineToRemoveId]); // Fire-and-forget\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleSelectVariant] AFTER _removeItemsImpl. Current userActionStatus: ${get().userActionStatus}`\n );\n }\n\n const itemToAdd: HRCartLineInput = {\n attributes: [\n { key: '_source', value: 'Rebuy' },\n { key: '_attribution', value: RebuyLineItemAttribution.TIERED_PROGRESS_BAR },\n { key: '_tier', value: tierId },\n ],\n merchandiseId: variantGid,\n quantity: 1,\n };\n\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleSelectVariant] BEFORE _addItemsImpl for new variant. Current userActionStatus: ${get().userActionStatus}`\n );\n _addItemsImpl([itemToAdd]); // Fire-and-forget\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[handleSelectVariant] AFTER _addItemsImpl. Dispatched. Current userActionStatus: ${get().userActionStatus}. Waiting for cart update.`\n );\n },\n // --- ACTIONS ---\n // eslint-disable-next-line require-await\n init: async (newSettings, shopifyDomain, storefrontAccessToken) => {\n const currentState = get();\n set({ initializationStatus: 'pending' });\n let rawSelectedBar: TieredProgressBar | null = null;\n\n /**\n * TODO: Geolocation support\n * This will involve:\n * 1. Accepting userCountryCode as a parameter.\n * 2. Implementing the logic to iterate through newSettings.bars, check\n * bar.geolocation_enabled and bar.country_codes against userCountryCode.\n * 3. Selecting the bar based on priority (geo-match first, then first default).\n */\n if (newSettings && newSettings.bars && newSettings.bars.length > 0) {\n rawSelectedBar = newSettings.bars[0];\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, `Selecting first available bar: ${rawSelectedBar?.id ?? 'None'}`);\n } else {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[TPB Store Init] No bars in newSettings or newSettings is null.');\n }\n let finalActiveBarConfig: TieredProgressBar | null = null;\n\n if (rawSelectedBar) {\n finalActiveBarConfig = {\n ...rawSelectedBar,\n tiers: [...(rawSelectedBar.tiers ?? [])].sort((a, b) => a.minimum - b.minimum),\n };\n }\n const prevActiveBarId = currentState.activeBarConfig?.id;\n const newActiveBarId = finalActiveBarConfig?.id;\n const updates: Partial<TieredProgressBarStoreState> = {\n _shopifyDomain: shopifyDomain,\n _storefrontAccessToken: storefrontAccessToken,\n activeBarConfig: finalActiveBarConfig,\n initializationStatus: 'complete',\n settings: newSettings,\n };\n\n if (prevActiveBarId !== newActiveBarId) {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `Active bar changed from ${prevActiveBarId ?? 'None'} to ${newActiveBarId ?? 'None'}. Resetting product-related states.`\n );\n updates.fetchedProductMap = new Map();\n updates.giftStates = new Map();\n updates.productFetchStatus = 'idle';\n updates.productFetchError = null;\n updates.cartSyncStatus = 'idle';\n updates.cartSyncError = null;\n updates.userActionStatus = 'idle';\n updates.userActionError = null;\n updates._lastFetchedBarId = null;\n }\n set(updates);\n\n if (finalActiveBarConfig && !get().isManuallyDisabled) {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `Active bar \"${finalActiveBarConfig.id}\". Triggering product fetch.`\n );\n await get().fetchProducts();\n } else {\n if (!finalActiveBarConfig) {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n 'No active bar after selection. Products will not be fetched.'\n );\n } else if (get().isManuallyDisabled) {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, 'Bar is manually disabled. Products will not be fetched.');\n }\n }\n },\n\n recalculateState: () => {\n const state = get();\n rebuyDebugLog.groupCollapsed(DebugKey.SC_TPB_STORE, '[recalculateState] Execution Started.');\n\n const { activeBarConfig, cartData, giftStates: currentGiftStates, isCartReady, productFetchStatus } = state;\n\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n '[recalculateState] Input cart subtotal:',\n cartData?.cost?.subtotalAmount?.amount,\n 'Declined map:',\n state.declinedGiftMap\n );\n\n if (!activeBarConfig || !isCartReady || productFetchStatus !== 'success' || !cartData) {\n if (currentGiftStates.size > 0 || state.currentSubtotal !== 0) {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[recalculateState] Preconditions not met, resetting relevant states. Details:`,\n {\n activeBar: !!activeBarConfig,\n cartData: !!cartData,\n cartReady: isCartReady,\n productFetch: productFetchStatus,\n }\n );\n set({ currentSubtotal: 0, giftStates: new Map() });\n }\n rebuyDebugLog.groupEnd();\n\n return;\n }\n\n const actualCartLines = cartData.lines ? flattenConnection(cartData.lines) : [];\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[recalculateState] Starting. Cart lines count: ${actualCartLines.length}, Current subtotal (from state): ${state.currentSubtotal}`\n );\n\n const nextCurrentSubtotal = calculateCurrentProgressBarSubtotal(cartData, activeBarConfig);\n const nextHasFreeShippingOnSubscription = checkHasFreeShippingOnSubscription(cartData, activeBarConfig);\n\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n '[recalculateState] Next current subtotal:',\n nextCurrentSubtotal,\n 'Next has free shipping on subscription:',\n nextHasFreeShippingOnSubscription\n );\n\n const newGiftStatesCandidate = new Map<string, TieredProgressBarQualifiedGiftState>();\n\n const giftLinesInCart = actualCartLines.filter((line) => isTieredProgressBarGiftItem(line as CartLine));\n\n activeBarConfig.tiers.forEach((tier) => {\n if (tier.type !== TieredProgressBarTierType.PRODUCT || !tier.products?.[0]) return;\n\n const tierProductSettings = tier.products[0];\n const legacyProductId = tierProductSettings.product_id;\n const fetchedProduct = state.fetchedProductMap.get(legacyProductId);\n\n if (!fetchedProduct) return;\n\n const tierId = tier.id;\n const isReached = checkIsTierReached(tier, nextCurrentSubtotal, nextHasFreeShippingOnSubscription);\n const allVariants = fetchedProduct.variants.edges.map((e) => e.node);\n const allowedVariantLegacyIds = new Set(tierProductSettings.variant_ids ?? []);\n const filterOOS = tier.filter_oos_variants ?? false;\n\n const availableChoices = allVariants.filter((v) => {\n const legacyVariantId = getNumericIdFromGid(v.id);\n const isAllowed = allowedVariantLegacyIds.size === 0 || allowedVariantLegacyIds.has(legacyVariantId);\n const isInStock = !filterOOS || v.availableForSale;\n\n return isAllowed && isInStock;\n });\n\n const declineKey = getDeclineKey(tierId, legacyProductId);\n const isDeclined = state.declinedGiftMap[declineKey] ?? false;\n\n const cartLineForThisGift = giftLinesInCart.find((line) =>\n line.attributes?.some((attr) => attr.key === '_tier' && attr.value === tierId)\n );\n const isInCart = !!cartLineForThisGift;\n const variantInCart = isInCart\n ? (allVariants.find((v) => v.id === cartLineForThisGift?.merchandise.id) ?? null)\n : null;\n\n let currentError = null;\n const existingGiftState = currentGiftStates.get(tierId);\n\n if (existingGiftState?.error && Date.now() - state.lastErrorTimestamp < 7000) {\n currentError = existingGiftState.error;\n }\n\n if (\n state.userActionError &&\n state.userActionError.tierId === tierId &&\n Date.now() - state.lastErrorTimestamp < 7000\n ) {\n currentError = state.userActionError.message;\n }\n\n let displayStatus: GiftStatus;\n\n if (currentError) displayStatus = GiftStatus.ERROR;\n else if (!isReached) displayStatus = GiftStatus.IDLE;\n else if (availableChoices.length === 0) displayStatus = GiftStatus.UNAVAILABLE;\n else if (isInCart) displayStatus = GiftStatus.ADDED;\n else if (isDeclined) displayStatus = GiftStatus.DECLINED;\n else if (availableChoices.length > 1) displayStatus = GiftStatus.NEEDS_SELECTION;\n else displayStatus = GiftStatus.IDLE;\n\n const canReAdd = isReached && isDeclined && availableChoices.length > 0 && !currentError;\n\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[recalculateState] Tier ${tierId}: isReached=${isReached}, isInCart=${isInCart} (lineId: ${cartLineForThisGift?.id ?? 'N/A'}), isDeclined=${isDeclined}, choices=${availableChoices.length}, status=${displayStatus}`\n );\n\n const qualifiedGiftStateForThisTier: TieredProgressBarQualifiedGiftState = {\n allowedVariantIds: tierProductSettings.variant_ids ?? [],\n availableChoices,\n canReAdd,\n displayStatus,\n error: currentError,\n filterOOS,\n handle: fetchedProduct.handle,\n image: fetchedProduct.images?.edges[0]?.node\n ? {\n altText: fetchedProduct.images.edges[0].node.altText ?? '',\n src: fetchedProduct.images.edges[0].node.url,\n }\n : undefined,\n isDeclined,\n isInCart,\n isReached,\n legacyProductId,\n productId: fetchedProduct.id,\n tierId,\n title: fetchedProduct.title,\n variantInCart,\n variants: allVariants,\n };\n newGiftStatesCandidate.set(tierId, qualifiedGiftStateForThisTier);\n });\n\n const updates: Partial<TieredProgressBarStoreState> = {};\n let hasChanges = false;\n\n if (state.currentSubtotal !== nextCurrentSubtotal) {\n updates.currentSubtotal = nextCurrentSubtotal;\n hasChanges = true;\n }\n\n if (state.hasFreeShippingOnSubscription !== nextHasFreeShippingOnSubscription) {\n updates.hasFreeShippingOnSubscription = nextHasFreeShippingOnSubscription;\n hasChanges = true;\n }\n\n if (!isEqual(currentGiftStates, newGiftStatesCandidate)) {\n updates.giftStates = newGiftStatesCandidate;\n hasChanges = true;\n }\n\n const nextCartSyncError =\n state.cartSyncError && Date.now() - state.lastErrorTimestamp > 7000 ? null : state.cartSyncError;\n\n if (state.cartSyncError !== nextCartSyncError) {\n updates.cartSyncError = nextCartSyncError;\n hasChanges = true;\n }\n\n if (hasChanges) {\n set(updates);\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n '[recalculateState] Completed. Changes detected and applied. New giftStates:',\n JSON.parse(JSON.stringify(Array.from(get().giftStates.entries()))),\n 'New subtotal:',\n get().currentSubtotal\n );\n } else {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[recalculateState] Completed. No effective state changes.');\n }\n rebuyDebugLog.groupEnd();\n },\n\n setCartData: (newCartData, newIsCartReady) => {\n const currentState = get(); // Get state *before* any modifications by this call\n\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n '[setCartData] Called. Current userActionStatus:',\n currentState.userActionStatus,\n 'Current cartSyncStatus:',\n currentState.cartSyncStatus,\n 'New isCartReady:',\n newIsCartReady\n // 'New cartData:', newCartData // Can be verbose\n );\n\n const updates: Partial<TieredProgressBarStoreState> = {};\n let didCartDataContentChange = false;\n let didIsCartReadyChange = false;\n\n if (!isEqual(currentState.cartData, newCartData)) {\n updates.cartData = newCartData;\n didCartDataContentChange = true;\n }\n\n if (currentState.isCartReady !== newIsCartReady) {\n updates.isCartReady = newIsCartReady;\n didIsCartReadyChange = true;\n }\n\n if (didCartDataContentChange || didIsCartReadyChange) {\n set(updates); // Apply basic cartData and isCartReady updates first\n }\n\n const stateAfterCartDataUpdate = get(); // Get state after potential cartData/isCartReady update\n\n // Recalculate internal gift states, subtotal etc. based on the (potentially) new cartData\n if (\n stateAfterCartDataUpdate.isCartReady &&\n (stateAfterCartDataUpdate.productFetchStatus === 'success' || !stateAfterCartDataUpdate.activeBarConfig)\n ) {\n stateAfterCartDataUpdate.recalculateState();\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[setCartData] recalculateState() was called.');\n } else {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[setCartData] recalculateState() was SKIPPED.', {\n /* ... conditions ... */\n });\n }\n\n // Now, manage status transitions based on the fresh state from recalculateState\n const statusUpdates: Partial<TieredProgressBarStoreState> = {};\n let statusesChanged = false;\n\n // If a user action was pending, the arrival and processing of new cart data means\n // we can consider that direct user interaction phase completed.\n if (get().userActionStatus === 'pending') {\n statusUpdates.userActionStatus = 'idle';\n statusesChanged = true;\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[setCartData] Transitioned userActionStatus from 'pending' to 'idle'.`\n );\n }\n\n // If the cart was awaiting an update from a syncCartGifts operation, it has now arrived and been processed.\n if (get().cartSyncStatus === 'awaiting_cart_update') {\n statusUpdates.cartSyncStatus = 'idle';\n statusesChanged = true;\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n `[setCartData] Transitioned cartSyncStatus from 'awaiting_cart_update' to 'idle'.`\n );\n } else {\n // If cartSyncStatus was not 'awaiting_cart_update', no transition needed for it here.\n // The syncCartGifts useEffect in SmartCartContext will evaluate if a new sync is needed\n // now that userActionStatus might be 'idle' and cartData is updated.\n }\n\n if (statusesChanged) {\n set(statusUpdates);\n }\n },\n\n setSubmitFunctions: (addItemsImpl, removeItemsImpl) => {\n set({ _addItemsImpl: addItemsImpl, _removeItemsImpl: removeItemsImpl });\n },\n\n syncCartGifts: async () => {\n rebuyDebugLog.groupCollapsed(\n DebugKey.SC_TPB_STORE,\n '[syncCartGifts] Execution Started. Current cartSyncStatus:',\n get().cartSyncStatus\n );\n\n const state = get();\n\n if (state.cartSyncStatus === 'syncing') {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[syncCartGifts] Already syncing, exiting early');\n rebuyDebugLog.groupEnd();\n\n return;\n }\n\n const { _addItemsImpl, _removeItemsImpl } = state;\n\n if (!_addItemsImpl || !_removeItemsImpl) {\n rebuyDebugLog.error(DebugKey.SC_TPB_STORE, '[syncCartGifts] Submit functions not set. Cannot sync gifts.');\n rebuyDebugLog.groupEnd();\n\n return;\n }\n\n if (\n !state.isCartReady ||\n state.productFetchStatus !== 'success' ||\n !state.activeBarConfig ||\n state.isManuallyDisabled ||\n !state.cartData\n ) {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[syncCartGifts] Required conditions not met:', {\n hasActiveBarConfig: !!state.activeBarConfig,\n hasCartData: !!state.cartData,\n isCartReady: state.isCartReady,\n isManuallyDisabled: state.isManuallyDisabled,\n productFetchStatus: state.productFetchStatus,\n });\n rebuyDebugLog.groupEnd();\n\n return;\n }\n\n const itemsToAddPayload: { attributes: StorefrontAttribute[]; merchandiseId: string; quantity: number }[] = [];\n const lineIdsToRemove: string[] = [];\n\n const actualCartLinesForSync = state.cartData.lines ? flattenConnection(state.cartData.lines) : [];\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[syncCartGifts] Cart lines count:', actualCartLinesForSync.length);\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n '[syncCartGifts] Using giftStates:',\n JSON.parse(JSON.stringify(Array.from(state.giftStates.entries())))\n );\n\n state.activeBarConfig.tiers.forEach((tier) => {\n if (tier.type !== TieredProgressBarTierType.PRODUCT || !tier.products?.[0]) return;\n const giftState = state.giftStates.get(tier.id);\n\n if (!giftState) return;\n\n const { availableChoices, isDeclined, isInCart, isReached, tierId } = giftState;\n const cartLineForThisTier = actualCartLinesForSync.find((line) =>\n line.attributes?.some((attr) => attr.key === '_tier' && attr.value === tierId)\n );\n\n if (isReached && availableChoices.length === 1 && !isDeclined && !isInCart) {\n itemsToAddPayload.push({\n attributes: [\n { key: '_source', value: 'Rebuy' },\n { key: '_attribution', value: RebuyLineItemAttribution.TIERED_PROGRESS_BAR },\n { key: '_tier', value: tierId },\n ],\n merchandiseId: availableChoices[0].id,\n quantity: 1,\n });\n }\n\n if (cartLineForThisTier) {\n let shouldRemove = false;\n\n if (!isReached) shouldRemove = true;\n else if (availableChoices.length === 0) shouldRemove = true;\n else if (!availableChoices.some((v) => v.id === cartLineForThisTier.merchandise.id))\n shouldRemove = true;\n\n if (shouldRemove && !lineIdsToRemove.includes(cartLineForThisTier.id)) {\n lineIdsToRemove.push(cartLineForThisTier.id);\n }\n }\n });\n\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[syncCartGifts] Calculated actions:', {\n itemsToAddPayload,\n lineIdsToRemove,\n });\n\n if (itemsToAddPayload.length === 0 && lineIdsToRemove.length === 0) {\n const statusUpdates: Partial<TieredProgressBarStoreState> = {};\n let changed = false;\n\n if (get().cartSyncStatus !== 'idle') {\n statusUpdates.cartSyncStatus = 'idle';\n changed = true;\n }\n\n if (get().userActionStatus === 'pending') {\n statusUpdates.userActionStatus = 'idle';\n changed = true;\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n \"[syncCartGifts] No Shopify actions needed. UserActionStatus was 'pending', resetting to 'idle'.\"\n );\n }\n\n if (changed) {\n set(statusUpdates);\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n '[syncCartGifts] No Shopify actions needed by sync. Applied status updates:',\n statusUpdates\n );\n } else {\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n '[syncCartGifts] No Shopify actions needed by sync. Statuses were already appropriate.'\n );\n }\n rebuyDebugLog.groupEnd();\n\n return;\n }\n\n set({ cartSyncError: null, cartSyncStatus: 'syncing' });\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n \"[syncCartGifts] Set cartSyncStatus to 'syncing'. Current userActionStatus:\",\n get().userActionStatus\n );\n\n try {\n if (lineIdsToRemove.length > 0) {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[syncCartGifts] Removing lines:', lineIdsToRemove);\n await _removeItemsImpl(lineIdsToRemove);\n }\n\n if (itemsToAddPayload.length > 0) {\n if (lineIdsToRemove.length > 0) {\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[syncCartGifts] Waiting 300ms before adding items');\n await new Promise((res) => setTimeout(res, 300));\n }\n\n const itemsForAddImpl = itemsToAddPayload.map((item) => ({\n ...item,\n attributes: item.attributes.map((attr) => ({ key: attr.key, value: attr.value || '' })),\n }));\n\n rebuyDebugLog.log(DebugKey.SC_TPB_STORE, '[syncCartGifts] Adding items:', itemsForAddImpl);\n await _addItemsImpl(itemsForAddImpl as HRCartLineInput[]);\n }\n\n set({ cartSyncStatus: 'awaiting_cart_update' });\n rebuyDebugLog.log(\n DebugKey.SC_TPB_STORE,\n \"[syncCartGifts] Sync successful (dispatched actions). Set cartSyncStatus to 'awaiting_cart_update'. userActionStatus remains:\",\n get().userActionStatus\n );\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Failed to sync gifts.';\n\n if (get().userActionStatus === 'pending') {\n set({\n cartSyncError: message,\n cartSyncStatus: 'error',\n lastErrorTimestamp: Date.now(),\n userActionStatus: 'error',\n });\n } else {\n set({\n cartSyncError: message,\n cartSyncStatus: 'error',\n lastErrorTimestamp: Date.now(),\n });\n }\n rebuyDebugLog.error(DebugKey.SC_TPB_STORE, '[syncCartGifts] Sync error:', message);\n }\n\n rebuyDebugLog.groupEnd();\n },\n}));\n\nexport type SelectedTieredProgressBarStore = Pick<\n TieredProgressBarStoreState,\n | 'activeBarConfig'\n | 'currentSubtotal'\n | 'giftStates'\n | 'isCartReady'\n | 'productFetchStatus'\n | 'cartSyncStatus'\n | 'userActionStatus'\n | 'productFetchError'\n | 'cartSyncError'\n | 'userActionError'\n | 'isManuallyDisabled'\n | 'hasFreeShippingOnSubscription'\n | 'declinedGiftMap'\n | 'initializationStatus'\n | '_lastFetchedBarId'\n | 'fetchedProductMap'\n>;\n", "// ~/smart-cart/components/TieredProgressBar/progressBarUtils.tsx\n\nimport { flattenConnection } from '@shopify/hydrogen';\nimport type { CartLine } from '@shopify/hydrogen/storefront-api-types';\nimport type React from 'react';\nimport { DebugKey } from '~/constants/debug';\nimport { CheckIcon, DiscountIcon, GiftIcon, ShippingIcon } from '~/smart-cart/components/TieredProgressBar/Icons';\nimport {\n type TieredProgressBarFetchedProductData as FetchedProductData,\n type TieredProgressBar,\n type TieredProgressBarCachedGiftData,\n type TieredProgressBarExcludedProduct,\n type TieredProgressBarTier,\n type TieredProgressBarTierProduct,\n TieredProgressBarTierType,\n type TieredProgressBarVariantNode,\n} from '~/smart-cart/components/TieredProgressBar/types';\nimport { CartExclusionProductTag, SessionStorageKey } from '~/smart-cart/constants';\nimport type { StorefrontCartData } from '~/smart-cart/types/rebuy-storefront-cart';\nimport { isSubscriptionItem, isTieredProgressBarGiftItem } from '~/smart-cart/utils/cartItemUtils';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport { formatMoney } from '~/smart-cart/utils/moneyUtils';\nimport { safeJsonParse } from '~/smart-cart/utils/safeJsonParse';\n\n// Type for the map itself (use FetchedProductData alias)\ntype FetchedProductMap = Map<number, FetchedProductData>;\n\n/**\n * Helper to get numeric ID from a Shopify GID string.\n * e.g., \"gid://shopify/Product/12345\" -> 12345\n *\n * @param {string} gid The Shopify GID string.\n *\n * @returns {number} The numeric ID.\n */\nexport const getNumericIdFromGid = (gid: string): number => {\n return parseInt(gid.split('/').pop() ?? '0', 10);\n};\n\n/**\n * Helper to generate a unique key for storing declined gift states.\n * Uses a combination of tier ID and legacy product ID.\n *\n * @param {string} tierId The ID of the tier.\n * @param {number|string} legacyProductId The legacy numeric ID of the product associated with the tier.\n *\n * @returns {string} A string key for the declined gift.\n */\nexport const getDeclineKey = (tierId: string, legacyProductId: number | string): string => {\n return `${tierId}:${legacyProductId}`;\n};\n\n/**\n * Generates the replacement string for discount tier feedback text (e.g., \"$10 Off\" or \"15%\").\n *\n * @param {TieredProgressBarTier} tier The discount tier configuration.\n *\n * @returns {string} The formatted discount string.\n */\nconst getDiscountTierTextReplacementString = (tier: TieredProgressBarTier): string => {\n if (!tier || tier.type !== TieredProgressBarTierType.DISCOUNT) return '';\n\n return tier.discount_type === 'fixedAmount'\n ? formatMoney(Number(tier.discount_amount_from_total ?? 0))\n : `${tier.discount_amount_from_total ?? 0}%`;\n};\n\n/**\n * Gets the display label for a tier marker.\n *\n * @param {TieredProgressBarTier} tier The tier configuration.\n * @param {FetchedProductMap} fetchedProductMap Optional: A map of fetched product data, used to look up product titles for product tiers.\n *\n * @returns {string} The label string for the tier.\n */\nexport const getTierLabel = (tier: TieredProgressBarTier, fetchedProductMap?: FetchedProductMap): string => {\n if ((tier.custom_tier_label || tier.type === TieredProgressBarTierType.DECORATIVE) && tier.custom_tier_label_text) {\n return tier.custom_tier_label_text;\n }\n\n switch (tier.type) {\n case TieredProgressBarTierType.SHIPPING:\n return 'Free Shipping'; // TODO: Wire up to language settings\n case TieredProgressBarTierType.DISCOUNT:\n return tier.discount_type === 'fixedAmount'\n ? `${formatMoney(Number(tier.discount_amount_from_total ?? 0))} Off`\n : `${tier.discount_amount_from_total ?? 0}% Discount`;\n case TieredProgressBarTierType.DECORATIVE:\n return tier.custom_tier_label_text ?? 'Decorative';\n case TieredProgressBarTierType.PRODUCT:\n if (fetchedProductMap && tier.products?.[0]?.product_id) {\n const productData = fetchedProductMap.get(tier.products[0].product_id);\n\n if (productData?.title) {\n return productData.title;\n }\n }\n\n return 'Free Gift';\n default:\n return 'Tier';\n }\n};\n\n/**\n * Generates the main feedback text displayed below the progress bar.\n * This text guides the user on how much more they need to spend for the next tier or confirms rewards.\n * It respects boolean flags on the tier settings (e.g., `product_amount_reached_label`) to determine\n * if a specific label text should be used.\n *\n * @param {TieredProgressBar|null} barConfig The active progress bar configuration.\n * @param {TieredProgressBarTier|null} currentTier The next tier the user is progressing towards, or null if all tiers are reached.\n * @param {TieredProgressBarTier|null} lastReachedTier The most recent tier the user has successfully reached, or null if no tiers are reached.\n * @param {number} amountToNextTier The monetary amount remaining to reach the `currentTier`.\n * @param {FetchedProductMap} fetchedProductMap A map of fetched product data, used to look up product titles for product tiers.\n *\n * @returns {string} The formatted feedback string, or an empty string if no label should be shown.\n */\nexport const getTierFeedbackText = (\n barConfig: TieredProgressBar | null,\n currentTier: TieredProgressBarTier | null,\n lastReachedTier: TieredProgressBarTier | null,\n amountToNextTier: number,\n fetchedProductMap: FetchedProductMap\n): string => {\n if (!barConfig) return '';\n\n const language = barConfig.language;\n const validAmountToNextTier = typeof amountToNextTier === 'number' ? amountToNextTier : 0;\n const remainingAmountReplacement = formatMoney(validAmountToNextTier);\n const remainingAmountRegex = /\\{\\{remaining_amount\\}\\}/g;\n const productRegex = /\\{\\{product_title\\}\\}/g;\n const discountRegex = /\\{\\{discount_amount\\}\\}/g;\n\n // Case 1: All tiers reached (lastReachedTier is the one to display info for)\n if (!currentTier && lastReachedTier) {\n const finalTier = lastReachedTier;\n let text = '';\n\n switch (finalTier.type) {\n case TieredProgressBarTierType.PRODUCT:\n if (finalTier.product_amount_reached_label && finalTier.product_amount_reached_label_text) {\n const tierProductInfo: TieredProgressBarTierProduct | undefined = finalTier.products?.[0];\n const productTitle = tierProductInfo?.product_id\n ? (fetchedProductMap.get(tierProductInfo.product_id)?.title ?? 'your free gift')\n : 'your free gift';\n text = finalTier.product_amount_reached_label_text\n .replace(remainingAmountRegex, remainingAmountReplacement)\n .replace(productRegex, productTitle);\n }\n break;\n case TieredProgressBarTierType.SHIPPING:\n // Shipping tiers don't have explicit boolean flags in the provided Tier type for reached/remaining.\n if (language?.free_shipping_reached) {\n text = language.free_shipping_reached.replace(remainingAmountRegex, remainingAmountReplacement);\n }\n break;\n case TieredProgressBarTierType.DISCOUNT:\n if (finalTier.discount_amount_reached_label && finalTier.discount_amount_reached_label_text) {\n const discountTextReplacement = getDiscountTierTextReplacementString(finalTier);\n text = finalTier.discount_amount_reached_label_text\n .replace(remainingAmountRegex, remainingAmountReplacement)\n .replace(discountRegex, discountTextReplacement);\n }\n break;\n case TieredProgressBarTierType.DECORATIVE:\n if (finalTier.decorative_amount_reached_label && finalTier.decorative_amount_reached_label_text) {\n text = finalTier.decorative_amount_reached_label_text.replace(\n remainingAmountRegex,\n remainingAmountReplacement\n );\n }\n break;\n default:\n break;\n }\n\n return text;\n }\n\n // Case 2: Progressing towards the 'currentTier'\n if (currentTier) {\n let text = '';\n switch (currentTier.type) {\n case TieredProgressBarTierType.PRODUCT:\n if (currentTier.product_amount_remaining_label && currentTier.product_amount_remaining_label_text) {\n const tierProductInfo: TieredProgressBarTierProduct | undefined = currentTier.products?.[0];\n const productTitle = tierProductInfo?.product_id\n ? (fetchedProductMap.get(tierProductInfo.product_id)?.title ?? 'a free gift')\n : 'a free gift';\n text = currentTier.product_amount_remaining_label_text\n .replace(remainingAmountRegex, remainingAmountReplacement)\n .replace(productRegex, productTitle);\n }\n break;\n case TieredProgressBarTierType.SHIPPING:\n // Shipping tiers don't have explicit boolean flags for reached/remaining.\n if (language?.free_shipping_remaining) {\n text = language.free_shipping_remaining.replace(remainingAmountRegex, remainingAmountReplacement);\n }\n break;\n case TieredProgressBarTierType.DISCOUNT:\n if (currentTier.discount_amount_remaining_label && currentTier.discount_amount_remaining_label_text) {\n const discountTextReplacement = getDiscountTierTextReplacementString(currentTier);\n text = currentTier.discount_amount_remaining_label_text\n .replace(remainingAmountRegex, remainingAmountReplacement)\n .replace(discountRegex, discountTextReplacement);\n }\n break;\n case TieredProgressBarTierType.DECORATIVE:\n if (\n currentTier.decorative_amount_remaining_label &&\n currentTier.decorative_amount_remaining_label_text\n ) {\n text = currentTier.decorative_amount_remaining_label_text.replace(\n remainingAmountRegex,\n remainingAmountReplacement\n );\n }\n break;\n default:\n break;\n }\n\n return text;\n }\n\n // Fallback case: No current tier, no last reached tier (e.g., bar with no tiers, or initial state)\n return '';\n};\n\n/**\n * Minimal image object type for tier icons.\n * Represents an image with an optional alt text and type.\n *\n * @property {string} alt - The alternative text for the image.\n * @property {string} src - The source URL of the image.\n * @property {string} type - The type of the icon (always 'image').\n */\nexport type TierIconImage = { alt: string; src: string; type: 'image' };\n\n/**\n * Determines the icon component to display for a tier marker.\n *\n * @param {TieredProgressBarTier} tier The tier configuration.\n * @param {boolean} isReached Whether the tier has been reached.\n * @param {FetchedProductMap} fetchedProductMap A map of fetched product data, used for product tier image checks.\n *\n * @returns {TierIconReturnType} A React element or image object representing the icon.\n */\nexport type TierIconReturnType = React.ReactElement | TierIconImage;\n\nexport const getTierIconComponent = (\n tier: TieredProgressBarTier,\n isReached: boolean,\n fetchedProductMap: FetchedProductMap\n): TierIconReturnType => {\n if (isReached) {\n return <CheckIcon />;\n }\n\n switch (tier.type) {\n case TieredProgressBarTierType.SHIPPING:\n return <ShippingIcon />;\n case TieredProgressBarTierType.DISCOUNT:\n return <DiscountIcon />;\n case TieredProgressBarTierType.PRODUCT: {\n const tierProductInfo: TieredProgressBarTierProduct | undefined = tier.products?.[0];\n const productData = tierProductInfo?.product_id\n ? fetchedProductMap.get(tierProductInfo.product_id)\n : undefined;\n const imageUrl = productData?.images?.edges?.[0]?.node?.url;\n\n if (tier.product_tier_image && imageUrl && productData) {\n return {\n alt: productData.title || 'Gift product',\n src: imageUrl,\n type: 'image',\n };\n }\n\n return <GiftIcon />;\n }\n case TieredProgressBarTierType.DECORATIVE:\n return <GiftIcon />;\n default:\n console.warn(`Unknown tier type for icon: ${tier.type}`);\n\n return <GiftIcon />;\n }\n};\n\n/**\n * Gets the minimum spend required to reach a specific tier.\n *\n * @param {TieredProgressBarTier} tier The tier configuration.\n *\n * @returns {number} The minimum amount, or Infinity if tier is invalid.\n */\nexport const getTierMinimum = (tier: TieredProgressBarTier): number => {\n if (!tier) return Infinity;\n\n return tier.minimum ?? Infinity;\n};\n\n/**\n * Gets a user-friendly display title for a selected gift variant.\n *\n * @param {TieredProgressBarVariantNode|null} variant The variant node.\n *\n * @returns {string} The display title string.\n */\nexport const getFreeVariantTitle = (variant: TieredProgressBarVariantNode | null): string => {\n if (!variant) return '';\n\n if (variant.title && variant.title.toLowerCase() !== 'default title') {\n return variant.title;\n }\n\n const meaningfulOptions = variant.selectedOptions?.filter((opt) => opt.value.toLowerCase() !== 'default title');\n\n if (meaningfulOptions && meaningfulOptions.length > 0) {\n return meaningfulOptions.map((opt) => opt.value).join(' / ');\n }\n\n return '';\n};\n\n/**\n * Determines if the main gift area container should be rendered.\n * Renders if there's an active bar configuration and items to display within the gift area.\n *\n * @param {TieredProgressBar|null} barConfig The active progress bar configuration.\n * @param {boolean} hasRenderableItems A boolean indicating if there are any gift items to be rendered.\n *\n * @returns {boolean} True if the gift area should be rendered, false otherwise.\n */\nexport const shouldRenderGiftArea = (barConfig: TieredProgressBar | null, hasRenderableItems: boolean): boolean => {\n if (!barConfig || !hasRenderableItems) return false;\n\n return true;\n};\n\n/**\n * Determines if the title for the gift area should be shown.\n *\n * @param {TieredProgressBar|null} barConfig The active progress bar configuration.\n *\n * @returns {boolean} True if the gift area title should be rendered, false otherwise.\n */\nexport const shouldRenderGiftAreaTitle = (barConfig: TieredProgressBar | null): boolean => {\n return !!barConfig?.language?.gift_area_title?.trim();\n};\n\n/**\n * Gets the title text for the gift area.\n *\n * @param {TieredProgressBar|null} barConfig The active progress bar configuration.\n *\n * @returns {string} The gift area title string, or a default if not configured.\n */\nexport const getGiftAreaTitle = (barConfig: TieredProgressBar | null): string => {\n return barConfig?.language?.gift_area_title ?? 'FREE GIFTS';\n};\n\n/**\n * Calculates the current subtotal relevant for the progress bar.\n * It starts with zero and adds the cost of each included cart item.\n *\n * Excluded items are:\n * 1. Tiered Progress Bar gift items.\n * 2. Items tagged with the specific exclusion tag.\n * 3. If `bar.discounted_by === 'functions'`, items listed in `bar.excluded_products`.\n *\n * @param {StorefrontCartData|null} cart The current storefront cart data.\n * @param {TieredProgressBar|null} bar The active progress bar configuration.\n *\n * @returns {number} The calculated subtotal for the progress bar.\n */\nexport const calculateCurrentProgressBarSubtotal = (\n cart: StorefrontCartData | null,\n bar: TieredProgressBar | null\n): number => {\n const logCollector: string[] = [];\n\n if (!cart || !bar || !cart.cost || !cart.lines) {\n logCollector.push(\n '[TPB SubtotalCalc] Aborted: Essential data missing (cart, bar config, cart cost, or cart lines object).'\n );\n logCollector.push('[TPB SubtotalCalc] Resulting Subtotal: 0');\n rebuyDebugLog.log(DebugKey.SC_TPB_SUBTOTAL_CALC, logCollector.join('\\n'));\n\n return 0;\n }\n let actualCartLineNodes: Readonly<CartLine>[] = [];\n\n try {\n actualCartLineNodes = flattenConnection(cart.lines) as Readonly<CartLine>[];\n } catch (error) {\n logCollector.push(\n '[TPB SubtotalCalc] Aborted: Failed to flatten cart.lines connection.',\n `Error: ${error instanceof Error ? error.message : String(error)}`\n );\n logCollector.push('[TPB SubtotalCalc] Resulting Subtotal: 0');\n rebuyDebugLog.log(DebugKey.SC_TPB_SUBTOTAL_CALC, logCollector.join('\\n'));\n\n return 0;\n }\n\n if (!actualCartLineNodes.length) {\n logCollector.push('[TPB SubtotalCalc] No cart lines found after flattening connection.');\n }\n\n let progressiveSubtotal = 0;\n\n const isFunctionsMode = bar.discounted_by === 'functions';\n const barExcludedProductsConfig: TieredProgressBarExcludedProduct[] = bar.excluded_products ?? [];\n\n const lineItemLogEntries: LineItemLogEntry[] = [];\n const includedItemsForExpression: string[] = [];\n\n actualCartLineNodes.forEach((lineNode, index: number) => {\n const line = lineNode as CartLine;\n const lineIdentifier = line.merchandise?.product?.title || line.merchandise?.title || `Line ${line.id}`;\n const lineAmount = parseFloat(line.cost.totalAmount.amount);\n const lineAmountStr = isNaN(lineAmount) ? `\"${line.cost.totalAmount.amount}\"` : lineAmount.toFixed(2);\n\n const entry: Partial<LineItemLogEntry> = {\n '#': index + 1,\n Item: lineIdentifier,\n 'Original Amount': lineAmountStr,\n };\n\n if (isNaN(lineAmount)) {\n entry.Status = 'SKIPPED';\n entry.Contribution = '0.00';\n entry['Reasons (if Excluded/Skipped)'] = 'Invalid line item amount';\n lineItemLogEntries.push(entry as LineItemLogEntry);\n\n return;\n }\n\n let isExcluded = false;\n const currentLineExclusionReasons: string[] = [];\n\n if (isTieredProgressBarGiftItem(line)) {\n isExcluded = true;\n currentLineExclusionReasons.push('TPB Gift');\n }\n\n const tags = line.merchandise?.product?.tags?.map((t: string) => t.toLowerCase()) ?? [];\n const exclusionTagToCheck = CartExclusionProductTag.EXCLUDE_FROM_PROGRESS_BAR_SUBTOTAL.toLowerCase();\n\n if (tags.some((tag: string) => tag === exclusionTagToCheck)) {\n isExcluded = true;\n currentLineExclusionReasons.push(`Tag: ${exclusionTagToCheck}`);\n }\n\n if (isFunctionsMode && barExcludedProductsConfig.length > 0) {\n const lineProductIdNumeric = line.merchandise?.product?.id\n ? getNumericIdFromGid(line.merchandise.product.id)\n : null;\n const lineVariantIdNumeric = line.merchandise?.id ? getNumericIdFromGid(line.merchandise.id) : null;\n\n if (lineProductIdNumeric !== null) {\n const isExcludedByBarRule = barExcludedProductsConfig.some((excludedProductSetting) => {\n if (excludedProductSetting.product_id === lineProductIdNumeric) {\n const variantsToExclude = excludedProductSetting.variant_ids;\n\n if (!Array.isArray(variantsToExclude) || variantsToExclude.length === 0) return true;\n\n if (lineVariantIdNumeric !== null && variantsToExclude.includes(lineVariantIdNumeric))\n return true;\n }\n\n return false;\n });\n\n if (isExcludedByBarRule) {\n isExcluded = true;\n currentLineExclusionReasons.push('Bar Setting');\n }\n }\n }\n\n if (isExcluded) {\n entry.Status = 'EXCLUDED';\n entry.Contribution = '0.00';\n entry['Reasons (if Excluded/Skipped)'] = currentLineExclusionReasons.join(', ');\n } else {\n progressiveSubtotal += lineAmount; // ONLY ADD IF NOT EXCLUDED\n entry.Status = 'INCLUDED';\n entry.Contribution = lineAmount.toFixed(2);\n entry['Reasons (if Excluded/Skipped)'] = '-';\n includedItemsForExpression.push(`(\"${lineIdentifier}\" - ${lineAmount.toFixed(2)})`);\n }\n lineItemLogEntries.push(entry as LineItemLogEntry);\n });\n\n const finalSubtotal = Math.max(0, progressiveSubtotal);\n logCollector.push(`[TPB SubtotalCalc] Tiered Progress Bar Subtotal Calculation Summary:`);\n\n let contributingItemsExpression = 'No items contributed to subtotal';\n\n if (includedItemsForExpression.length > 0) {\n contributingItemsExpression = includedItemsForExpression.join(' + ');\n } else if (actualCartLineNodes.length > 0) {\n contributingItemsExpression = 'All items were excluded, skipped, or had zero value';\n }\n\n logCollector.push(` Contribution Expression: ${contributingItemsExpression} = ${finalSubtotal.toFixed(2)}`);\n logCollector.push(` Final Tiered Progress Bar Subtotal: ${finalSubtotal.toFixed(2)}`);\n\n logCollector.push(`\\n Relevant Bar Configuration:`);\n logCollector.push(` - Discounted By: ${bar.discounted_by} (Functions Mode: ${isFunctionsMode})`);\n logCollector.push(` - Bar Excluded Products Rules: ${barExcludedProductsConfig.length}`);\n\n logCollector.push(`\\n Line Item Breakdown:`);\n\n const tableLines = formatLogEntriesAsTextTable(lineItemLogEntries);\n logCollector.push(...tableLines);\n rebuyDebugLog.log(DebugKey.SC_TPB_SUBTOTAL_CALC, logCollector.join('\\n'));\n\n return finalSubtotal;\n};\n\n/**\n * Interface for line item log entries used in detailed debugging output.\n */\ntype LineItemLogEntry = {\n '#': number;\n Contribution: string;\n Item: string;\n 'Original Amount': string;\n 'Reasons (if Excluded/Skipped)': string;\n Status: 'INCLUDED' | 'EXCLUDED' | 'SKIPPED';\n};\n\n/**\n * Helper function to format an array of objects as a text table for debugging output.\n *\n * @param {LineItemLogEntry[]} data The array of line item log entries to format.\n *\n * @returns {string[]} An array of formatted text lines representing the table.\n */\nconst formatLogEntriesAsTextTable = (data: LineItemLogEntry[]): string[] => {\n if (data.length === 0) return [' No line items processed.'];\n\n const headers: Record<keyof LineItemLogEntry, string> = {\n '#': '#',\n Contribution: 'Contribution',\n Item: 'Item',\n 'Original Amount': 'Original Amount',\n 'Reasons (if Excluded/Skipped)': 'Reasons (if Excluded/Skipped)',\n Status: 'Status',\n };\n\n const keys = Object.keys(headers) as (keyof LineItemLogEntry)[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const columnWidths: Record<keyof LineItemLogEntry, number> = {} as any;\n\n keys.forEach((key) => {\n columnWidths[key] = headers[key].length;\n });\n\n data.forEach((row) => {\n keys.forEach((key) => {\n const valueStr = String(row[key]);\n columnWidths[key] = Math.max(columnWidths[key], valueStr.length);\n });\n });\n\n const pad = (str: string, width: number) => String(str).padEnd(width);\n\n const headerRowParts = keys.map((key) => pad(headers[key], columnWidths[key]));\n const headerRow = ` | ${headerRowParts.join(' | ')} |`;\n\n const separatorRowParts = keys.map((key) => '-'.repeat(columnWidths[key]));\n const separatorRow = ` +-${separatorRowParts.join('-+-')}-+`;\n\n const tableOutput: string[] = [headerRow, separatorRow];\n\n data.forEach((row) => {\n const rowParts = keys.map((key) => pad(String(row[key]), columnWidths[key]));\n tableOutput.push(` | ${rowParts.join(' | ')} |`);\n });\n\n return tableOutput;\n};\n\n/**\n * Checks if the cart qualifies for free shipping due to subscription items,\n * based on the progress bar's settings.\n *\n * @param {StorefrontCartData|null} cart The current storefront cart data.\n * @param {TieredProgressBar|null} bar The active progress bar configuration.\n *\n * @returns {boolean} True if free shipping on subscription is active, false otherwise.\n */\nexport const checkHasFreeShippingOnSubscription = (\n cart: StorefrontCartData | null,\n bar: TieredProgressBar | null\n): boolean => {\n if (!bar?.free_shipping_on_subscription || !cart?.lines) {\n return false;\n }\n\n const hasShippingTier = bar.tiers.some((tier) => tier.type === TieredProgressBarTierType.SHIPPING);\n\n if (!hasShippingTier) {\n return false;\n }\n\n let actualCartLineNodes: Readonly<CartLine>[] = [];\n\n try {\n actualCartLineNodes = flattenConnection(cart.lines) as Readonly<CartLine>[];\n } catch (error) {\n rebuyDebugLog.warn('checkHasFreeShippingOnSubscription: Failed to flatten cart.lines connection.', error);\n }\n\n return actualCartLineNodes.some((lineNode) => {\n const line = lineNode as CartLine;\n\n return !isTieredProgressBarGiftItem(line) && isSubscriptionItem(line);\n });\n};\n\n/**\n * Checks if a specific tier has been reached based on the current subtotal\n * and free shipping on subscription status.\n *\n * @param {TieredProgressBarTier} tier The tier configuration.\n * @param {number} currentSubtotal The current progress bar subtotal.\n * @param {boolean} hasFreeShippingOnSubscription Whether free shipping on subscription is active.\n *\n * @returns {boolean} True if the tier is reached, false otherwise.\n */\nexport const checkIsTierReached = (\n tier: TieredProgressBarTier,\n currentSubtotal: number,\n hasFreeShippingOnSubscription: boolean\n): boolean => {\n if (!tier) return false;\n\n const minimum = getTierMinimum(tier);\n\n if (tier.type === TieredProgressBarTierType.SHIPPING && hasFreeShippingOnSubscription) return true;\n\n return currentSubtotal >= minimum;\n};\n\n/**\n * Updates the session storage cache for declined gifts.\n * This cache helps persist user choices across page loads within the same session.\n *\n * @param {Record<string, boolean>} newDeclinedMap A record object where keys are decline keys (from `getDeclineKey`)\n * and values are booleans indicating if the gift is declined.\n *\n * @returns {void}\n */\nexport const updateDeclinedCache = (newDeclinedMap: Record<string, boolean>): void => {\n try {\n const cachedDataString = sessionStorage.getItem(SessionStorageKey.TIERED_PROGRESS_BAR_GIFT_DATA);\n const cachedData: TieredProgressBarCachedGiftData | null = safeJsonParse(cachedDataString);\n\n const newCache: TieredProgressBarCachedGiftData = {\n ...(cachedData ?? { products: [], timestamp: 0 }),\n declined: newDeclinedMap,\n timestamp: cachedData?.timestamp ?? Date.now(),\n };\n sessionStorage.setItem(SessionStorageKey.TIERED_PROGRESS_BAR_GIFT_DATA, JSON.stringify(newCache));\n } catch (error) {\n console.error('[progressBarUtils] Failed to update declined cache:', error);\n }\n};\n\n/**\n * Calculates the visual progress bar percentage based on legacy logic for visual alignment.\n * This logic often involves adjusting segment calculations (e.g., dividing by 2)\n * to better align the visual progress with tier markers.\n *\n * @param {TieredProgressBar|null} barConfig The active progress bar configuration.\n * @param {number} subtotal The current subtotal for progress calculation.\n * @param {boolean} hasFreeShippingOnSubscription Whether free shipping is achieved via subscription.\n *\n * @returns {number} The calculated visual percentage (0-100).\n */\nexport const calculateVisualProgressBarPercentage = (\n barConfig: TieredProgressBar | null,\n subtotal: number,\n hasFreeShippingOnSubscription: boolean\n): number => {\n if (!barConfig || !barConfig.tiers || barConfig.tiers.length === 0) {\n return 0;\n }\n\n const allTiers = barConfig.tiers;\n\n if (subtotal <= 0) {\n return 0;\n }\n\n // Check if the very last tier in the definition is met.\n // `checkIsTierReached` handles FSoS for shipping tiers.\n const lastOverallTier = allTiers[allTiers.length - 1];\n\n if (checkIsTierReached(lastOverallTier, subtotal, hasFreeShippingOnSubscription)) {\n // If the last tier is $0 minimum, it's reached if subtotal > 0.\n // If its minimum is > $0, checkIsTierReached already confirms subtotal meets it.\n if (getTierMinimum(lastOverallTier) <= 0 && subtotal > 0) return 100;\n\n if (getTierMinimum(lastOverallTier) > 0) return 100;\n }\n\n let percentage = 0;\n const firstTier = allTiers[0];\n const firstTierMinimum = getTierMinimum(firstTier);\n\n // Logic for single tier (matches legacy specific handling for 1 tier)\n if (allTiers.length === 1) {\n if (firstTierMinimum > 0) {\n percentage = (subtotal / firstTierMinimum) * 100;\n } else {\n // Tier minimum is $0 or less\n percentage = subtotal > 0 ? 100 : 0; // Reached if any subtotal\n }\n }\n // Logic for multiple tiers (incorporates the \"dividing by 2\" visual adjustment)\n else {\n const tierPercentageSize = 100 / allTiers.length;\n const completedTiers = allTiers.filter((tier) =>\n checkIsTierReached(tier, subtotal, hasFreeShippingOnSubscription)\n );\n\n if (completedTiers.length === 0) {\n if (firstTierMinimum > 0) {\n percentage = (subtotal / firstTierMinimum) * (tierPercentageSize / 2);\n } else {\n // First tier is $0, but not considered \"completed\" if subtotal is $0.\n // If subtotal > 0 and firstTierMinimum is $0, completedTiers would not be 0.\n percentage = 0;\n }\n } else {\n // At least one tier completed\n percentage = completedTiers.length * tierPercentageSize - tierPercentageSize / 2;\n\n const lastCompletedTier = completedTiers[completedTiers.length - 1];\n const lastCompletedTierMinimum = getTierMinimum(lastCompletedTier);\n\n // Find the next tier that is not yet completed\n let nextIncompleteTier: TieredProgressBarTier | undefined = undefined;\n const lastCompletedTierIndex = allTiers.findIndex((t) => t.id === lastCompletedTier.id);\n\n if (lastCompletedTierIndex !== -1 && lastCompletedTierIndex < allTiers.length - 1) {\n for (let i = lastCompletedTierIndex + 1; i < allTiers.length; i++) {\n if (!checkIsTierReached(allTiers[i], subtotal, hasFreeShippingOnSubscription)) {\n nextIncompleteTier = allTiers[i];\n break;\n }\n }\n }\n\n if (nextIncompleteTier) {\n const spendSinceLastTier = subtotal - lastCompletedTierMinimum;\n // Monetary distance of the current progress segment (from last completed to next incomplete)\n const segmentMonetaryLength = getTierMinimum(nextIncompleteTier) - lastCompletedTierMinimum;\n\n if (segmentMonetaryLength > 0) {\n percentage += (spendSinceLastTier / segmentMonetaryLength) * tierPercentageSize;\n } else if (spendSinceLastTier > 0 && segmentMonetaryLength <= 0) {\n // Edge case: next tier min is <= last completed min. If spent more, count full segment.\n percentage += tierPercentageSize;\n }\n }\n // If no nextIncompleteTier, all tiers are complete. The top 100% check should handle this.\n }\n }\n\n return Math.min(Math.max(0, percentage), 100);\n};\n", "// ~/smart-cart/components/TieredProgressBar/Icons.tsx\n\n// eslint-disable-next-line no-restricted-imports\n\n// TODO: Use an icon library, maybe?\n\nexport const CheckIcon = () => (\n <svg fill=\"none\" height=\"8\" viewBox=\"0 0 9 8\" width=\"9\" xmlns=\"http://www.w3.org/2000/svg\">\n <path\n d=\"M2.82415 6.15237L0.726419 4.05464L0.012085 4.76395L2.82415 7.57601L8.86078 1.53938L8.15147 0.830078L2.82415 6.15237Z\"\n fill=\"currentColor\"\n />\n </svg>\n);\n\nexport const ShippingIcon = () => (\n <svg\n fill=\"none\"\n height=\"16\"\n viewBox=\"0 0 21 16\"\n width=\"21\"\n xmlns=\"http://www.w3.org/2000/svg\" /* style={{ transform: 'scale(0.8)', transformOrigin: 'center' }} */\n >\n <path\n d=\"M17.6392 4.49332H14.9621V0.923828H2.46883C1.48722 0.923828 0.684082 1.72696 0.684082 2.70857V12.5247H2.46883C2.46883 14.006 3.66461 15.2018 5.14595 15.2018C6.62729 15.2018 7.82307 14.006 7.82307 12.5247H13.1773C13.1773 14.006 14.3731 15.2018 15.8544 15.2018C17.3358 15.2018 18.5315 14.006 18.5315 12.5247H20.3163V8.06281L17.6392 4.49332ZM17.193 5.83188L18.942 8.06281H14.9621V5.83188H17.193ZM5.14595 13.4171C4.65514 13.4171 4.25357 13.0155 4.25357 12.5247C4.25357 12.0339 4.65514 11.6323 5.14595 11.6323C5.63675 11.6323 6.03832 12.0339 6.03832 12.5247C6.03832 13.0155 5.63675 13.4171 5.14595 13.4171ZM7.12702 10.7399C6.63621 10.1956 5.94016 9.84756 5.14595 9.84756C4.35174 9.84756 3.65568 10.1956 3.16488 10.7399H2.46883V2.70857H13.1773V10.7399H7.12702ZM15.8544 13.4171C15.3636 13.4171 14.9621 13.0155 14.9621 12.5247C14.9621 12.0339 15.3636 11.6323 15.8544 11.6323C16.3452 11.6323 16.7468 12.0339 16.7468 12.5247C16.7468 13.0155 16.3452 13.4171 15.8544 13.4171Z\"\n fill=\"currentColor\"\n />\n </svg>\n);\n\nexport const DiscountIcon = () => (\n <svg\n fill=\"none\"\n height=\"24\"\n style={{ transform: 'scale(0.75)', transformOrigin: 'center' }}\n viewBox=\"0 0 24 24\"\n width=\"24\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n d=\"M21.408 11.4124L12.578 2.58244C12.208 2.21244 11.698 2.00244 11.168 2.00244H3.99805C2.89805 2.00244 1.99805 2.90244 1.99805 4.00244V11.1724C1.99805 11.7024 2.20805 12.2124 2.58805 12.5824L11.418 21.4124C12.198 22.1924 13.468 22.1924 14.248 21.4124L21.418 14.2424C22.198 13.4624 22.198 12.2024 21.408 11.4124ZM12.828 20.0024L3.99805 11.1724V4.00244H11.168L19.998 12.8324L12.828 20.0024Z\"\n fill=\"currentColor\"\n />\n <path\n d=\"M6.49805 8.00244C7.32647 8.00244 7.99805 7.33087 7.99805 6.50244C7.99805 5.67401 7.32647 5.00244 6.49805 5.00244C5.66962 5.00244 4.99805 5.67401 4.99805 6.50244C4.99805 7.33087 5.66962 8.00244 6.49805 8.00244Z\"\n fill=\"currentColor\"\n />\n </svg>\n);\n\nexport const GiftIcon = () => (\n <svg\n fill=\"none\"\n height=\"18\"\n style={{ transform: 'scale(0.9)', transformOrigin: 'center' }}\n viewBox=\"0 0 15 18\"\n width=\"15\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n d=\"M12.7808 3.71012H10.9961C10.9961 1.73797 9.39873 0.140625 7.42658 0.140625C5.45444 0.140625 3.85709 1.73797 3.85709 3.71012H2.07234C1.09073 3.71012 0.287598 4.51325 0.287598 5.49486V16.2033C0.287598 17.185 1.09073 17.9881 2.07234 17.9881H12.7808C13.7624 17.9881 14.5656 17.185 14.5656 16.2033V5.49486C14.5656 4.51325 13.7624 3.71012 12.7808 3.71012ZM7.42658 1.92537C8.40819 1.92537 9.21133 2.72851 9.21133 3.71012H5.64184C5.64184 2.72851 6.44497 1.92537 7.42658 1.92537ZM12.7808 16.2033H2.07234V5.49486H3.85709V7.27961C3.85709 7.77042 4.25866 8.17198 4.74946 8.17198C5.24027 8.17198 5.64184 7.77042 5.64184 7.27961V5.49486H9.21133V7.27961C9.21133 7.77042 9.6129 8.17198 10.1037 8.17198C10.5945 8.17198 10.9961 7.77042 10.9961 7.27961V5.49486H12.7808V16.2033Z\"\n fill=\"currentColor\"\n />\n </svg>\n);\n", "// ~/smart-cart/constants.ts\n\n/**\n * Rebuy-specific attribution of the item (ie. key: '_attribution', value: 'Rebuy Buy More Save More')\n */\nexport enum RebuyLineItemAttribution {\n BUY_MORE_SAVE_MORE = 'Rebuy Buy More Save More',\n SWITCH_TO_ONE_TIME = 'Rebuy Switch to One-Time',\n SWITCH_TO_SUBSCRIPTION = 'Rebuy Switch to Subscription',\n TIERED_PROGRESS_BAR = 'Rebuy Tiered Progress Bar',\n}\n\n/**\n * Line Item Attribute Keys (for attribution, tracking, safeguarding discounts, etc.)\n */\nexport enum LineItemAttributeKey {\n /**\n * Rebuy-specific attribution of the item\n */\n ATTRIBUTION = '_attribution',\n /**\n * Quantity before BMSM (not currently used - just an idea if we want to calculate more accurate RGR)\n */\n BMSM_QTY_BEFORE = '_bmsm_qty_before',\n /**\n * Hide quantity selector (ie. for Gift with Purchase items)\n */\n HIDE_QUANTITY_SELECTOR_GWP_ITEM = '_r_gwp_hide_qty',\n\n /**\n * Source of the item (ie. 'Rebuy')\n */\n SOURCE = '_source',\n}\n\nexport enum CartExclusionProductTag {\n /**\n * Exclude items with this tag from cart subtotal used to calculate final display price\n */\n EXCLUDE_FROM_CART_SUBTOTAL = 'smart-cart-subtotal-excluded',\n /**\n * Exclude items with this tag from progress bar subtotal used to calculate thresholds\n */\n EXCLUDE_FROM_PROGRESS_BAR_SUBTOTAL = 'smart-cart-shipping-excluded',\n /**\n * Hide bundle options in cart\n */\n HIDE_BUNDLE_OPTIONS_IN_CART = 'smart-cart-hide-bundle-options',\n /**\n * Hide cart items in the cart display\n */\n HIDE_FROM_CART_ITEMS = 'smart-cart-hidden',\n /**\n * Hide quantity selector in cart\n */\n HIDE_QUANTITY_SELECTOR_IN_CART = 'smart-cart-hide-qty',\n}\n\nexport enum SessionStorageKey {\n TIERED_PROGRESS_BAR_GIFT_DATA = '_r_progress_bar_gift_data',\n}\n\nexport const NO_IMAGE_SHOPIFY_PLACEHOLDER =\n '//cdn.shopify.com/s/files/1/0533/2089/files/placeholder-images-image_large.png?format=webp&v=1530129081';\n", "// ~/smart-cart/utils/moneyUtils.ts\n\n// TODO: REMOVE THIS AND USE npm-rebuy utils instead\nimport type { StorefrontMoney } from '~/smart-cart/types/rebuy-storefront-cart';\n\n/**\n * Formats a numeric amount as a currency string.\n * Uses Intl.NumberFormat for locale-aware formatting when a valid currencyCode is provided.\n * Falls back to simple symbol + fixed decimal formatting otherwise.\n *\n * @param {string|number|undefined|null} amount - The amount as a string or number. Can be null or undefined.\n * @param {string} currencyCodeOrSymbol - The ISO currency code (e.g., 'USD', 'CAD') OR a currency symbol (e.g., '$'). Defaults to '$'.\n * @param {string} locale - Optional locale string (e.g., 'en-US', 'en-CA', 'fr-FR'). Defaults to 'en-US'. Used only with Intl.NumberFormat.\n *\n * @returns {string} Formatted currency string.\n */\nexport const formatMoney = (\n amount: string | number | undefined | null,\n currencyCodeOrSymbol: string = '$', // Default to symbol for simple calls\n locale: string = 'en-US'\n): string => {\n const isCurrencyCode = /^[A-Z]{3}$/.test(currencyCodeOrSymbol); // Simple check for 3 uppercase letters\n\n // --- Handle null/undefined/NaN input ---\n let numericAmount: number;\n\n if (amount === null || amount === undefined) {\n numericAmount = 0;\n } else {\n numericAmount = typeof amount === 'string' ? parseFloat(amount) : amount;\n\n if (isNaN(numericAmount)) {\n console.warn(`formatMoney received non-numeric amount: ${amount}`);\n numericAmount = 0;\n }\n }\n\n // --- Use Intl.NumberFormat if a valid currency code is provided ---\n if (isCurrencyCode) {\n try {\n return new Intl.NumberFormat(locale, {\n currency: currencyCodeOrSymbol, // Use the code\n currencyDisplay: 'symbol',\n style: 'currency',\n }).format(numericAmount);\n } catch (error) {\n console.error(\n `Error formatting money with Intl (Amount: ${amount}, Code: ${currencyCodeOrSymbol}, Locale: ${locale}):`,\n error\n );\n\n // Fallback to simple formatting if Intl fails (e.g., invalid code/locale combo)\n // Use the code as a symbol in this specific error case\n return `${currencyCodeOrSymbol}${numericAmount.toFixed(2)}`;\n }\n }\n\n // --- Fallback to simple formatting (Symbol + Fixed Decimals) ---\n // This handles cases where only amount is passed, or a symbol is passed.\n const symbol = currencyCodeOrSymbol; // Assume it's a symbol if not a code\n\n return `${symbol}${numericAmount.toFixed(2)}`;\n};\n\n/**\n * Gets the maximum amount between a compare-at price and regular price\n *\n * @param {StorefrontMoney} compareAtPrice The compare-at price object with amount string\n * @param {StorefrontMoney} price The regular price object with amount string\n *\n * @returns {number} The higher of the two amounts within each money object\n */\nexport const getMaxAmount = (compareAtPrice: StorefrontMoney | null, price: StorefrontMoney) => {\n if (!compareAtPrice) return parseFloat(price?.amount || '0');\n\n return Math.max(parseFloat(compareAtPrice?.amount || '0'), parseFloat(price?.amount || '0'));\n};\n", "import type { CartLine } from '@shopify/hydrogen/storefront-api-types';\nimport {\n CartExclusionProductTag,\n LineItemAttributeKey,\n NO_IMAGE_SHOPIFY_PLACEHOLDER,\n RebuyLineItemAttribution,\n} from '~/smart-cart/constants';\nimport type {\n AnyCartLine,\n StorefrontAttribute,\n StorefrontAutomaticDiscountAllocation,\n StorefrontCartLine,\n StorefrontCodeDiscountAllocation,\n StorefrontCustomDiscountAllocation,\n StorefrontSellingPlanPriceAdjustment,\n StorefrontTypedDiscountAllocation,\n} from '~/smart-cart/types/rebuy-storefront-cart';\nimport type { BuyMoreSaveMoreTier, SmartCartConfig, SwitchToSubscriptionLanguage } from '~/smart-cart/types/smart-cart';\nimport { formatMoney } from '~/smart-cart/utils/moneyUtils';\n\n// *== General Helpers ==*\n\n/**\n * Checks standard hide conditions (tags, specific attributes like _type=child)\n * Does NOT check for TPB gifts based on mode - that's handled in CartItemList filter.\n *\n * @param {AnyCartLine} line - The line item to check\n *\n * @returns {boolean} true if the line item is hidden by standard logic, false otherwise\n */\nexport const isCartItemHiddenByStandardLogic = (line: AnyCartLine): boolean => {\n // Legacy: Hide items with _type === 'child', potentially from an old bundle feature?\n if (line.attributes?.some((attr) => attr.key === '_type' && attr.value === 'child')) {\n return true;\n }\n\n // Check for specific product tag to hide from cart items\n const tags = line.merchandise?.product?.tags ?? [];\n\n if (tags.includes(CartExclusionProductTag.HIDE_FROM_CART_ITEMS)) {\n return true;\n }\n\n // Check for specific line item property (attribute) if needed\n if (line.attributes?.some((attr) => attr.key === LineItemAttributeKey.HIDE_QUANTITY_SELECTOR_GWP_ITEM)) {\n return true;\n }\n\n return false;\n};\n\n/**\n * Identifies if a line item is a subscription item based on Storefront API structure\n *\n * @param {StorefrontCartLine} line - The line item to check\n *\n * @returns {boolean} true if the line item is a subscription item, false otherwise\n */\nexport const isSubscriptionItem = (line: StorefrontCartLine): boolean => {\n return !!line?.sellingPlanAllocation;\n};\n\n// *== General Attribute Helpers ==*\n\n/**\n * Merges new/updated attributes into existing, overwriting duplicates.\n *\n * @param {StorefrontAttribute[] | undefined | null} existing - The existing attribute list.\n * @param {StorefrontAttribute[]} newOrUpdated - The new or updated attribute list.\n *\n * @returns {StorefrontAttribute[]} - The merged attribute list.\n */\nexport const mergeAttributes = (\n existing: StorefrontAttribute[] | undefined | null,\n newOrUpdated: StorefrontAttribute[]\n): StorefrontAttribute[] => {\n const map = new Map<string, string | null>();\n (existing ?? []).forEach((attr) => map.set(attr.key, attr.value ?? null));\n newOrUpdated.forEach((attr) => map.set(attr.key, attr.value ?? null));\n\n return Array.from(map, ([key, value]) => ({ key, value }));\n};\n\n/**\n * Removes specified keys from an attribute list.\n *\n * @param {StorefrontAttribute[] | undefined | null} existing - The existing attribute list.\n * @param {string[]} keysToRemove - The keys to remove from the attribute list.\n *\n * @returns {StorefrontAttribute[]} - The filtered attribute list.\n */\nexport const removeAttributes = (\n existing: StorefrontAttribute[] | undefined | null,\n keysToRemove: string[]\n): StorefrontAttribute[] => {\n if (!existing) return [];\n\n return existing.filter((attr) => !keysToRemove.includes(attr.key));\n};\n\n// *== Meta Helpers ==*\n\n/**\n * Generates an alt text for the item image.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {string} The alt text string.\n */\nexport const getItemImageAlt = (line: StorefrontCartLine): string => {\n return line.merchandise.image?.altText || `Image of ${line.merchandise.product.title}`;\n};\n\n/**\n * Generates the URL for a product based on its handle.\n * Assumes standard '/products/' path.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {string} The product URL string.\n */\nexport const getItemURL = (line: StorefrontCartLine): string => {\n return `/products/${line.merchandise.product.handle}`;\n};\n\n/**\n * Generates an ARIA label for the item link.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {string} The ARIA label string.\n */\nexport const getItemLinkLabel = (line: StorefrontCartLine): string => {\n return `View product: ${line.merchandise.product.title}`;\n};\n\n// *== CSS Class Helpers ==*\n\n/**\n * Sanitizes a string for use in CSS class names.\n *\n * @param {string | undefined | null} str - The string to sanitize.\n *\n * @returns {string} The sanitized string.\n */\nconst sanitizeForClass = (str: string | undefined | null): string => {\n if (typeof str !== 'string' || !str) return '';\n\n return str\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '');\n};\n\n/**\n * Generates CSS class names based on product tags.\n * Prefixes tags with 'tag-'.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {string} A string of space-separated class names.\n */\nexport const getItemProductTagsClasses = (line: StorefrontCartLine): string => {\n const tags = line.merchandise.product.tags ?? [];\n\n return tags.map((tag) => `tag-${sanitizeForClass(tag)}`).join(' ');\n};\n\n/**\n * Generates CSS class names based on line item attributes (properties).\n * Creates classes like 'property-key-{key}' and 'property-value-{value}'.\n * Sanitizes key and value for CSS class usage.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {string} A string of space-separated class names.\n */\nexport const getItemAttributeClasses = (line: StorefrontCartLine): string => {\n return (line.attributes || [])\n .map((attr) => `property-key-${sanitizeForClass(attr.key)} property-value-${sanitizeForClass(attr.value)}`)\n .join(' ');\n};\n\n/**\n * Generates a specific class name for a property key.\n * Handles potentially null/undefined values.\n *\n * @param {StorefrontAttribute} property - The attribute object.\n *\n * @returns {string} A CSS class name string.\n */\nexport const getItemPropertyKeyClass = (property: StorefrontAttribute): string => {\n // Ensure key is a string before sanitizing\n const key = typeof property.key === 'string' ? property.key : '';\n\n return `property-key-${sanitizeForClass(key)}`;\n};\n\n/**\n * Generates a specific class name for a property value.\n * Handles potentially null/undefined values.\n *\n * @param {StorefrontAttribute} property - The attribute object.\n *\n * @returns {string} A CSS class name string.\n */\nexport const getItemPropertyValueClass = (property: StorefrontAttribute): string => {\n // Provide default empty string if value is null/undefined\n const value = property.value ?? '';\n\n return `property-value-${sanitizeForClass(value)}`;\n};\n\n// *== Pricing Helpers ==*\n\ntype CalculatedPricing = {\n compareAtDisplayPrice: string | null;\n displayPrice: string;\n hasDiscount: boolean;\n};\n\n/**\n * Calculates display price, compare-at price, and discount status for a line item.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {CalculatedPricing} The calculated pricing data.\n */\nexport const calculatePricingData = (line: StorefrontCartLine): CalculatedPricing => {\n const hasAppliedDiscount = line.discountAllocations && line.discountAllocations.length > 0;\n const totalAmount = parseFloat(line.cost.totalAmount.amount);\n const quantity = line.quantity;\n const amountPerQuantity = parseFloat(line.cost.amountPerQuantity.amount);\n const compareAtAmountPerQuantity = line.cost.compareAtAmountPerQuantity?.amount\n ? parseFloat(line.cost.compareAtAmountPerQuantity.amount)\n : null;\n\n let calculatedDisplayPrice = amountPerQuantity;\n let calculatedCompareAtPrice = compareAtAmountPerQuantity;\n\n if (hasAppliedDiscount && quantity > 0) {\n calculatedDisplayPrice = totalAmount / quantity;\n calculatedCompareAtPrice =\n compareAtAmountPerQuantity && compareAtAmountPerQuantity > amountPerQuantity\n ? compareAtAmountPerQuantity\n : amountPerQuantity;\n } else if (compareAtAmountPerQuantity && compareAtAmountPerQuantity > amountPerQuantity) {\n calculatedDisplayPrice = amountPerQuantity;\n calculatedCompareAtPrice = compareAtAmountPerQuantity;\n } else {\n calculatedDisplayPrice = amountPerQuantity;\n calculatedCompareAtPrice = null;\n }\n\n const displayPriceStr = formatMoney(calculatedDisplayPrice.toString());\n const compareAtDisplayPriceStr = calculatedCompareAtPrice ? formatMoney(calculatedCompareAtPrice.toString()) : null;\n const hasDiscount = !!(\n compareAtDisplayPriceStr &&\n calculatedCompareAtPrice &&\n calculatedCompareAtPrice > calculatedDisplayPrice\n );\n\n return {\n compareAtDisplayPrice: compareAtDisplayPriceStr,\n displayPrice: displayPriceStr,\n hasDiscount: hasDiscount,\n };\n};\n\n// *== Property Helpers ==*\n\n/**\n * Filters and returns visible item properties (attributes), excluding internal ones (_*).\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {StorefrontAttribute[]} The visible properties.\n */\nexport const getVisibleItemProperties = (line: StorefrontCartLine): StorefrontAttribute[] => {\n return (line.attributes || []).filter((attr) => !attr.key.startsWith('_'));\n};\n\n/**\n * Extracts discount allocation messages as properties.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {StorefrontAttribute[]} The discount properties.\n */\nexport const getDiscountProperties = (line: StorefrontCartLine): StorefrontAttribute[] => {\n const allocations = line.discountAllocations ?? [];\n const messages: StorefrontAttribute[] = [];\n\n allocations.forEach((alloc: StorefrontTypedDiscountAllocation) => {\n let discountMessage: string | null = null;\n\n // Use type guards or __typename to determine the correct property\n switch (alloc.__typename) {\n case 'CartAutomaticDiscountAllocation':\n case 'CartCustomDiscountAllocation':\n // These types have 'title'\n // Need to cast to access the title property safely\n discountMessage = (alloc as StorefrontAutomaticDiscountAllocation | StorefrontCustomDiscountAllocation)\n .title;\n break;\n case 'CartCodeDiscountAllocation': {\n // This type has 'code'\n // Need to cast to access the code property safely\n const code = (alloc as StorefrontCodeDiscountAllocation).code; // Declaration is now safe inside the block scope\n // Optionally add prefix/suffix for codes\n discountMessage = code ? `Code: ${code}` : null; // Example: Prefix with \"Code: \"\n break;\n }\n default: {\n // Handle unexpected allocation types (unlikely)\n const unknownAlloc = alloc as { __typename?: string };\n console.warn('[cartItemUtils] Unknown discount allocation type:', unknownAlloc.__typename);\n break;\n }\n }\n\n if (discountMessage) {\n messages.push({\n key: '_Discount', // Consistent key for styling\n value: discountMessage,\n });\n }\n });\n\n return messages;\n};\n\n/**\n * Extracts the delivery frequency string if item is a subscription.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {string | null} The delivery frequency string, or null if not a subscription.\n */\nexport const getItemDeliveryFrequency = (line: StorefrontCartLine): string | null => {\n // Primarily relies on selling plan allocation name\n if (line.sellingPlanAllocation) {\n return line.sellingPlanAllocation.sellingPlan.name;\n }\n\n // Add fallback logic for properties if necessary (legacy support?)\n return null;\n};\n\n// *== Buy More Save More (BMSM) Utilities ==*\n\n/**\n * Checks if Buy More Save More is enabled in the configuration.\n *\n * @param {SmartCartConfig | null} config The smart cart configuration.\n *\n * @returns {boolean} True if BMSM is enabled.\n */\nexport const isBMSMEnabled = (config: SmartCartConfig | null): boolean => {\n return config?.buy_more_save_more_enabled ?? false;\n};\n\n/**\n * Checks if a specific item is eligible for the Buy More Save More promotion.\n * Compares the item's product/variant ID against the configured list.\n * NOTE: Assumes config.buy_more_save_more.discount_products structure based on legacy code.\n * You might need to adjust based on the actual structure in your `SmartCartConfig`.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n * @param {SmartCartConfig|null} config - The cart configuration.\n *\n * @returns {boolean} True if the item is eligible for BMSM, false otherwise.\n */\nexport const itemHasBMSM = (line: StorefrontCartLine, config: SmartCartConfig | null): boolean => {\n if (!isBMSMEnabled(config)) return false;\n\n // Check if product/variant is eligible\n const bmsmSettings = config?.buy_more_save_more;\n const eligibleItems = bmsmSettings?.discount_products ?? [];\n\n // Extract necessary IDs from the line item\n // Storefront API uses GIDs like \"gid://shopify/Product/12345\"\n // Legacy config likely uses numeric IDs. We need to extract the numeric part.\n const getNumericId = (gid: string | undefined): number | null => {\n if (!gid) return null;\n\n const match = gid.match(/\\/(\\d+)$/);\n\n return match ? parseInt(match[1], 10) : null;\n };\n\n const numericProductId = getNumericId(line.merchandise.product.id);\n const numericVariantId = getNumericId(line.merchandise.id);\n\n if (!numericProductId || !numericVariantId) {\n console.warn('[SmartCartReact] Could not extract numeric ID for BMSM check:', line);\n\n return false; // Cannot check eligibility without numeric IDs matching config\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const foundEligibleItem = eligibleItems.find((product: any) => {\n // TODO: update product type\n // Use 'any' temporarily if config type isn't precise\n // If specific variants have been selected in config\n if (product.variant_ids && product.variant_ids.length > 0) {\n return product.variant_ids.some((configVariantId: number) => configVariantId === numericVariantId);\n }\n\n // If no specific variants, check product ID\n return product.product_id === numericProductId;\n });\n\n // TODO: Consider adding the _rebuyCartId cart attribute update logic here or elsewhere\n // if BMSM + Shopify Functions integration is needed. See legacy code.\n // This usually involves calling Cart.updateItem({ attributes: { _rebuyCartId: ... } })\n // which is a *cart* update, not a line item update. Needs careful placement.\n\n return !!foundEligibleItem; // Return true if an eligible configuration was found\n};\n\n/**\n * Gets the configured BMSM tiers from config, ensuring quantity and discount are numbers.\n *\n * @param {SmartCartConfig | null} config - The cart configuration.\n *\n * @returns {Array<BuyMoreSaveMoreTier>} Array of tier objects with numeric quantity/discount.\n */\nexport const getBMSMTiers = (config: SmartCartConfig | null): BuyMoreSaveMoreTier[] => {\n const tiers = config?.buy_more_save_more?.tiers ?? [];\n\n // Ensure quantity and discount are numbers, provide defaults if missing/invalid\n return tiers\n .map((tier) => ({\n discount: typeof tier.discount === 'number' ? tier.discount : 0,\n quantity: typeof tier.quantity === 'number' ? tier.quantity : 0,\n }))\n .filter((tier) => tier.quantity > 0); // Only include tiers with a quantity\n};\n\n/**\n * Checks if the final BMSM tier has been reached for this item.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n * @param {SmartCartConfig|null} config - The cart configuration.\n *\n * @returns {boolean} True if the final tier has not been reached, false otherwise.\n */\nexport const bMSMFinalTierNotReached = (line: StorefrontCartLine, config: SmartCartConfig | null): boolean => {\n const tiers = getBMSMTiers(config);\n\n if (!tiers.length) return false; // No tiers means no BMSM applies or final tier is irrelevant\n\n const maxTierQuantity = Math.max(...tiers.map((t) => t.quantity ?? 0));\n\n return line.quantity < maxTierQuantity;\n};\n\n/**\n * Checks if BMSM should be displayed as buttons based on config.\n *\n * @param {SmartCartConfig|null} config - The cart configuration.\n *\n * @returns {boolean} True if BMSM should be displayed as buttons, false otherwise.\n */\nexport const hasBMSMButtons = (config: SmartCartConfig | null): boolean => {\n return config?.buy_more_save_more?.display_type === 'buttons';\n};\n\n/**\n * Generates the text for a BMSM tier button based on language settings.\n * Handles placeholders for {{quantity}} and {{discount}}.\n *\n * @param {BuyMoreSaveMoreTier} tier - The tier object.\n * @param {SmartCartConfig|null} config - The cart configuration.\n *\n * @returns {string} The button text.\n */\nexport const getBMSMButtonText = (tier: BuyMoreSaveMoreTier, config: SmartCartConfig | null): string => {\n const bmsmSettings = config?.buy_more_save_more;\n const language = bmsmSettings?.language;\n const discountType = bmsmSettings?.discount_type;\n\n // Default template if not found in config\n const template = language?.bmsm_discount_message || 'Buy {{quantity}}, save {{discount}}%';\n\n const discountValue = tier.discount;\n const discountText =\n discountType === 'percentage'\n ? `${discountValue}%`\n : // Assume fixed amount needs formatting (requires currency info)\n // For now, just display the number if not percentage. Refine if needed.\n formatMoney(discountValue?.toString() ?? ''); // Assuming formatMoney handles fixed amounts\n\n // Basic replacement\n let buttonText = template.replace(/\\{\\{\\s*quantity\\s*\\}\\}/gi, tier.quantity?.toString() ?? '');\n buttonText = buttonText.replace(/\\{\\{\\s*discount\\s*\\}\\}/gi, discountText);\n\n // Support legacy {{difference}} placeholder for buttons as well if needed\n // buttonText = buttonText.replace(/\\{\\{\\s*difference\\s*\\}\\}/gi, tier.quantity.toString());\n\n return buttonText;\n};\n\n/**\n * Generates the dynamic text message for BMSM (when not using buttons).\n * Finds the next applicable tier and formats the message.\n * Handles placeholders for {{quantity}}, {{difference}}, and {{discount}}.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n * @param {SmartCartConfig|null} config - The cart configuration.\n *\n * @returns {string} The dynamic text message, or empty string if no next tier.\n */\nexport const buyMoreSaveMoreDynamicText = (line: StorefrontCartLine, config: SmartCartConfig | null): string => {\n const tiers = getBMSMTiers(config);\n const bmsmSettings = config?.buy_more_save_more;\n const language = bmsmSettings?.language;\n const discountType = bmsmSettings?.discount_type;\n\n // Default template if not found in config\n const template = language?.bmsm_discount_message || 'Buy {{difference}} more to save {{discount}}%';\n\n // Find the *next* tier quantity greater than the current item quantity\n const nextTier = tiers\n .filter((tier) => tier.quantity && tier.quantity > line.quantity)\n .sort((a, b) => (a.quantity ?? 0) - (b.quantity ?? 0))[0]; // Get the lowest tier above current quantity\n\n if (!nextTier) {\n return ''; // No next tier available or already at max tier\n }\n\n const quantityDifference = (nextTier.quantity ?? 0) - (line.quantity ?? 0);\n const discountValue = nextTier.discount;\n const discountText =\n discountType === 'percentage' ? `${discountValue}%` : formatMoney(discountValue?.toString() ?? ''); // Assuming formatMoney handles fixed amounts\n\n // Replace placeholders\n let dynamicText = template.replace(/\\{\\{\\s*difference(_next_quantity)?\\s*\\}\\}/gi, quantityDifference.toString()); // Support legacy 'difference_next_quantity'\n dynamicText = dynamicText.replace(/\\{\\{\\s*quantity\\s*\\}\\}/gi, quantityDifference.toString()); // Also support 'quantity' for difference\n dynamicText = dynamicText.replace(/\\{\\{\\s*discount\\s*\\}\\}/gi, discountText);\n\n return dynamicText;\n};\n\n// *== Subscription Utilities ==*\n\n/**\n * Extracts available selling plans from the cart line's product data.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {Array<{id: string, name: string, adjustments: StorefrontSellingPlanPriceAdjustment[] | null}>} - Array of selling plan details.\n */\nexport const getAvailableSellingPlans = (\n line: StorefrontCartLine\n): {\n adjustments: StorefrontSellingPlanPriceAdjustment[] | null;\n id: string;\n name: string;\n}[] => {\n const groups = line.merchandise.product.sellingPlanGroups?.edges ?? [];\n\n return groups.flatMap((groupEdge) => {\n const planEdge = groupEdge?.node?.sellingPlans?.edges?.[0];\n const planNode = planEdge?.node;\n\n if (planNode) {\n return [\n {\n adjustments: planNode.priceAdjustments ?? null,\n id: planNode.id,\n name: planNode.name,\n },\n ];\n }\n\n return [];\n });\n};\n\n/**\n * Calculates the discount percentage for the first selling plan.\n *\n * @param {Array<{adjustments: StorefrontSellingPlanPriceAdjustment[] | null}>} sellingPlans - Array of selling plan details.\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {number} - The calculated discount percentage.\n */\nexport const calculateDefaultSellingPlanDiscount = (\n sellingPlans: {\n adjustments: StorefrontSellingPlanPriceAdjustment[] | null;\n }[],\n line: StorefrontCartLine\n): number => {\n if (sellingPlans.length === 0) return 0;\n\n const defaultPlan = sellingPlans[0];\n const adjustments = defaultPlan.adjustments;\n const basePrice = parseFloat(line.merchandise.price.amount);\n\n if (!adjustments || adjustments.length === 0 || basePrice <= 0) return 0;\n\n const firstAdjustment = adjustments[0];\n\n if (!firstAdjustment?.adjustmentValue) return 0;\n\n const adjustmentValue = firstAdjustment.adjustmentValue;\n\n // Check for percentage adjustment\n if ('adjustmentPercentage' in adjustmentValue) {\n return Math.max(0, adjustmentValue.adjustmentPercentage);\n }\n\n // If we have an amount adjustment\n if ('adjustmentAmount' in adjustmentValue) {\n const discountAmount = parseFloat(adjustmentValue.adjustmentAmount.amount);\n\n if (discountAmount > 0) {\n // Calculate percentage and round to integer\n return Math.round((discountAmount / basePrice) * 100);\n }\n }\n\n return 0;\n};\n\n/**\n * Gets STS language string, replacing discount placeholder if applicable.\n *\n * @param {keyof SwitchToSubscriptionLanguage} key - The language key.\n * @param {SmartCartConfig | null} config - The cart configuration.\n * @param {number} discountPercent - The discount percentage.\n * @param {string} fallback - The fallback language string.\n *\n * @returns {string} - The formatted language string.\n */\nexport const getSwitchToSubscriptionLabelWithDiscount = (\n key: keyof SwitchToSubscriptionLanguage,\n config: SmartCartConfig | null,\n discountPercent: number,\n fallback?: string\n): string => {\n const language = config?.switch_to_subscription?.language;\n const labelTemplate = language?.[key] ?? fallback ?? key.toString();\n\n if ((key === 'upgrade_to_subscription_label' || key === 'subscription_option_group_label') && discountPercent > 0) {\n return labelTemplate.replace('{{subscription_discount}}', discountPercent.toString());\n }\n\n return labelTemplate;\n};\n\n// *== Bundle Product (Shopify Bundles) Utility Placeholders ==*\n\n// ! Note: Bundles will not be supported on release of this feature.\n// ! This code is provided as a reference for future implementation.\n\n/**\n * Placeholder: Checks if an item represents a bundle.\n * Implement this based on how bundles are identified (e.g., product type, tags, properties).\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {boolean} True if the item is a bundle, false otherwise.\n */\nexport const itemIsBundle = (line: StorefrontCartLine): boolean => {\n // Example: return line.merchandise.product.productType === 'Bundle';\n // Example: return line.merchandise.product.tags.includes('bundle');\n return false; // Placeholder\n};\n\n/**\n * Placeholder: Checks if bundle options should be hidden for this item.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {boolean} True if bundle options should be hidden, false otherwise.\n */\nexport const hideBundleOptions = (line: StorefrontCartLine): boolean => {\n return false; // Placeholder\n};\n\n/**\n * Placeholder: Gets the number of items within a bundle.\n * Requires specific logic based on bundle representation.\n *\n * @param {StorefrontCartLine} line - The cart line item.\n *\n * @returns {number} The number of items in the bundle.\n */\nexport const getItemBundleLength = (line: StorefrontCartLine): number => {\n // Example: Check a property like '_bundle_items_count'\n return 0; // Placeholder\n};\n\n/**\n * Placeholder: Gets the image URL for a specific option within a bundle.\n * Requires specific logic based on bundle representation and product data.\n *\n * @param {unknown} product - The product object.\n * @param {unknown} option - The bundle option object.\n * @param {number} index - The index of the option.\n *\n * @returns {string} The image URL.\n */\nexport const getBundleOptionImage = (product: unknown, option: unknown, index: number): string => {\n // Needs implementation based on how bundle option images are stored/linked\n return NO_IMAGE_SHOPIFY_PLACEHOLDER; // Placeholder\n};\n\n/**\n * Placeholder: Gets the title for a child item/option within a bundle.\n *\n * @param {any} option - The bundle option object.\n *\n * @returns {string} The title of the child bundle item.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const getChildBundleTitle = (option: any): string => {\n // Needs implementation based on bundle option data structure\n return option?.name || 'Bundle Item'; // Placeholder\n};\n\n// * == Tiered Progress Bar ==*\n\n/**\n * Identifies if a line item is a gift from the tiered progress bar\n *\n * @param {CartLine} line - The line item to check\n *\n * @returns {boolean} true if the line item is a gift from the tiered progress bar, false otherwise\n */\nexport const isTieredProgressBarGiftItem = (line: CartLine): boolean => {\n return line?.attributes?.some(\n (attr: StorefrontAttribute) =>\n attr.key === '_attribution' && attr.value === RebuyLineItemAttribution.TIERED_PROGRESS_BAR\n );\n};\n", "// TODO: REMOVE THIS AND USE npm-rebuy utils instead\n\nexport const safeJsonParse = <T>(jsonString: string | null | undefined): T | null => {\n if (!jsonString) return null;\n try {\n return JSON.parse(jsonString) as T;\n } catch (e) {\n console.error('[safeJsonParse] Failed to parse JSON string:', e, jsonString);\n\n return null;\n }\n};\n", "import type { Cart as HydrogenStorefrontApiCart } from '@shopify/hydrogen/storefront-api-types';\nimport { DebugKey } from '~/constants/debug';\nimport type {\n StorefrontAttribute,\n StorefrontBuyerIdentity,\n StorefrontCartData,\n StorefrontCartLine,\n StorefrontDiscountCode,\n StorefrontTypedDiscountAllocation,\n} from '~/smart-cart/types/rebuy-storefront-cart';\n\nimport type { ContextParameters, RawCartLine } from '~/types/rebuyCustom';\nimport { rebuyDebugLog } from './debugLog';\n\n/**\n * Maps the cart data structure from RebuyContext.contextParameters\n * (derived from Hydrogen/Hydrogen React cart) to the StorefrontCartData shape.\n * Since StorefrontCartData now aliases HydrogenCart, this is a simplified pass-through.\n *\n * @param {HydrogenStorefrontApiCart | Partial<HydrogenStorefrontApiCart> | null | undefined} cartSource - The primary cart data object.\n * @param {ContextParameters | null | undefined} contextParameters - Additional context parameters, used for fallback or supplementary data.\n * @returns {StorefrontCartData | null} - The cart data, or null if essential data is missing.\n */\nexport const mapHydrogenCartToStorefrontCartData = (\n cartSource: HydrogenStorefrontApiCart | Partial<HydrogenStorefrontApiCart> | null | undefined,\n contextParameters: ContextParameters | null | undefined\n): StorefrontCartData | null => {\n // If a direct cartSource is provided and it's valid, use it\n if (cartSource && typeof cartSource === 'object' && cartSource.id) {\n rebuyDebugLog.log(DebugKey.CART_MAPPER, 'Using provided cartSource for mapping.');\n\n return { ...cartSource } as StorefrontCartData;\n }\n\n // Fallback: If no direct cartSource, try getting hydrogenCart from contextParameters\n if (contextParameters?.hydrogenCart) {\n rebuyDebugLog.log(DebugKey.CART_MAPPER, 'Using direct hydrogenCart from contextParameters.');\n\n return { ...contextParameters.hydrogenCart } as StorefrontCartData;\n }\n\n // Fall back to legacy approach using other fields from contextParameters\n if (!contextParameters?.cartId || !contextParameters.cartCost) {\n rebuyDebugLog.warn(\n DebugKey.CART_MAPPER,\n 'Cannot map cart: No valid cartSource provided, and missing contextParameters.cartId or contextParameters.cartCost for legacy mapping.'\n );\n\n return null;\n }\n\n rebuyDebugLog.log(\n DebugKey.CART_MAPPER,\n 'No direct cart object available. Falling back to legacy mapping approach using contextParameters fields.'\n );\n\n const sourceCartId = contextParameters.cartId;\n const sourceCartLines = contextParameters.cartLines ?? [];\n const sourceCartAttributes = contextParameters.cartAttributes ?? [];\n const sourceCartNote = contextParameters.cartNote ?? null;\n const sourceCheckoutUrl = contextParameters.checkoutUrl ?? '';\n const sourceDiscounts = contextParameters.discountCodes ?? [];\n const sourceCartCost = contextParameters.cartCost;\n\n try {\n // --- Map Lines ---\n const mappedLinesEdges = sourceCartLines.map((line: RawCartLine) => {\n const lineNode: StorefrontCartLine = {\n __typename: 'CartLine',\n attributes: (line.attributes ?? []).map((attr) => ({ key: attr.key, value: String(attr.value ?? '') })),\n cost: line.cost,\n discountAllocations: (line.discountAllocations ?? []).map((da) => ({ ...da })),\n estimatedCost: line.estimatedCost ?? null,\n id: line.id,\n merchandise: line.merchandise,\n quantity: line.quantity,\n sellingPlanAllocation: line.sellingPlanAllocation ?? null,\n };\n\n return { cursor: '', node: lineNode };\n });\n\n // --- Map Cart Attributes ---\n const mappedAttributes: StorefrontAttribute[] = sourceCartAttributes.map((attr) => ({\n key: attr.key,\n value: String(attr.value ?? ''),\n }));\n\n // --- Map Buyer Identity ---\n const mappedBuyerIdentity: StorefrontBuyerIdentity = {\n __typename: 'CartBuyerIdentity',\n countryCode: null,\n customer: null,\n deliveryAddressPreferences: [],\n email: null,\n phone: null,\n };\n\n // --- Map Discount Codes ---\n const mappedDiscountCodes: StorefrontDiscountCode[] = sourceDiscounts.map((dc) => ({\n __typename: 'CartDiscountCode',\n applicable: dc.applicable,\n code: dc.code,\n }));\n\n // --- Assemble Final Mapped Cart ---\n const mappedCart: Partial<StorefrontCartData> = {\n __typename: 'Cart',\n appliedGiftCards: [],\n attributes: mappedAttributes,\n buyerIdentity: mappedBuyerIdentity,\n checkoutUrl: sourceCheckoutUrl,\n cost: {\n __typename: 'CartCost',\n subtotalAmount: sourceCartCost.subtotalAmount,\n totalAmount: sourceCartCost.totalAmount,\n } as StorefrontCartData['cost'],\n createdAt: new Date().toISOString(),\n delivery: {\n __typename: 'CartDelivery',\n addresses: [],\n },\n deliveryGroups: {\n __typename: 'CartDeliveryGroupConnection',\n edges: [],\n nodes: [],\n pageInfo: {\n endCursor: null,\n hasNextPage: false,\n hasPreviousPage: false,\n startCursor: null,\n },\n },\n discountAllocations: [] as StorefrontTypedDiscountAllocation[],\n discountCodes: mappedDiscountCodes,\n estimatedCost: {\n __typename: 'CartEstimatedCost',\n checkoutChargeAmount: {\n __typename: 'MoneyV2',\n amount: '0',\n currencyCode: 'USD',\n },\n subtotalAmount: {\n __typename: 'MoneyV2',\n amount: '0',\n currencyCode: 'USD',\n },\n totalAmount: {\n __typename: 'MoneyV2',\n amount: '0',\n currencyCode: 'USD',\n },\n },\n id: sourceCartId,\n lines: {\n __typename: 'BaseCartLineConnection',\n edges: mappedLinesEdges,\n nodes: mappedLinesEdges.map((edge) => edge.node),\n pageInfo: {\n endCursor: null,\n hasNextPage: false,\n hasPreviousPage: false,\n startCursor: null,\n },\n },\n metafields: [],\n note: sourceCartNote,\n totalQuantity: sourceCartLines.reduce((sum, line) => sum + line.quantity, 0),\n updatedAt: new Date().toISOString(),\n };\n\n rebuyDebugLog.log(DebugKey.CART_MAPPER, 'Legacy mapping successful:', mappedCart);\n\n return mappedCart as StorefrontCartData;\n } catch (error) {\n rebuyDebugLog.error(DebugKey.CART_MAPPER, 'Error during legacy cart mapping:', error);\n\n return null;\n }\n};\n", "import * as Utilities from '@rebuy/rebuy/utilities';\nimport type {\n Attribute,\n BaseCartLineConnection,\n CartAutomaticDiscountAllocation,\n CartCodeDiscountAllocation,\n CartCustomDiscountAllocation,\n CartDeliveryGroupConnection,\n CartDiscountCode,\n CartLine,\n ComponentizableCartLine,\n CurrencyCode,\n CartBuyerIdentity as HydrogenCartBuyerIdentity,\n CartCost as HydrogenCartCost,\n MoneyV2 as HydrogenMoneyV2,\n PageInfo as HydrogenPageInfo,\n Cart as HydrogenStorefrontApiCart,\n Metafield,\n} from '@shopify/hydrogen/storefront-api-types';\nimport type { CartContext, CartItem, ContextParameters, RebuyContextProps } from '~/types/rebuyCustom';\nimport { getEncodedAttributes } from '~/utils/getEncodedAttributes';\n\n/* Helper to create a default MoneyV2 object */\nconst defaultMoney = (currencyCode: CurrencyCode = 'USD' as CurrencyCode): HydrogenMoneyV2 => ({\n __typename: 'MoneyV2',\n amount: '0.0',\n currencyCode,\n});\n\n/* Helper to create default PageInfo */\nconst defaultPageInfo = (): HydrogenPageInfo => ({\n __typename: 'PageInfo',\n endCursor: null,\n hasNextPage: false,\n hasPreviousPage: false,\n startCursor: null,\n});\n\n/* Helper for default BuyerIdentity */\nconst defaultBuyerIdentity = (): HydrogenCartBuyerIdentity => ({\n __typename: 'CartBuyerIdentity',\n countryCode: null,\n customer: null,\n deliveryAddressPreferences: [],\n email: null,\n phone: null,\n // preferences and purchasingCompany are not on the official type\n});\n\nexport const createContextParameters = ({\n cacheKey,\n cartAttributes: legacyCartAttributes,\n cartCost: legacyCartCost,\n cartId: legacyCartId,\n cartLines: legacyCartLines,\n cartLinesLength: legacyCartLinesLength,\n cartNote: legacyCartNote,\n cartSubtotal: legacyCartSubtotal,\n cartTotalQuantity: legacyCartTotalQuantity,\n checkoutUrl: legacyCheckoutUrl,\n discountCodes: legacyDiscountCodes,\n hydrogenReactCartActions,\n hydrogenReactCartError,\n hydrogenReactCartStatus,\n isHydrogenReact,\n /* H-React specific */\n queryObject,\n sourceHydrogenCart,\n windowUrl,\n}: RebuyContextProps): ContextParameters => {\n let solidifiedHydrogenCart: HydrogenStorefrontApiCart | null = null;\n const sourceCartCurrency = (sourceHydrogenCart?.cost?.totalAmount?.currencyCode ?? 'USD') as CurrencyCode;\n\n if (sourceHydrogenCart && sourceHydrogenCart.id) {\n const builtCart: Partial<HydrogenStorefrontApiCart> = {\n __typename: 'Cart',\n appliedGiftCards: sourceHydrogenCart.appliedGiftCards ?? [],\n attributes: sourceHydrogenCart.attributes ?? [],\n buyerIdentity: (sourceHydrogenCart.buyerIdentity as HydrogenCartBuyerIdentity) ?? defaultBuyerIdentity(),\n checkoutUrl: sourceHydrogenCart.checkoutUrl ?? '',\n cost: (sourceHydrogenCart.cost as HydrogenCartCost) ?? {\n __typename: 'CartCost',\n checkoutChargeAmount: defaultMoney(sourceCartCurrency),\n subtotalAmount: defaultMoney(sourceCartCurrency),\n subtotalAmountEstimated: false,\n totalAmount: defaultMoney(sourceCartCurrency),\n totalAmountEstimated: false,\n totalDutyAmount: null,\n totalDutyAmountEstimated: false,\n totalTaxAmount: null,\n totalTaxAmountEstimated: false,\n },\n createdAt: sourceHydrogenCart.createdAt ?? new Date().toISOString(),\n deliveryGroups: (sourceHydrogenCart.deliveryGroups as CartDeliveryGroupConnection) ?? {\n __typename: 'CartDeliveryGroupConnection',\n edges: [],\n nodes: [],\n pageInfo: defaultPageInfo(),\n },\n discountAllocations: (sourceHydrogenCart.discountAllocations ?? []) as (\n | CartAutomaticDiscountAllocation\n | CartCodeDiscountAllocation\n | CartCustomDiscountAllocation\n )[],\n discountCodes: (sourceHydrogenCart.discountCodes as CartDiscountCode[]) ?? [],\n id: sourceHydrogenCart.id,\n lines: (sourceHydrogenCart.lines as BaseCartLineConnection) ?? {\n __typename: 'BaseCartLineConnection',\n edges: [],\n nodes: [],\n pageInfo: defaultPageInfo(),\n },\n metafields: (sourceHydrogenCart.metafields ?? []) as Metafield[],\n note: sourceHydrogenCart.note ?? null,\n totalQuantity: sourceHydrogenCart.totalQuantity ?? 0,\n updatedAt: sourceHydrogenCart.updatedAt ?? new Date().toISOString(),\n };\n solidifiedHydrogenCart = builtCart as HydrogenStorefrontApiCart;\n }\n\n let numericCartToken: string | null = null;\n let cartSubtotalInCents: number = 0;\n let linesForCounts: (CartLine | ComponentizableCartLine)[] = [];\n let totalQuantity: number = 0;\n let lineCount: number = 0;\n let legacyNote: string | null = null;\n let legacyAttributes: Attribute[] = [];\n let legacyCheckoutUrlValue: string | undefined;\n let legacyDiscountCodesValue: CartDiscountCode[] = [];\n let legacyCartCostValue: RebuyContextProps['cartCost'] | undefined;\n let legacyCartIdValue: string | undefined;\n\n if (solidifiedHydrogenCart) {\n numericCartToken = Utilities.getIdFromGraphUrl(solidifiedHydrogenCart.id, 'Cart')?.toString() || null;\n cartSubtotalInCents = solidifiedHydrogenCart.cost?.subtotalAmount?.amount\n ? Utilities.amountToCents(parseFloat(solidifiedHydrogenCart.cost.subtotalAmount.amount))\n : 0;\n\n linesForCounts =\n (solidifiedHydrogenCart.lines.nodes?.length ?? 0) > 0\n ? (solidifiedHydrogenCart.lines.nodes as (CartLine | ComponentizableCartLine)[])\n : ((solidifiedHydrogenCart.lines.edges?.map((e) => e.node) as (CartLine | ComponentizableCartLine)[]) ??\n []);\n\n totalQuantity = solidifiedHydrogenCart.totalQuantity;\n lineCount = linesForCounts.length;\n legacyNote = solidifiedHydrogenCart.note ?? null;\n legacyAttributes = [...solidifiedHydrogenCart.attributes];\n legacyCheckoutUrlValue = solidifiedHydrogenCart.checkoutUrl;\n legacyDiscountCodesValue = [...solidifiedHydrogenCart.discountCodes];\n legacyCartCostValue = solidifiedHydrogenCart.cost;\n legacyCartIdValue = solidifiedHydrogenCart.id;\n } else {\n numericCartToken = legacyCartId ? Utilities.getIdFromGraphUrl(legacyCartId, 'Cart')?.toString() || null : null;\n const subtotalString = legacyCartCost?.subtotalAmount?.amount ?? legacyCartSubtotal;\n cartSubtotalInCents = subtotalString ? Utilities.amountToCents(parseFloat(subtotalString)) : 0;\n linesForCounts = Array.isArray(legacyCartLines)\n ? ([...legacyCartLines] as (CartLine | ComponentizableCartLine)[])\n : [];\n totalQuantity = legacyCartTotalQuantity ?? linesForCounts.reduce((sum, line) => sum + (line?.quantity ?? 0), 0);\n lineCount = legacyCartLinesLength ?? linesForCounts.length;\n legacyNote = legacyCartNote ?? null;\n legacyAttributes = legacyCartAttributes ? [...legacyCartAttributes] : [];\n legacyCheckoutUrlValue = legacyCheckoutUrl;\n legacyDiscountCodesValue = legacyDiscountCodes ? [...legacyDiscountCodes] : [];\n legacyCartCostValue = legacyCartCost;\n legacyCartIdValue = legacyCartId;\n }\n\n const contextParametersOutput: ContextParameters = {\n cache_key: cacheKey,\n cart: undefined,\n cart_count: totalQuantity,\n cart_item_count: totalQuantity,\n cart_line_count: lineCount,\n cart_subtotal: cartSubtotalInCents,\n\n cart_token: numericCartToken || undefined,\n cartAttributes: legacyAttributes,\n cartCost: legacyCartCostValue,\n cartId: legacyCartIdValue,\n cartLines: linesForCounts as CartLine[],\n cartNote: legacyNote,\n checkoutUrl: legacyCheckoutUrlValue,\n\n discountCodes: legacyDiscountCodesValue,\n\n hydrogenCart: solidifiedHydrogenCart,\n hydrogenReactCartActions,\n hydrogenReactCartError,\n\n hydrogenReactCartStatus,\n isHydrogenReact,\n time: queryObject.time ?? '',\n\n url: windowUrl,\n };\n\n const cartContext: CartContext = {\n attributes: '',\n item_count: totalQuantity,\n items: [],\n line_count: lineCount,\n note: legacyNote ?? '',\n subtotal: cartSubtotalInCents,\n token: numericCartToken ?? '',\n };\n\n if (legacyAttributes.length > 0) {\n const validAttributes = legacyAttributes.filter(\n (attr): attr is { key: string; value: string } =>\n typeof attr.key === 'string' && typeof attr.value === 'string'\n );\n cartContext.attributes = getEncodedAttributes(validAttributes);\n }\n\n if (linesForCounts.length > 0) {\n cartContext.items = linesForCounts.map((line): CartItem => {\n const item: CartItem = {\n attributes: line.attributes ? [...line.attributes] : [],\n product_id: line.merchandise?.product?.id\n ? Utilities.getIdFromGraphUrl(line.merchandise.product.id, 'Product')?.toString() || ''\n : '',\n properties: '',\n quantity: line.quantity,\n variant_id: line.merchandise?.id\n ? Utilities.getIdFromGraphUrl(line.merchandise.product.id, 'Product')?.toString() || ''\n : '',\n };\n\n if (line.attributes?.length) {\n const validLineAttributes = line.attributes.filter(\n (attr): attr is { key: string; value: string } =>\n typeof attr.key === 'string' && typeof attr.value === 'string'\n );\n item.properties = getEncodedAttributes(validLineAttributes);\n }\n\n return item;\n });\n }\n\n // Create a new object with all properties from contextParametersOutput\n // but with cart property set to cartContext\n return {\n ...contextParametersOutput,\n cart: cartContext,\n };\n};\n", "import type { Attribute } from '@shopify/hydrogen-react/storefront-api-types';\n\nexport const getEncodedAttributes = (attributes: Attribute[]) =>\n encodeURIComponent(\n JSON.stringify(attributes.reduce((merged, { key, value }) => ({ ...merged, [key]: value }), {}))\n );\n", "/* eslint-disable jsdoc/require-param */\nimport * as Utilities from '@rebuy/rebuy/utilities';\nimport { CartProvider, ShopifyProvider, useCart } from '@shopify/hydrogen-react';\nimport { useEffect, useMemo, useRef } from 'react';\nimport { useLocation } from 'react-router';\nimport { DebugKey } from '~/constants/debug';\nimport { RebuyConfigProvider, useRebuyConfig } from '~/context/RebuyConfigContext';\nimport { RebuyContext, type RebuyContextType } from '~/context/RebuyContext';\nimport { useBFCacheReset } from '~/hooks/useBFCacheReset';\nimport type { RebuyHydrogenReactContextProviderProps, RebuyHydrogenReactProps } from '~/providers/types';\nimport { CART_FRAGMENT } from '~/queries/cart.queries';\nimport { SmartCartProvider as RebuySmartCartProvider } from '~/smart-cart/context/SmartCartContext';\nimport type { SmartCartConfig } from '~/smart-cart/types/smart-cart';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport type { HydrogenReactCartActions, RebuyContextProps } from '~/types/rebuyCustom';\nimport { createContextParameters } from '~/utils/createContextParameters';\n\n/**\n * Internal component handling Rebuy configuration fetching,\n * context setup, and conditional Smart Cart provider rendering\n * for Hydrogen React environments.\n */\nconst RebuyHydrogenReactContext = ({\n children,\n enableSmartCart,\n publicPrimaryDomain,\n publicStorefrontToken,\n}: RebuyHydrogenReactProps) => {\n const resetKey = useBFCacheReset();\n\n const {\n apiKey,\n fetchError: configFetchError,\n loadingStatus: configLoadingStatus,\n rebuyConfig,\n shopDomain: configShopDomain,\n } = useRebuyConfig();\n\n const warningLogged = useRef(false);\n\n const location = useLocation();\n const queryObject = Utilities.queryStringToObject(location.search);\n const windowUrl = publicPrimaryDomain ? `${publicPrimaryDomain}${location.pathname}${location.search}` : '';\n\n // ---- Hydrogen React Cart Integration ----\n const {\n cartAttributesUpdate,\n cartCreate,\n discountCodesUpdate,\n error: hydrogenReactCartError,\n linesAdd,\n linesRemove,\n linesUpdate,\n noteUpdate,\n status: hydrogenReactCartStatus,\n ...hydrogenReactCartData\n } = useCart();\n\n const hydrogenReactCartActions: HydrogenReactCartActions | undefined = useMemo(\n () => ({\n cartAttributesUpdate,\n cartCreate,\n discountCodesUpdate,\n linesAdd,\n linesRemove,\n linesUpdate,\n noteUpdate,\n }),\n [cartAttributesUpdate, cartCreate, discountCodesUpdate, linesAdd, linesRemove, linesUpdate, noteUpdate]\n );\n\n // --- Context Parameters Memoization ---\n const contextParameters = useMemo(() => {\n const propsForParamCreation: RebuyContextProps = {\n cacheKey: rebuyConfig?.shop?.cache_key,\n hydrogenReactCartActions,\n hydrogenReactCartError,\n hydrogenReactCartStatus,\n isHydrogenReact: true,\n queryObject,\n sourceHydrogenCart: hydrogenReactCartData as any, // eslint-disable-line @typescript-eslint/no-explicit-any\n windowUrl,\n };\n\n return createContextParameters(propsForParamCreation);\n }, [\n rebuyConfig?.shop?.cache_key,\n windowUrl,\n queryObject,\n hydrogenReactCartData,\n hydrogenReactCartActions,\n hydrogenReactCartStatus,\n hydrogenReactCartError,\n ]);\n\n const defaultContextValue = useMemo(() => ({ contextParameters: {} }) as RebuyContextType, []);\n const rebuyContextValue = useMemo(\n () => (configLoadingStatus === 'success' && rebuyConfig ? { contextParameters } : defaultContextValue),\n [configLoadingStatus, rebuyConfig, contextParameters, defaultContextValue]\n );\n\n // --- Smart Cart Prerequisites Calculation ---\n const smartCartConfig = enableSmartCart ? (rebuyConfig?.smart_cart as SmartCartConfig | null) : null;\n const cacheKey = rebuyConfig?.shop?.cache_key || '';\n const shopifyDomainForSmartCart = configShopDomain || rebuyConfig?.shop?.domain || '';\n const storefrontAccessToken = publicStorefrontToken || rebuyConfig?.shop?.storefront_access_token || '';\n\n const hasAllSmartCartPrerequisites =\n enableSmartCart &&\n configLoadingStatus === 'success' &&\n !!rebuyConfig &&\n !!(smartCartConfig && apiKey && shopifyDomainForSmartCart && storefrontAccessToken);\n\n // --- State Logging ---\n useEffect(() => {\n if (configLoadingStatus === 'loading') return;\n const smartCartDetails = enableSmartCart\n ? {\n hasAllSmartCartPrerequisites,\n hasApiKey: !!apiKey,\n hasShopifyDomain: !!shopifyDomainForSmartCart,\n hasStorefrontToken: !!storefrontAccessToken,\n smartCartConfigLoaded: !!smartCartConfig,\n }\n : { smartCartEnabled: false };\n\n rebuyDebugLog.log(DebugKey.REBUY_HYDROGEN_REACT_PROVIDER, '[Rebuy React Provider State Update]', {\n apiKeyAvailable: !!apiKey,\n fetchError: configFetchError\n ? configFetchError instanceof Error\n ? configFetchError.message\n : configFetchError\n : null,\n loadingStatus: configLoadingStatus,\n rebuyConfigLoaded: !!rebuyConfig,\n ...smartCartDetails,\n });\n }, [\n configLoadingStatus,\n configFetchError,\n rebuyConfig,\n smartCartConfig,\n apiKey,\n shopifyDomainForSmartCart,\n storefrontAccessToken,\n hasAllSmartCartPrerequisites,\n enableSmartCart,\n ]);\n\n // --- Render Logic: Provide Context and Conditionally Render Smart Cart ---\n return (\n <RebuyContext.Provider value={rebuyContextValue}>\n {configLoadingStatus === 'success' && rebuyConfig ? (\n enableSmartCart && hasAllSmartCartPrerequisites ? (\n <RebuySmartCartProvider\n apiKey={apiKey!}\n cacheKey={cacheKey}\n config={smartCartConfig!}\n hydrogenCart={hydrogenReactCartData as any} // eslint-disable-line @typescript-eslint/no-explicit-any\n key={`smart-cart-react-${resetKey}`}\n shopifyDomain={shopifyDomainForSmartCart}\n storefrontAccessToken={storefrontAccessToken}\n >\n {children}\n </RebuySmartCartProvider>\n ) : (\n <>\n {enableSmartCart &&\n !hasAllSmartCartPrerequisites &&\n !warningLogged.current &&\n (() => {\n console.warn(\n `[Rebuy React Provider] Rebuy config loaded, but Smart Cart prerequisites NOT met for ${shopifyDomainForSmartCart}. Smart Cart UI will not render. Check Rebuy Admin/env vars. Missing:`,\n {\n apiKey: !!apiKey,\n config: !!smartCartConfig,\n domain: !!shopifyDomainForSmartCart,\n token: !!storefrontAccessToken,\n }\n );\n warningLogged.current = true;\n\n return null;\n })()}\n {children}\n </>\n )\n ) : configLoadingStatus === 'error' ? (\n <>{children}</>\n ) : null}\n </RebuyContext.Provider>\n );\n};\n\n/**\n * Outer provider component responsible for setting up ShopifyProvider,\n * CartProvider (from @shopify/hydrogen-react), and wrapping the application\n * with the RebuyHydrogenReactContext.\n */\nexport const RebuyHydrogenReactContextProvider = ({\n cart,\n cartFragment = CART_FRAGMENT,\n\n // --- ShopifyProvider Props ---\n children,\n countryIsoCode = 'US',\n customerAccessToken = '',\n enableSmartCart = true,\n languageIsoCode = 'EN',\n numCartLines,\n onAttributesUpdate,\n\n // --- CartProvider Props ---\n onAttributesUpdateComplete,\n onBuyerIdentityUpdate,\n onBuyerIdentityUpdateComplete,\n onCreate,\n // --- CartProvider Callbacks (adapted) ---\n onCreateComplete,\n onDiscountCodesUpdate,\n onDiscountCodesUpdateComplete,\n onLineAdd,\n onLineAddComplete,\n onLineRemove,\n onLineRemoveComplete,\n onLineUpdate,\n onLineUpdateComplete,\n onNoteUpdate,\n onNoteUpdateComplete,\n overrideApiKey,\n publicPrimaryDomain,\n publicStoreDomain,\n publicStorefrontId,\n publicStorefrontToken,\n storefrontApiVersion = '2025-01',\n}: RebuyHydrogenReactContextProviderProps) => {\n // Adapt callbacks to prevent errors if undefined\n const adaptedCallbacks = useMemo(\n () => ({\n onAttributesUpdate: onAttributesUpdate ? () => onAttributesUpdate() : undefined,\n onAttributesUpdateComplete: onAttributesUpdateComplete ? () => onAttributesUpdateComplete() : undefined,\n onBuyerIdentityUpdate: onBuyerIdentityUpdate ? () => onBuyerIdentityUpdate() : undefined,\n onBuyerIdentityUpdateComplete: onBuyerIdentityUpdateComplete\n ? () => onBuyerIdentityUpdateComplete()\n : undefined,\n onCreate: onCreate ? () => onCreate() : undefined,\n onCreateComplete: onCreateComplete ? () => onCreateComplete() : undefined,\n onDiscountCodesUpdate: onDiscountCodesUpdate ? () => onDiscountCodesUpdate() : undefined,\n onDiscountCodesUpdateComplete: onDiscountCodesUpdateComplete\n ? () => onDiscountCodesUpdateComplete()\n : undefined,\n onLineAdd: onLineAdd ? () => onLineAdd() : undefined,\n onLineAddComplete: onLineAddComplete ? () => onLineAddComplete() : undefined,\n onLineRemove: onLineRemove ? () => onLineRemove() : undefined,\n onLineRemoveComplete: onLineRemoveComplete ? () => onLineRemoveComplete() : undefined,\n onLineUpdate: onLineUpdate ? () => onLineUpdate() : undefined,\n onLineUpdateComplete: onLineUpdateComplete ? () => onLineUpdateComplete() : undefined,\n onNoteUpdate: onNoteUpdate ? () => onNoteUpdate() : undefined,\n onNoteUpdateComplete: onNoteUpdateComplete ? () => onNoteUpdateComplete() : undefined,\n }),\n [\n // List all original callback props as dependencies\n onAttributesUpdate,\n onAttributesUpdateComplete,\n onBuyerIdentityUpdate,\n onBuyerIdentityUpdateComplete,\n onCreate,\n onCreateComplete,\n onDiscountCodesUpdate,\n onDiscountCodesUpdateComplete,\n onLineAdd,\n onLineAddComplete,\n onLineRemove,\n onLineRemoveComplete,\n onLineUpdate,\n onLineUpdateComplete,\n onNoteUpdate,\n onNoteUpdateComplete,\n ]\n );\n\n // --- ShopifyProvider Validation ---\n if (!publicStoreDomain) {\n console.warn(\n '[RebuyHydrogenReactContextProvider] Missing required prop: `publicStoreDomain` (for Rebuy config fetching).'\n );\n\n return <>{children}</>;\n }\n\n if (!publicStorefrontToken) {\n console.warn(\n '[RebuyHydrogenReactContextProvider] Missing `publicStorefrontToken` (Shopify Storefront API Token). This is required for ShopifyProvider and cart operations.'\n );\n }\n\n return (\n <ShopifyProvider\n countryIsoCode={countryIsoCode}\n languageIsoCode={languageIsoCode}\n storeDomain={publicStoreDomain}\n storefrontApiVersion={storefrontApiVersion}\n storefrontId={publicStorefrontId}\n storefrontToken={publicStorefrontToken}\n >\n <CartProvider\n cartFragment={cartFragment}\n countryCode={countryIsoCode}\n customerAccessToken={customerAccessToken}\n data={cart}\n languageCode={languageIsoCode}\n numCartLines={numCartLines}\n {...adaptedCallbacks}\n >\n <RebuyConfigProvider initialShopDomain={publicStoreDomain} overrideApiKey={overrideApiKey}>\n <RebuyHydrogenReactContext\n enableSmartCart={enableSmartCart}\n publicPrimaryDomain={publicPrimaryDomain}\n publicStorefrontToken={publicStorefrontToken}\n >\n {children}\n </RebuyHydrogenReactContext>\n </RebuyConfigProvider>\n </CartProvider>\n </ShopifyProvider>\n );\n};\n", "export const OPTION_FRAGMENT = `#graphql\n fragment OptionFragment on ProductOption {\n __typename\n id\n name\n optionValues {\n __typename\n id\n name\n swatch {\n __typename\n color\n image {\n __typename\n mediaContentType\n previewImage {\n __typename\n height\n id\n url\n width\n altText\n }\n id\n alt\n }\n }\n }\n }\n`;\n/*\n * STOREFRONT API QUERIES -----------------------------------------------------\n */\n\n// Docs: https://shopify.dev/docs/api/storefront/latest/objects/Cart\n\nexport const CART_LINE_FRAGMENT = `#graphql\n fragment CartLineFragment on CartLine {\n __typename\n id\n quantity\n cost {\n __typename\n amountPerQuantity {\n __typename\n amount\n currencyCode\n }\n compareAtAmountPerQuantity {\n __typename\n amount\n currencyCode\n }\n totalAmount {\n __typename\n amount\n currencyCode\n }\n subtotalAmount {\n __typename\n amount\n currencyCode\n }\n }\n attributes {\n __typename\n key\n value\n }\n discountAllocations {\n discountedAmount {\n __typename\n amount\n currencyCode\n }\n ... on CartAutomaticDiscountAllocation {\n __typename\n discountedAmount {\n amount\n currencyCode\n }\n title\n }\n ... on CartCodeDiscountAllocation {\n __typename\n code\n discountedAmount {\n amount\n currencyCode\n }\n }\n ... on CartCustomDiscountAllocation {\n __typename\n discountedAmount {\n amount\n currencyCode\n }\n title\n }\n }\n merchandise {\n ... on ProductVariant {\n __typename\n availableForSale\n id\n sku\n title\n compareAtPrice {\n __typename\n amount\n currencyCode\n }\n image {\n __typename\n altText\n height\n id\n url\n width\n }\n price {\n __typename\n amount\n currencyCode\n }\n product {\n __typename\n handle\n id\n productType\n tags\n title\n vendor\n description\n requiresSellingPlan\n collections(first: 10) {\n __typename\n nodes {\n __typename\n handle\n }\n }\n options {\n ...OptionFragment\n }\n images(first: 20) {\n __typename\n nodes {\n __typename\n altText\n height\n id\n url\n width\n }\n }\n sellingPlanGroups(first: 100) {\n __typename\n edges {\n __typename\n node {\n __typename\n appName\n name\n options { __typename name values }\n sellingPlans(first: 100) {\n __typename\n edges {\n __typename\n node {\n __typename\n id\n name\n options { __typename name value }\n priceAdjustments {\n __typename\n adjustmentValue {\n __typename\n ... on SellingPlanFixedAmountPriceAdjustment {\n adjustmentAmount { __typename amount currencyCode }\n }\n ... on SellingPlanFixedPriceAdjustment {\n price { __typename amount currencyCode }\n }\n ... on SellingPlanPercentagePriceAdjustment {\n adjustmentPercentage\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n selectedOptions {\n __typename\n name\n value\n }\n }\n }\n sellingPlanAllocation {\n __typename\n sellingPlan {\n __typename\n id\n name\n }\n }\n }\n` as const;\n\nexport const CART_LINE_COMPONENT_FRAGMENT = `#graphql\n fragment CartLineComponentFragment on ComponentizableCartLine {\n __typename\n id\n quantity\n cost {\n __typename\n amountPerQuantity { __typename amount currencyCode }\n compareAtAmountPerQuantity { __typename amount currencyCode }\n totalAmount { __typename amount currencyCode }\n subtotalAmount { __typename amount currencyCode }\n }\n attributes { __typename key value }\n discountAllocations {\n discountedAmount { __typename amount currencyCode }\n ... on CartAutomaticDiscountAllocation {\n __typename\n discountedAmount { amount currencyCode }\n title\n }\n ... on CartCodeDiscountAllocation {\n __typename\n code\n discountedAmount { amount currencyCode }\n }\n ... on CartCustomDiscountAllocation {\n __typename\n discountedAmount { amount currencyCode }\n title\n }\n }\n merchandise {\n ... on ProductVariant {\n __typename\n availableForSale\n id\n sku\n title\n compareAtPrice { __typename amount currencyCode }\n image { __typename altText height id url width }\n price { __typename amount currencyCode }\n product {\n __typename\n handle\n id\n productType\n tags\n title\n vendor\n description\n requiresSellingPlan\n collections(first: 10) {\n __typename\n nodes { __typename handle }\n }\n options {\n id\n name\n optionValues {\n __typename\n id\n name\n swatch {\n __typename\n color\n image {\n __typename\n mediaContentType\n previewImage { __typename height id url width altText }\n id\n alt\n }\n }\n }\n }\n images(first: 20) {\n __typename\n nodes { __typename altText height id url width }\n }\n sellingPlanGroups(first: 100) {\n __typename\n edges {\n __typename\n node {\n __typename\n appName\n name\n options { __typename name values }\n sellingPlans(first: 100) {\n __typename\n edges {\n __typename\n node {\n __typename\n id\n name\n options { __typename name value }\n priceAdjustments {\n __typename\n adjustmentValue {\n __typename\n ... on SellingPlanFixedAmountPriceAdjustment { adjustmentAmount { __typename amount currencyCode } }\n ... on SellingPlanFixedPriceAdjustment { price { __typename amount currencyCode } }\n ... on SellingPlanPercentagePriceAdjustment { adjustmentPercentage }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n selectedOptions { __typename name value }\n }\n }\n sellingPlanAllocation {\n __typename\n sellingPlan {\n __typename\n id\n name\n }\n }\n lineComponents {\n __typename\n id\n quantity\n cost {\n __typename\n amountPerQuantity { __typename amount currencyCode }\n compareAtAmountPerQuantity { __typename amount currencyCode }\n totalAmount { __typename amount currencyCode }\n subtotalAmount { __typename amount currencyCode }\n }\n attributes { __typename key value }\n discountAllocations {\n discountedAmount { __typename amount currencyCode }\n ... on CartAutomaticDiscountAllocation {\n __typename\n discountedAmount { amount currencyCode }\n title\n }\n ... on CartCodeDiscountAllocation {\n __typename\n code\n discountedAmount { amount currencyCode }\n }\n ... on CartCustomDiscountAllocation {\n __typename\n discountedAmount { amount currencyCode }\n title\n }\n }\n merchandise {\n ... on ProductVariant {\n __typename\n availableForSale\n id\n sku\n title\n compareAtPrice { __typename amount currencyCode }\n image { __typename altText height id url width }\n price { __typename amount currencyCode }\n product {\n __typename\n handle\n id\n productType\n tags\n title\n vendor\n description\n requiresSellingPlan\n collections(first: 10) {\n __typename\n nodes { __typename handle }\n }\n options {\n ...OptionFragment\n }\n images(first: 20) {\n __typename\n nodes { __typename altText height id url width }\n }\n sellingPlanGroups(first: 100) {\n __typename\n edges {\n __typename\n node {\n __typename\n appName\n name\n options { __typename name values }\n sellingPlans(first: 100) {\n __typename\n edges {\n __typename\n node {\n __typename\n id\n name\n options { __typename name value }\n priceAdjustments {\n __typename\n adjustmentValue {\n __typename\n ... on SellingPlanFixedAmountPriceAdjustment { adjustmentAmount { __typename amount currencyCode } }\n ... on SellingPlanFixedPriceAdjustment { price { __typename amount currencyCode } }\n ... on SellingPlanPercentagePriceAdjustment { adjustmentPercentage }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n selectedOptions { __typename name value }\n }\n }\n sellingPlanAllocation {\n __typename\n sellingPlan {\n __typename\n id\n name\n }\n }\n }\n }\n` as const;\n\nexport const CART_FRAGMENT = `#graphql\n fragment CartFragment on Cart {\n id\n checkoutUrl\n createdAt\n totalQuantity\n note\n updatedAt\n __typename\n buyerIdentity {\n __typename\n countryCode\n customer {\n __typename\n id\n email\n firstName\n lastName\n displayName\n }\n email\n phone\n }\n attributes {\n __typename\n key\n value\n }\n cost {\n __typename\n subtotalAmount {\n __typename\n amount\n currencyCode\n }\n totalAmount {\n __typename\n amount\n currencyCode\n }\n }\n discountAllocations {\n discountedAmount {\n __typename\n amount\n currencyCode\n }\n ... on CartAutomaticDiscountAllocation {\n __typename\n discountedAmount {\n amount\n currencyCode\n }\n title\n }\n ... on CartCodeDiscountAllocation {\n __typename\n code\n discountedAmount {\n amount\n currencyCode\n }\n }\n ... on CartCustomDiscountAllocation {\n __typename\n discountedAmount {\n amount\n currencyCode\n }\n title\n }\n }\n discountCodes {\n __typename\n applicable\n code\n }\n lines(first: $numCartLines) {\n __typename\n edges {\n __typename\n node {\n ...CartLineComponentFragment\n }\n }\n }\n }\n ${CART_LINE_FRAGMENT}\n ${CART_LINE_COMPONENT_FRAGMENT}\n ${OPTION_FRAGMENT}\n` as const;\n", "/* eslint-disable no-restricted-imports */\n// ~/smart-cart/components/SmartCartContainer.tsx\nimport clsx from 'clsx';\nimport React, { useCallback, useEffect, useMemo, useRef } from 'react';\nimport { AnchorSlot } from '~/smart-cart/components/_Layouts/AnchorSlot';\nimport { DoubleColumnLayout } from '~/smart-cart/components/_Layouts/DoubleColumnLayout';\nimport { SingleColumnLayout } from '~/smart-cart/components/_Layouts/SingleColumnLayout';\nimport { ScreenReaderText } from '~/smart-cart/components/ScreenReaderText/ScreenReaderText';\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport type { TitleBarSettings } from '~/smart-cart/types/smart-cart-component';\n\nimport './Global.css';\nimport styles from './SmartCartContainer.module.css';\n\ntype SmartCartContainerProps = { containerId?: string };\n\nexport const SmartCartContainer: React.FC<SmartCartContainerProps> = ({ containerId }) => {\n const { config, getItemCount, hideCart, isVisible } = useSmartCart();\n const containerRef = useRef<HTMLDivElement>(null);\n const previousFocusRef = useRef<HTMLElement | null>(null);\n\n const components = useMemo(() => (config && Array.isArray(config.components) ? config.components : []), [config]);\n\n const handleClose = useCallback(() => {\n hideCart();\n\n // Restore focus when closing\n if (previousFocusRef.current) {\n previousFocusRef.current.focus();\n }\n }, [hideCart]);\n\n // Store the focused element when opening the cart\n useEffect(() => {\n if (isVisible) {\n previousFocusRef.current = document.activeElement as HTMLElement;\n // Focus the close button when opening\n const closeButton = containerRef.current?.querySelector('#rebuy-cart-close');\n\n if (closeButton instanceof HTMLElement) {\n closeButton.focus();\n }\n }\n }, [isVisible]);\n\n // Prevent body scroll when cart is open\n useEffect(() => {\n if (isVisible) {\n document.body.classList.add('rebuy-smart-cart-open');\n } else {\n document.body.classList.remove('rebuy-smart-cart-open');\n }\n\n // Cleanup on unmount\n return () => {\n document.body.classList.remove('rebuy-smart-cart-open');\n };\n }, [isVisible]);\n\n const backgroundClassName = clsx(styles['rebuy-smart-cart__overlay-background'], {\n [styles['rebuy-smart-cart__overlay-background--visible']]: isVisible,\n });\n\n const flyoutContainerClasses = clsx(\n styles['rebuy-smart-cart'], // Base container class\n {\n [styles['rebuy-smart-cart--visible']]: isVisible,\n [styles['rebuy-smart-cart--layout-double']]:\n config?.layout === 'double' || config?.layout === 'double-right',\n }\n );\n\n const renderLayoutContent = () => {\n if (!config) return <div style={{ padding: '20px', textAlign: 'center' }}>Loading configuration...</div>;\n switch (config.layout) {\n case 'double':\n case 'double-right':\n return <DoubleColumnLayout components={components} itemCount={getItemCount()} layout={config.layout} />;\n default:\n return <SingleColumnLayout components={components} itemCount={getItemCount()} />;\n }\n };\n\n const defaultTitleId = 'rebuy-smart-cart-default-title';\n const titleBarComponent = components.find((c) => c.type === 'title_bar');\n const ariaLabelledBy = titleBarComponent ? `rebuy-title-${titleBarComponent.component_id}` : defaultTitleId;\n\n return (\n <React.Fragment>\n <div className={backgroundClassName} onClick={handleClose} />\n <div\n aria-labelledby={ariaLabelledBy}\n aria-modal=\"true\"\n className={flyoutContainerClasses}\n data-rebuy-cart-layout={config?.layout || 'single'}\n id={containerId || 'rebuy-cart-react'}\n ref={containerRef}\n role=\"dialog\"\n tabIndex={-1}\n >\n <header className={styles['rebuy-smart-cart__header']} data-rebuy-cart-anchor=\"header\">\n <div className={styles['rebuy-smart-cart__header-top-bar']} data-rebuy-cart-header-top-bar=\"\">\n <div className={styles['rebuy-smart-cart__header-content']} data-rebuy-cart-header-top-inner=\"\">\n <AnchorSlot anchor=\"header\" components={components} includeTypes={['title_bar', 'login']} />\n {!components.some(\n (c) => c.type === 'title_bar' && !(c.settings as TitleBarSettings)?.screen_reader_only\n ) && (\n <h2 id={defaultTitleId}>\n <ScreenReaderText>Your Cart</ScreenReaderText>\n </h2>\n )}\n </div>\n <button\n aria-label=\"Close Cart\"\n className={styles['rebuy-smart-cart__close-button']}\n id=\"rebuy-cart-close\"\n onClick={handleClose}\n type=\"button\"\n >\n \u2715<ScreenReaderText>Close Cart</ScreenReaderText>\n </button>\n </div>\n <AnchorSlot anchor=\"header\" components={components} excludeTypes={['title_bar', 'login']} />\n </header>\n\n {renderLayoutContent()}\n\n <div aria-live=\"polite\" className=\"rebuy-sr-only\" id=\"rebuy-cart-live-region\"></div>\n </div>\n </React.Fragment>\n );\n};\n", "// ~/smart-cart/components/AnchorSlot.tsx\nimport { useMemo, type FC } from 'react';\nimport { DebugKey } from '~/constants/debug';\n\nimport { componentRegistry } from '~/smart-cart/components/componentRegistry'; // Ensure path is correct\nimport type { ComponentAnchor, SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\n\ntype AnchorSlotProps = {\n anchor: ComponentAnchor;\n components: SmartCartComponentConfig[];\n /** Optional list of component types to *exclude*. If provided, these types are skipped. */\n excludeTypes?: string[];\n /** Optional list of component types to *include*. If provided, only these types are rendered. */\n includeTypes?: string[];\n};\n\nexport const AnchorSlot: FC<AnchorSlotProps> = ({ anchor, components, excludeTypes, includeTypes }) => {\n const componentsForSlot = useMemo(() => {\n return components\n .filter((comp) => {\n // Basic filtering\n const isCorrectAnchor = comp.anchor === anchor;\n const isVisible = comp.visibility_status !== 'hidden';\n const included = !includeTypes || includeTypes.includes(comp.type);\n const excluded = excludeTypes && excludeTypes.includes(comp.type);\n\n return isCorrectAnchor && isVisible && included && !excluded;\n })\n .sort((a, b) => a.anchor_order - b.anchor_order); // Sort by anchor_order\n }, [anchor, components, includeTypes, excludeTypes]);\n\n if (!componentsForSlot.length) {\n rebuyDebugLog.log(DebugKey.SC_ANCHOR_SLOT, `AnchorSlot: No components for anchor \"${anchor}\" with filters`, {\n excludeTypes,\n includeTypes,\n });\n\n return null; // Render nothing if no matching components\n }\n\n // rebuyDebugLog.log(DebugKey.SC_ANCHOR_SLOT, `AnchorSlot: Rendering ${componentsForSlot.length} components for anchor \"${anchor}\"`, componentsForSlot);\n\n return (\n <>\n {componentsForSlot.map((componentConfig) => {\n const Component = componentRegistry[componentConfig.type];\n\n if (!Component) {\n console.warn(`[SmartCartReact] No component registered for type: \"${componentConfig.type}\"`);\n\n return null; // Skip rendering if component type is unknown\n }\n\n // rebuyDebugLog.log(DebugKey.SC_ANCHOR_SLOT, `AnchorSlot: Rendering component ${componentConfig.type} (ID: ${componentConfig.component_id})`);\n return <Component componentConfig={componentConfig} key={componentConfig.component_id} />;\n })}\n </>\n );\n};\n", "import DOMPurify from 'dompurify';\nimport React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\nimport { ScreenReaderText } from '~/smart-cart/components/ScreenReaderText/ScreenReaderText';\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport type { AnnouncementBarSettings, SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\n\nimport styles from './AnnouncementBar.module.css';\n\n/* eslint-disable-next-line no-restricted-imports */\n\nconst AUTOPLAY_INTERVAL = 5_000; // Default interval (milliseconds)\nconst DRAG_THRESHOLD = 50; // Min pixels to drag to trigger slide change\n\n/**\n * Renders a rotating announcement bar based on configuration settings.\n * Uses a simple timer-based carousel.\n */\nexport const AnnouncementBar = React.memo(({ componentConfig }: { componentConfig: SmartCartComponentConfig }) => {\n const { isVisible } = useSmartCart();\n const [currentSlideIndex, setCurrentSlideIndex] = useState(0);\n const [isPaused, setIsPaused] = useState(false);\n const [isFocused, setIsFocused] = useState(false);\n const intervalRef = useRef<NodeJS.Timeout | null>(null);\n const containerRef = useRef<HTMLDivElement>(null);\n\n const [isDragging, setIsDragging] = useState(false);\n const [startX, setStartX] = useState(0);\n const [dragOffset, setDragOffset] = useState(0);\n\n const sanitizedMessages = useMemo(() => {\n const settings = componentConfig?.settings as AnnouncementBarSettings;\n const rawMessages = settings?.messages ?? [];\n\n if (!Array.isArray(rawMessages)) {\n console.warn('AnnouncementBar: messages configuration is not an array.', componentConfig);\n\n return [];\n }\n\n return rawMessages\n .filter((msg): msg is string => typeof msg === 'string' && msg.trim() !== '')\n .map((msg) => DOMPurify.sanitize(msg));\n }, [componentConfig]);\n\n const messageCount = sanitizedMessages.length;\n const isCarousel = messageCount >= 2;\n\n const clearTimer = useCallback(() => {\n if (intervalRef.current) {\n clearInterval(intervalRef.current);\n intervalRef.current = null;\n }\n }, []);\n\n const startTimer = useCallback(() => {\n clearTimer();\n\n // ! Note: This implementation moves the slides right, then resets by going back to the first slide (left).\n // ! In a future implementation, we can implement fade in/out transitions between slides, using something lightweight like react-transition-group.\n // TODO: Implement fade in/out transitions between slides, or looping behavior using clones (so the slides move in one direction).\n\n if (!isPaused && isVisible && isCarousel && !isFocused && !isDragging) {\n intervalRef.current = setInterval(() => {\n setCurrentSlideIndex((prevIndex) => (prevIndex + 1) % messageCount);\n }, AUTOPLAY_INTERVAL);\n }\n }, [clearTimer, isPaused, isVisible, isCarousel, messageCount, isFocused, isDragging]);\n\n const goToSlide = useCallback(\n (index: number) => {\n setCurrentSlideIndex((index + messageCount) % messageCount);\n },\n [messageCount]\n );\n\n useEffect(() => {\n startTimer();\n\n return clearTimer;\n }, [startTimer, isPaused, isVisible, isFocused]);\n\n useEffect(() => {\n if (!isVisible) {\n setCurrentSlideIndex(0);\n setIsPaused(false);\n setIsFocused(false);\n }\n }, [isVisible]);\n\n const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (!isCarousel) return;\n switch (event.key) {\n case 'ArrowLeft':\n event.preventDefault();\n goToSlide(currentSlideIndex - 1);\n setIsPaused(true);\n break;\n case 'ArrowRight':\n event.preventDefault();\n goToSlide(currentSlideIndex + 1);\n setIsPaused(true);\n break;\n case ' ':\n case 'Enter':\n event.preventDefault();\n setIsPaused((prevPaused) => !prevPaused);\n break;\n default:\n break;\n }\n };\n\n const handleFocus = () => setIsFocused(true);\n const handleBlur = () => setIsFocused(false);\n const handleMouseEnter = () => {\n if (isCarousel) setIsFocused(true);\n };\n const handleMouseLeave = () => {\n if (isCarousel) setIsFocused(false);\n };\n\n const handlePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {\n if (!isCarousel || !containerRef.current) return;\n setStartX(e.clientX);\n setIsDragging(true);\n setIsPaused(true);\n containerRef.current.style.cursor = 'grabbing';\n containerRef.current.setPointerCapture(e.pointerId);\n };\n\n const handlePointerMove = (e: React.PointerEvent<HTMLDivElement>) => {\n if (!isDragging || !isCarousel) return;\n e.preventDefault();\n setDragOffset(e.clientX - startX);\n };\n\n const handlePointerUpOrLeave = (e: React.PointerEvent<HTMLDivElement>) => {\n if (!isDragging || !isCarousel || !containerRef.current) return;\n try {\n containerRef.current.releasePointerCapture(e.pointerId);\n } catch (error) {\n /* Ignored */\n }\n setIsDragging(false);\n containerRef.current.style.cursor = 'grab';\n\n if (Math.abs(dragOffset) > DRAG_THRESHOLD) {\n if (dragOffset < 0) goToSlide(currentSlideIndex + 1);\n else goToSlide(currentSlideIndex - 1);\n }\n\n setDragOffset(0);\n };\n\n if (messageCount === 0) return null;\n\n const componentId = componentConfig.component_id;\n\n if (!isCarousel) {\n return (\n <div\n className={styles['rebuy-announcement-bar__static-message']}\n dangerouslySetInnerHTML={{ __html: sanitizedMessages[0] }}\n data-rebuy-component=\"announcement-bar\"\n data-rebuy-component-id={componentId}\n />\n );\n }\n\n return (\n <div\n aria-label={`Announcements (${isPaused ? 'Paused' : 'Playing'}). Use Left/Right arrows or swipe to navigate, Space/Enter to pause/play.`}\n aria-roledescription=\"carousel\"\n className={styles['rebuy-announcement-bar__container']}\n data-rebuy-component=\"announcement-bar\"\n data-rebuy-component-id={componentId}\n onBlur={handleBlur}\n onFocus={handleFocus}\n onKeyDown={handleKeyDown}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n onPointerDown={handlePointerDown}\n onPointerLeave={handlePointerUpOrLeave}\n onPointerMove={handlePointerMove}\n onPointerUp={handlePointerUpOrLeave}\n ref={containerRef}\n role=\"region\"\n style={{ touchAction: 'pan-y' }}\n tabIndex={0}\n >\n <ScreenReaderText aria-atomic=\"true\" aria-live=\"polite\">\n Announcement {currentSlideIndex + 1} of {messageCount}:{' '}\n {sanitizedMessages[currentSlideIndex]?.replace(/<[^>]*>?/gm, '') ?? ''}\n </ScreenReaderText>\n <div\n aria-hidden=\"true\"\n className={styles['rebuy-announcement-bar__message-wrapper']}\n style={{\n cursor: isDragging ? 'grabbing' : 'grab',\n transform: `translateX(calc(-${currentSlideIndex * 100}% + ${dragOffset}px))`,\n transition: isDragging ? 'none' : 'transform 0.5s ease-in-out',\n }}\n >\n {sanitizedMessages.map((message, index) => (\n <div\n className={styles['rebuy-announcement-bar__message-item']}\n dangerouslySetInnerHTML={{ __html: message }}\n key={`${componentId}-msg-${index}`}\n />\n ))}\n </div>\n </div>\n );\n});\nAnnouncementBar.displayName = 'AnnouncementBar';\n", "import type React from 'react';\nimport './ScreenReaderText.css';\n\ntype ScreenReaderTextProps = {\n children: React.ReactNode;\n};\n\nexport const ScreenReaderText = ({ children, ...props }: ScreenReaderTextProps) => (\n <span className=\"rebuy-sr-only\" {...props}>\n {children}\n </span>\n);\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/smart-cart/components/AnnouncementBar/AnnouncementBar.css\";\n const result = {\"rebuy-announcement-bar__container\":\"AnnouncementBar_rebuy-announcement-bar__container\",\"rebuy-announcement-bar__message-wrapper\":\"AnnouncementBar_rebuy-announcement-bar__message-wrapper\",\"rebuy-announcement-bar__message-item\":\"AnnouncementBar_rebuy-announcement-bar__message-item\",\"rebuy-announcement-bar__static-message\":\"AnnouncementBar_rebuy-announcement-bar__static-message\"};\n export default result;\n ", "import clsx from 'clsx';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { useFetcher } from 'react-router';\n\nimport { RebuyLink } from '~/components/RebuyLink';\nimport { ScreenReaderText } from '~/smart-cart/components/ScreenReaderText/ScreenReaderText';\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport { useCartItemFeatures } from '~/smart-cart/hooks/useCartItemFeatures';\nimport type { StorefrontCartLine } from '~/smart-cart/types/rebuy-storefront-cart';\nimport {\n getBundleOptionImage,\n getChildBundleTitle,\n getItemPropertyKeyClass,\n getItemPropertyValueClass,\n} from '~/smart-cart/utils/cartItemUtils';\nimport { sizeImage } from '~/smart-cart/utils/imageUtils';\nimport type { JsonValue } from '~/types/common';\n\n/* eslint-disable-next-line no-restricted-imports */\nimport styles from './CartItem.module.css';\n\nconst Spinner: React.FC<{ className?: string }> = ({ className }) => (\n <span className={clsx(styles['rebuy-cart-item__spinner'], className)}></span>\n);\n\ntype CartItemProps = {\n line: StorefrontCartLine;\n};\n\nexport const CartItem: React.FC<CartItemProps> = ({ line }) => {\n const { config, isCartBusy, isHydrogenReact, removeItem, updateItem } = useSmartCart();\n\n const itemFetcher = useFetcher<{ cart?: StorefrontCartLine; error?: string }>();\n\n // Local intent states for spinners\n const [isIncreasing, setIsIncreasing] = useState(false);\n const [isDecreasing, setIsDecreasing] = useState(false);\n const [isRemoving, setIsRemoving] = useState(false);\n const [isAdjustingBMSM, setIsAdjustingBMSM] = useState(false);\n const [isSwitchingSubscription, setIsSwitchingSubscription] = useState(false);\n const [switchingDirection, setSwitchingDirection] = useState<'upgrading' | 'downgrading' | null>(null);\n const { toggleCart } = useSmartCart();\n\n const {\n actions: itemActionsLogic,\n bmsm,\n bundle,\n isBundleExpanded,\n meta,\n pricing,\n properties,\n shouldHideQuantitySelector,\n sts,\n } = useCartItemFeatures({ config, line });\n\n // TODO: Update Query data in Hydrogen to support Selling Plan allocations\n\n const isLoadingCombined = useMemo(() => {\n // If isCartBusy is true, it's a global lock.\n // This covers H-React general loading AND TPB gift processing.\n if (isCartBusy) {\n return true;\n }\n\n // If not globally busy, consider local states for this specific item:\n // 1. For Remix: if this item's fetcher is active.\n if (!isHydrogenReact && itemFetcher.state !== 'idle') {\n return true;\n }\n\n // 2. For both: if any local intent spinner for *this item* is active.\n // These provide immediate feedback before isCartBusy might reflect the start of an operation.\n if (isIncreasing || isDecreasing || isRemoving || isAdjustingBMSM || isSwitchingSubscription) {\n return true;\n }\n\n return false;\n }, [\n isCartBusy,\n isHydrogenReact,\n itemFetcher.state,\n isIncreasing,\n isDecreasing,\n isRemoving,\n isAdjustingBMSM,\n isSwitchingSubscription,\n ]);\n\n const itemClasses = clsx(\n styles['rebuy-cart-item'],\n meta.baseCssClasses,\n meta.tagCssClasses,\n meta.attributeCssClasses,\n { [styles['rebuy-cart-item--updating']]: isLoadingCombined }\n );\n\n // --- Action Handlers ---\n const handleDecreaseQuantity = useCallback(() => {\n // Removed async\n if (isLoadingCombined) return;\n\n const payload = itemActionsLogic.prepareDecreaseQuantity();\n setIsDecreasing(true); // Set intent immediately\n\n if ('quantity' in payload) {\n // It's an UpdateLinePayload\n if (isHydrogenReact) {\n updateItem(payload.lineId, { attributes: payload.attributes, quantity: payload.quantity });\n } else {\n itemFetcher.submit(\n {\n action: 'cartLinesUpdate',\n data: {\n lines: [{ attributes: payload.attributes, id: payload.lineId, quantity: payload.quantity }],\n },\n } as JsonValue,\n { action: '/cart', encType: 'application/json', method: 'POST' }\n );\n }\n } else {\n // It's a RemoveLinePayload\n setIsRemoving(true); // Also set removing intent if quantity becomes 0\n setIsDecreasing(false); // Clear decreasing intent\n\n if (isHydrogenReact) {\n removeItem(payload.lineId);\n } else {\n itemFetcher.submit(\n {\n action: 'cartLinesRemove',\n data: { lineIds: [payload.lineId] },\n },\n { action: '/cart', encType: 'application/json', method: 'POST' }\n );\n }\n }\n }, [isLoadingCombined, itemActionsLogic, isHydrogenReact, updateItem, removeItem, itemFetcher]);\n\n const handleIncreaseQuantity = useCallback(() => {\n // Removed async\n if (isLoadingCombined) return;\n setIsIncreasing(true);\n\n const payload = itemActionsLogic.prepareIncreaseQuantity();\n\n if (isHydrogenReact) {\n updateItem(payload.lineId, { attributes: payload.attributes, quantity: payload.quantity });\n } else {\n itemFetcher.submit(\n {\n action: 'cartLinesUpdate',\n data: {\n lines: [{ attributes: payload.attributes, id: payload.lineId, quantity: payload.quantity }],\n },\n } as JsonValue,\n { action: '/cart', encType: 'application/json', method: 'POST' }\n );\n }\n }, [isLoadingCombined, itemActionsLogic, isHydrogenReact, updateItem, itemFetcher]);\n\n const handleRemoveItem = useCallback(() => {\n // Removed async\n if (isLoadingCombined) return;\n setIsRemoving(true);\n\n const payload = itemActionsLogic.prepareRemoveItem();\n\n if (isHydrogenReact) {\n removeItem(payload.lineId);\n } else {\n itemFetcher.submit(\n {\n action: 'cartLinesRemove',\n data: { lineIds: [payload.lineId] },\n },\n { action: '/cart', encType: 'application/json', method: 'POST' }\n );\n }\n }, [isLoadingCombined, itemActionsLogic, isHydrogenReact, removeItem, itemFetcher]);\n\n const handleAdjustBMSMQuantity = useCallback(\n (tierQuantity: number) => {\n // Removed async\n if (isLoadingCombined) return;\n\n const payload = itemActionsLogic.prepareAdjustBMSMQuantity(tierQuantity);\n\n if (!payload) return;\n setIsAdjustingBMSM(true);\n\n if (isHydrogenReact) {\n updateItem(payload.lineId, { attributes: payload.attributes, quantity: payload.quantity });\n } else {\n itemFetcher.submit(\n {\n action: 'cartLinesUpdate',\n data: {\n lines: [{ attributes: payload.attributes, id: payload.lineId, quantity: payload.quantity }],\n },\n } as JsonValue,\n { action: '/cart', encType: 'application/json', method: 'POST' }\n );\n }\n },\n [isLoadingCombined, itemActionsLogic, isHydrogenReact, updateItem, itemFetcher]\n );\n\n const handleSwitchSubscriptionChange = useCallback(\n (event: React.ChangeEvent<HTMLSelectElement>) => {\n // Removed async\n if (isLoadingCombined) return;\n\n const targetValue = event.target.value;\n const targetSellingPlanId = targetValue === 'onetime' ? null : targetValue;\n\n setSwitchingDirection(\n targetSellingPlanId === null && sts.isCurrentlySubscription\n ? 'downgrading'\n : targetSellingPlanId !== null && !sts.isCurrentlySubscription\n ? 'upgrading'\n : null\n );\n setIsSwitchingSubscription(true);\n\n const payload = itemActionsLogic.prepareSubscriptionSwitch(targetSellingPlanId);\n\n if (isHydrogenReact) {\n updateItem(payload.lineId, { attributes: payload.attributes, sellingPlanId: payload.sellingPlanId });\n } else {\n itemFetcher.submit(\n {\n action: 'cartLinesUpdate',\n data: {\n lines: [\n {\n attributes: payload.attributes,\n id: payload.lineId,\n sellingPlanId: payload.sellingPlanId,\n },\n ],\n },\n } as JsonValue,\n { action: '/cart', encType: 'application/json', method: 'POST' }\n );\n }\n },\n [isLoadingCombined, itemActionsLogic, isHydrogenReact, updateItem, itemFetcher, sts.isCurrentlySubscription]\n );\n\n const handleUpgradeToSubscriptionClick = useCallback(() => {\n // Renamed and removed async\n if (isLoadingCombined || sts.isCurrentlySubscription || sts.availableFrequencies.length === 0) return;\n\n const defaultFrequencyId = sts.availableFrequencies[0].id;\n\n if (!defaultFrequencyId) return;\n\n setSwitchingDirection('upgrading');\n setIsSwitchingSubscription(true);\n\n const payload = itemActionsLogic.prepareSubscriptionSwitch(defaultFrequencyId);\n\n if (isHydrogenReact) {\n updateItem(payload.lineId, { attributes: payload.attributes, sellingPlanId: payload.sellingPlanId });\n } else {\n itemFetcher.submit(\n {\n action: 'cartLinesUpdate',\n data: {\n lines: [\n {\n attributes: payload.attributes,\n id: payload.lineId,\n sellingPlanId: payload.sellingPlanId,\n },\n ],\n },\n } as JsonValue,\n { action: '/cart', encType: 'application/json', method: 'POST' }\n );\n }\n }, [\n isLoadingCombined,\n itemActionsLogic,\n isHydrogenReact,\n updateItem,\n itemFetcher,\n sts.isCurrentlySubscription,\n sts.availableFrequencies,\n ]);\n\n // Effect to reset local loading states\n useEffect(() => {\n const resetLocalSpinners = () => {\n setIsIncreasing(false);\n setIsDecreasing(false);\n setIsRemoving(false);\n setIsAdjustingBMSM(false);\n setIsSwitchingSubscription(false);\n setSwitchingDirection(null);\n };\n\n if (isHydrogenReact) {\n // isCartBusy includes the H-React global loading state.\n // If isCartBusy is false, it implies H-React global loading is also false.\n if (!isCartBusy) {\n resetLocalSpinners();\n }\n } else {\n if (itemFetcher.state === 'idle') {\n resetLocalSpinners(); // Reset when item's own fetcher is idle\n\n if (itemFetcher.data?.error) {\n console.error('CartItem Action Error (Remix):', itemFetcher.data.error);\n // TODO: Display this error in the UI, perhaps via a local state or a toast\n }\n }\n }\n }, [isHydrogenReact, isCartBusy, itemFetcher.state, itemFetcher.data]);\n\n const selectValue = line.sellingPlanAllocation?.sellingPlan.id ?? 'onetime';\n\n return (\n <li\n aria-label={meta.ariaLabel}\n className={itemClasses}\n data-line-id={line.id}\n data-variant-id={line.merchandise.id}\n >\n {/* Media (Image/Link) */}\n <div className={styles['rebuy-cart-item__media']}>\n <RebuyLink\n ariaLabel={meta.linkLabel}\n handle={meta.itemUrl}\n onClick={() => {\n toggleCart();\n }}\n >\n <img alt={meta.imageAltText} height={120} loading=\"lazy\" src={meta.imageUrl} width={120} />\n </RebuyLink>\n </div>\n {/* Item Info */}\n <div className={styles['rebuy-cart-item__info']}>\n <RebuyLink\n ariaLabel={meta.linkLabel}\n className={styles['rebuy-cart-item__product-title']}\n handle={meta.itemUrl}\n onClick={() => {\n toggleCart();\n }}\n role=\"heading\"\n >\n {meta.productTitle}\n </RebuyLink>\n {meta.variantTitle && (\n <div className={styles['rebuy-cart-item__variant-title']}>{meta.variantTitle}</div>\n )}\n\n {properties.hasVisibleProperties && (\n <div className={styles['rebuy-cart-item__properties-list']}>\n {properties.deliveryFrequency && (\n <div\n className={clsx(\n styles['rebuy-cart-item__property'],\n styles['rebuy-cart-item__property--delivery-frequency']\n )}\n >\n {properties.deliveryFrequency}\n </div>\n )}\n {properties.visibleProperties.map((prop, index) => (\n <div\n className={clsx(\n styles['rebuy-cart-item__property'],\n getItemPropertyKeyClass(prop),\n getItemPropertyValueClass(prop)\n )}\n key={`${line.id}-prop-${index}`}\n >\n {prop.key !== '_Discount' ? (\n <>\n <span className={styles['rebuy-cart-item__property-key']}>{prop.key}</span>\n <span className={styles['rebuy-cart-item__property-separator']}>: </span>\n <span className={styles['rebuy-cart-item__property-value']}>{prop.value}</span>\n </>\n ) : (\n <span className={styles['rebuy-cart-item__property-value']}>{prop.value}</span>\n )}\n </div>\n ))}\n </div>\n )}\n\n <button\n aria-label={`Remove ${meta.productTitle}`}\n className={styles['rebuy-cart-item__remove-button']}\n disabled={isLoadingCombined}\n onClick={handleRemoveItem}\n type=\"button\"\n >\n {isRemoving ? <Spinner /> : '\u2715'}\n </button>\n\n {!shouldHideQuantitySelector && (\n <div className={styles['rebuy-cart-item__quantity-selector-area']}>\n <div className={styles['rebuy-cart-item__quantity-selector']}>\n <button\n aria-label={`Decrease quantity of ${meta.productTitle}`}\n className={styles['rebuy-cart-item__quantity-selector-button']}\n disabled={isLoadingCombined}\n onClick={handleDecreaseQuantity}\n type=\"button\"\n >\n {isDecreasing ? <Spinner /> : '-'}\n </button>\n <span aria-live=\"polite\" className={styles['rebuy-cart-item__quantity-selector-label']}>\n <ScreenReaderText>Quantity of {meta.productTitle}</ScreenReaderText>\n {line.quantity}\n </span>\n <button\n aria-label={`Increase quantity of ${meta.productTitle}`}\n className={styles['rebuy-cart-item__quantity-selector-button']}\n disabled={isLoadingCombined}\n onClick={handleIncreaseQuantity}\n type=\"button\"\n >\n {isIncreasing ? <Spinner /> : '+'}\n </button>\n </div>\n </div>\n )}\n\n <div className={styles['rebuy-cart-item__price-details']}>\n {pricing.hasDiscount && pricing.compareAtDisplayPrice ? (\n <>\n <span\n aria-label=\"Sale price\"\n className={clsx(\n styles['rebuy-cart-item__money'],\n styles['rebuy-cart-item__money--sale']\n )}\n >\n <ScreenReaderText>Sale price</ScreenReaderText>\n {pricing.displayPrice}\n </span>\n <span\n aria-label=\"Original price\"\n className={clsx(\n styles['rebuy-cart-item__money'],\n styles['rebuy-cart-item__money--compare-at']\n )}\n >\n <ScreenReaderText>Original price</ScreenReaderText>\n {pricing.compareAtDisplayPrice}\n </span>\n </>\n ) : (\n <span aria-label=\"Price\" className={styles['rebuy-cart-item__money']}>\n <ScreenReaderText>Price</ScreenReaderText>\n {pricing.displayPrice}\n </span>\n )}\n </div>\n\n {bundle.isBundleParent && bundle.showToggle && (\n <div className={styles['rebuy-cart-item__bundle-section']}>\n {bundle.itemCount > 0 && (\n <button\n aria-controls={`bundle-details-${line.id}`}\n aria-expanded={isBundleExpanded}\n aria-label={`${isBundleExpanded ? 'Collapse' : 'Expand'} bundle details for ${meta.productTitle}`}\n className={styles['rebuy-cart-item__bundle-toggle-button']}\n disabled={isLoadingCombined}\n onClick={itemActionsLogic.toggleBundle}\n type=\"button\"\n >\n {isBundleExpanded ? 'Hide' : 'Show'} {bundle.itemCount} item\n {bundle.itemCount !== 1 ? 's' : ''}\n <span aria-hidden=\"true\" className={styles['rebuy-cart-item__bundle-chev-icon']}>\n {isBundleExpanded ? '\u25B2' : '\u25BC'}\n </span>\n </button>\n )}\n {bundle.itemCount > 0 && isBundleExpanded && (\n <ul\n className={styles['rebuy-cart-item__bundle-children-list']}\n id={`bundle-details-${line.id}`}\n tabIndex={-1}\n >\n {Array.from({ length: bundle.itemCount }).map((_, index) => {\n const optionData = { name: 'Placeholder Option', value: 'Details...' }; // Replace with actual data\n const childTitle = getChildBundleTitle(optionData);\n const childImage = getBundleOptionImage(\n line.merchandise.product,\n optionData,\n index\n ); // Pass product\n\n return (\n <li\n className={styles['rebuy-cart-item__bundle-child-item']}\n key={`${line.id}-bundle-child-${index}`}\n >\n <div className={styles['rebuy-cart-item__bundle-child-media-wrapper']}>\n <div className={styles['rebuy-cart-item__bundle-child-image-wrapper']}>\n <img\n alt={childTitle}\n className={styles['rebuy-cart-item__bundle-child-image']}\n loading=\"lazy\"\n src={sizeImage(childImage, '40x40')}\n />\n </div>\n </div>\n <div className={styles['rebuy-cart-item__bundle-child-details']}>\n <h5 className={styles['rebuy-cart-item__bundle-child-title']}>\n {childTitle}\n </h5>\n </div>\n </li>\n );\n })}\n </ul>\n )}\n </div>\n )}\n </div>{' '}\n {/* End Item Info */}\n {bmsm.isEnabledAndApplicable && (\n <div className={styles['rebuy-cart-item__bmsm-section']}>\n {bmsm.isButtonMode ? (\n <div className={styles['rebuy-cart-item__bmsm-button-wrapper']}>\n {bmsm.nextApplicableTiers.map((tier) => (\n <button\n aria-label={`${bmsm.getButtonText(tier)} for ${meta.productTitle}`}\n className={styles['rebuy-cart-item__bmsm-button']}\n disabled={isLoadingCombined}\n key={`bmsm-${line.id}-${tier.quantity}`}\n onClick={() => handleAdjustBMSMQuantity(tier.quantity ?? 0)}\n >\n <span>{bmsm.getButtonText(tier)}</span>\n </button>\n ))}\n </div>\n ) : (\n <span className={styles['rebuy-cart-item__bmsm-dynamic-message']}>{bmsm.dynamicText}</span>\n )}\n </div>\n )}\n {sts.isEnabledAndApplicable && (\n <div className={styles['rebuy-cart-item__sts-section']}>\n {!sts.isCurrentlySubscription && sts.availableFrequencies.length > 0 ? (\n <button\n aria-label={`Switch ${meta.productTitle} to a Subscription`}\n className={styles['rebuy-cart-item__sts-action-button']}\n disabled={isLoadingCombined}\n onClick={handleUpgradeToSubscriptionClick}\n type=\"button\"\n >\n {isSwitchingSubscription && switchingDirection === 'upgrading' ? (\n <Spinner />\n ) : (\n <span>{sts.getUpgradeButtonLabel()}</span>\n )}\n </button>\n ) : sts.isCurrentlySubscription || sts.canDowngrade ? (\n <>\n {isSwitchingSubscription ? (\n <span className={styles['rebuy-cart-item__sts-loading-replacement']}>\n {sts.getLoadingLabel(switchingDirection)}\n </span>\n ) : (\n <select\n aria-label={`Subscription delivery frequency for ${meta.productTitle}`}\n className={styles['rebuy-cart-item__sts-select']}\n disabled={isLoadingCombined}\n onChange={handleSwitchSubscriptionChange}\n value={selectValue}\n >\n {sts.canDowngrade && (\n <optgroup label={sts.getOneTimeGroupLabel()}>\n <option value=\"onetime\">{sts.getOneTimeLabel()}</option>\n </optgroup>\n )}\n {sts.availableFrequencies.length > 0 && (\n <optgroup label={sts.getGroupLabel()}>\n {sts.availableFrequencies.map((freq) => (\n <option key={freq.id} value={freq.id}>\n {sts.getOptionLabel(freq.id)}\n </option>\n ))}\n </optgroup>\n )}\n </select>\n )}\n </>\n ) : null}\n </div>\n )}\n </li>\n );\n};\n", "import { Link } from 'react-router';\nimport type { RebuyLinkProps } from './types';\n\nexport const RebuyLink = ({ ariaLabel, children, className, handle, onClick, role = 'link' }: RebuyLinkProps) => {\n return (\n <Link aria-label={ariaLabel} className={className} onClick={onClick} rel=\"nofollow\" role={role} to={handle}>\n {children}\n </Link>\n );\n};\n", "/* eslint-disable jsdoc/require-param, jsdoc/require-returns */\n\nimport type { AttributeInput as HRAttributeInput } from '@shopify/hydrogen-react/storefront-api-types';\nimport { useCallback, useMemo, useState } from 'react';\nimport { DebugKey } from '~/constants/debug';\n\nimport { LineItemAttributeKey, RebuyLineItemAttribution } from '~/smart-cart/constants';\nimport type {\n StorefrontAttribute,\n StorefrontCartLine,\n StorefrontProduct,\n} from '~/smart-cart/types/rebuy-storefront-cart';\nimport type {\n BuyMoreSaveMoreTier as BmsmTier,\n SmartCartConfig,\n SwitchToSubscriptionLanguage,\n} from '~/smart-cart/types/smart-cart';\nimport {\n bMSMFinalTierNotReached,\n buyMoreSaveMoreDynamicText,\n calculateDefaultSellingPlanDiscount,\n calculatePricingData,\n getAvailableSellingPlans,\n getBMSMButtonText,\n getBMSMTiers,\n getDiscountProperties,\n getItemAttributeClasses,\n getItemBundleLength,\n getItemDeliveryFrequency,\n getItemImageAlt,\n getItemLinkLabel,\n getItemProductTagsClasses,\n getItemURL,\n getSwitchToSubscriptionLabelWithDiscount,\n getVisibleItemProperties,\n hasBMSMButtons,\n hideBundleOptions,\n isBMSMEnabled,\n isCartItemHiddenByStandardLogic,\n isTieredProgressBarGiftItem,\n itemHasBMSM,\n itemIsBundle,\n mergeAttributes,\n removeAttributes,\n} from '~/smart-cart/utils/cartItemUtils';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport { sizeImage } from '~/smart-cart/utils/imageUtils';\n\n// Helper function to map StorefrontAttribute[] to HRAttributeInput[]\n// Ensures keys/values are strings as required by H-React input type and Storefront API\nexport const mapCartAttributes = (attributes?: StorefrontAttribute[] | null): HRAttributeInput[] => {\n if (!attributes) return [];\n\n return attributes\n .filter((attr): attr is { key: string; value: string } => typeof attr.key === 'string' && attr.value !== null)\n .map((attr) => ({\n key: attr.key,\n value: attr.value,\n }));\n};\n\ntype UseCartItemFeaturesProps = {\n config: SmartCartConfig | null;\n line: StorefrontCartLine;\n};\n\n// Data types returned by \"prepare\" functions\nexport type UpdateLinePayload = {\n attributes?: HRAttributeInput[];\n lineId: string;\n quantity?: number;\n sellingPlanId?: string | null;\n};\nexport type RemoveLinePayload = {\n lineId: string;\n};\n\nexport const useCartItemFeatures = ({ config, line }: UseCartItemFeaturesProps) => {\n const [isBundleExpanded, setIsBundleExpanded] = useState(false);\n\n // --- Memoized Calculations (Derived State) ---\n\n // Meta Info\n const productTitle = useMemo(() => line.merchandise.product.title, [line.merchandise.product.title]);\n const variantTitle = useMemo(\n () => (line.merchandise.title !== 'Default Title' ? line.merchandise.title : null),\n [line.merchandise.title]\n );\n const itemUrl = useMemo(() => getItemURL(line), [line]);\n const imageAltText = useMemo(() => getItemImageAlt(line), [line]);\n const imageUrl = useMemo(() => sizeImage(line.merchandise.image?.url, '120x120'), [line.merchandise.image?.url]);\n const linkLabel = useMemo(() => getItemLinkLabel(line), [line]);\n const tagCssClasses = useMemo(() => getItemProductTagsClasses(line), [line]);\n const attributeCssClasses = useMemo(() => getItemAttributeClasses(line), [line]);\n const baseCssClasses = useMemo(\n () => `product-${line.merchandise.product.handle}`,\n [line.merchandise.product.handle]\n );\n const pricing = useMemo(() => calculatePricingData(line), [line]);\n const deliveryFrequency = useMemo(() => getItemDeliveryFrequency(line), [line]);\n const standardProperties = useMemo(() => getVisibleItemProperties(line), [line]);\n const discountProperties = useMemo(() => getDiscountProperties(line), [line]);\n const allVisibleProperties = useMemo(\n () => [...standardProperties, ...discountProperties],\n [standardProperties, discountProperties]\n );\n const hasVisibleProperties = useMemo(\n () => allVisibleProperties.length > 0 || !!deliveryFrequency,\n [allVisibleProperties, deliveryFrequency]\n );\n const isBundleParent = useMemo(() => itemIsBundle(line), [line]);\n const bundleItemCount = useMemo(() => (isBundleParent ? getItemBundleLength(line) : 0), [isBundleParent, line]);\n const shouldHideBundleOptions = useMemo(() => isBundleParent && hideBundleOptions(line), [isBundleParent, line]);\n const showBundleToggle = useMemo(\n () => isBundleParent && !shouldHideBundleOptions && bundleItemCount > 0,\n [isBundleParent, shouldHideBundleOptions, bundleItemCount]\n );\n const shouldHideQuantitySelector = useMemo((): boolean => {\n if (isTieredProgressBarGiftItem(line)) return true;\n\n if (isCartItemHiddenByStandardLogic(line)) return true;\n\n return false;\n }, [line]);\n\n // BMSM Features\n const isBmsmGloballyEnabled = useMemo(() => isBMSMEnabled(config), [config]);\n const isBmsmEligible = useMemo(\n () => isBmsmGloballyEnabled && itemHasBMSM(line, config),\n [isBmsmGloballyEnabled, line, config]\n );\n const bmsmNotAtFinalTier = useMemo(\n () => isBmsmEligible && bMSMFinalTierNotReached(line, config),\n [isBmsmEligible, line, config]\n );\n const isBmsmEnabledAndApplicable = useMemo(\n () => isBmsmEligible && bmsmNotAtFinalTier,\n [isBmsmEligible, bmsmNotAtFinalTier]\n );\n const isBmsmButtonMode = useMemo(\n () => isBmsmEnabledAndApplicable && hasBMSMButtons(config),\n [isBmsmEnabledAndApplicable, config]\n );\n const bmsmTiers = useMemo(\n () => (isBmsmEnabledAndApplicable ? getBMSMTiers(config) : []),\n [isBmsmEnabledAndApplicable, config]\n );\n const bmsmNextApplicableTiers = useMemo(\n () =>\n isBmsmButtonMode\n ? bmsmTiers\n .filter((tier) => tier.quantity && tier.quantity > line.quantity)\n .sort((a, b) => (a.quantity ?? 0) - (b.quantity ?? 0))\n : [],\n [isBmsmButtonMode, bmsmTiers, line.quantity]\n );\n const bmsmDynamicText = useMemo(\n () => (isBmsmEnabledAndApplicable && !isBmsmButtonMode ? buyMoreSaveMoreDynamicText(line, config) : ''),\n [isBmsmEnabledAndApplicable, isBmsmButtonMode, line, config]\n );\n\n // STS Features\n const isStsGloballyEnabled = useMemo(() => config?.switch_to_subscription_enabled ?? false, [config]);\n const productHasSellingPlans = useMemo(\n () => (line.merchandise.product.sellingPlanGroups?.edges ?? []).length > 0,\n [line.merchandise.product.sellingPlanGroups]\n );\n const isStsEligible = useMemo(\n () => isStsGloballyEnabled && productHasSellingPlans,\n [isStsGloballyEnabled, productHasSellingPlans]\n );\n const isCurrentlySubscription = useMemo(() => !!line.sellingPlanAllocation, [line.sellingPlanAllocation]);\n const productRequiresSellingPlan = useMemo(\n () => (line.merchandise.product as StorefrontProduct).requiresSellingPlan ?? false,\n [line.merchandise.product]\n );\n const downgradeGloballyAllowed = useMemo(\n () => !(config?.switch_to_subscription?.disable_downgrade ?? false),\n [config?.switch_to_subscription?.disable_downgrade]\n );\n const canStsDowngrade = useMemo(\n () => isStsEligible && downgradeGloballyAllowed && !productRequiresSellingPlan,\n [isStsEligible, downgradeGloballyAllowed, productRequiresSellingPlan]\n );\n const stsAvailableFrequencies = useMemo(() => getAvailableSellingPlans(line), [line]);\n const defaultSellingPlanDiscountPercent = useMemo(\n () => calculateDefaultSellingPlanDiscount(stsAvailableFrequencies, line),\n [stsAvailableFrequencies, line]\n );\n const isStsEnabledAndApplicable = useMemo(\n () =>\n isStsEligible &&\n (canStsDowngrade ||\n stsAvailableFrequencies.length > 1 ||\n (!isCurrentlySubscription && stsAvailableFrequencies.length > 0)),\n [isStsEligible, canStsDowngrade, stsAvailableFrequencies.length, isCurrentlySubscription]\n );\n const getStsLabel = useCallback(\n // This remains as it's for UI text\n (key: keyof SwitchToSubscriptionLanguage, fallback?: string): string => {\n const labelTemplate = config?.switch_to_subscription?.language?.[key] ?? fallback ?? key.toString();\n const discount = defaultSellingPlanDiscountPercent;\n\n if (\n (key === 'upgrade_to_subscription_label' || key === 'subscription_option_group_label') &&\n discount > 0\n ) {\n return labelTemplate.replace('{{subscription_discount}}', discount.toString());\n }\n\n return labelTemplate;\n },\n [config?.switch_to_subscription?.language, defaultSellingPlanDiscountPercent]\n );\n\n // --- Payload Preparation \"Actions\" (Callbacks) ---\n\n const prepareDecreaseQuantity = useCallback((): UpdateLinePayload | RemoveLinePayload => {\n const newQuantity = line.quantity - 1;\n\n if (newQuantity <= 0) {\n rebuyDebugLog.log(DebugKey.SC_CART_ITEM_FEATURES, `Preparing remove for ${line.id} (qty became 0).`);\n\n return { lineId: line.id };\n }\n let finalAttributes: StorefrontAttribute[] | undefined = undefined;\n const currentAttributes = line.attributes;\n const currentBmsmAttr = currentAttributes?.find(\n (a) => a.key === LineItemAttributeKey.ATTRIBUTION && a.value === RebuyLineItemAttribution.BUY_MORE_SAVE_MORE\n );\n\n if (currentBmsmAttr) {\n const bmsmTiers = getBMSMTiers(config);\n\n if (bmsmTiers.length > 0) {\n const minBmsmQuantity = Math.min(...bmsmTiers.map((t) => t.quantity ?? Infinity));\n\n if (newQuantity < minBmsmQuantity) {\n finalAttributes = removeAttributes(currentAttributes, [\n LineItemAttributeKey.SOURCE,\n LineItemAttributeKey.ATTRIBUTION,\n ]);\n }\n } else {\n finalAttributes = removeAttributes(currentAttributes, [\n LineItemAttributeKey.SOURCE,\n LineItemAttributeKey.ATTRIBUTION,\n ]);\n }\n }\n const finalAttributesInput = mapCartAttributes(finalAttributes);\n rebuyDebugLog.log(DebugKey.SC_CART_ITEM_FEATURES, `Preparing decrease qty for ${line.id} to ${newQuantity}.`);\n\n return { attributes: finalAttributesInput, lineId: line.id, quantity: newQuantity };\n }, [line, config]);\n\n const prepareIncreaseQuantity = useCallback((): UpdateLinePayload => {\n const newQuantity = line.quantity + 1;\n let finalAttributes: StorefrontAttribute[] | undefined = undefined;\n const currentAttributes = line.attributes;\n const isEligibleForBmsm = itemHasBMSM(line, config);\n const hasBmsmAttr = currentAttributes?.some(\n (a) => a.key === LineItemAttributeKey.ATTRIBUTION && a.value === RebuyLineItemAttribution.BUY_MORE_SAVE_MORE\n );\n\n if (isEligibleForBmsm && !hasBmsmAttr) {\n const bmsmTiers = getBMSMTiers(config);\n\n if (bmsmTiers.length > 0) {\n const minBmsmQuantity = Math.min(...bmsmTiers.map((t) => t.quantity ?? Infinity));\n\n if (newQuantity >= minBmsmQuantity) {\n const bmsmAttributesToAdd: StorefrontAttribute[] = [\n { key: LineItemAttributeKey.SOURCE, value: 'Rebuy' },\n { key: LineItemAttributeKey.ATTRIBUTION, value: RebuyLineItemAttribution.BUY_MORE_SAVE_MORE },\n ];\n finalAttributes = mergeAttributes(currentAttributes, bmsmAttributesToAdd);\n }\n }\n }\n const finalAttributesInput = mapCartAttributes(finalAttributes);\n rebuyDebugLog.log(DebugKey.SC_CART_ITEM_FEATURES, `Preparing increase qty for ${line.id} to ${newQuantity}.`);\n\n return { attributes: finalAttributesInput, lineId: line.id, quantity: newQuantity };\n }, [line, config]);\n\n const prepareRemoveItem = useCallback((): RemoveLinePayload => {\n rebuyDebugLog.log(DebugKey.SC_CART_ITEM_FEATURES, `Preparing remove for ${line.id}.`);\n\n return { lineId: line.id };\n }, [line.id]);\n\n const prepareAdjustBMSMQuantity = useCallback(\n (tierQuantity: number): UpdateLinePayload | null => {\n if (tierQuantity === line.quantity) return null;\n\n const currentAttributes = line.attributes;\n const bmsmAttributes: StorefrontAttribute[] = [\n { key: LineItemAttributeKey.SOURCE, value: 'Rebuy' },\n {\n key: LineItemAttributeKey.ATTRIBUTION,\n value: RebuyLineItemAttribution.BUY_MORE_SAVE_MORE,\n },\n ];\n const finalAttributes = mergeAttributes(currentAttributes, bmsmAttributes);\n const finalAttributesInput = mapCartAttributes(finalAttributes);\n rebuyDebugLog.log(\n DebugKey.SC_CART_ITEM_FEATURES,\n `Preparing BMSM qty adjustment for ${line.id} to ${tierQuantity}.`\n );\n\n return { attributes: finalAttributesInput, lineId: line.id, quantity: tierQuantity };\n },\n [line]\n );\n\n const toggleBundle = useCallback(() => {\n setIsBundleExpanded((prev) => !prev);\n }, []);\n\n const prepareSubscriptionSwitch = useCallback(\n (targetSellingPlanId: string | null): UpdateLinePayload => {\n const currentAttributes = line.attributes;\n let finalAttributesArray: StorefrontAttribute[] | undefined = undefined;\n const hasBmsmAttr = currentAttributes?.some(\n (a) =>\n a.key === LineItemAttributeKey.ATTRIBUTION &&\n a.value === RebuyLineItemAttribution.BUY_MORE_SAVE_MORE\n );\n\n if (!hasBmsmAttr) {\n let newAttributionValue: string | null = null;\n let isSubscriptionStateChange = false;\n\n if (targetSellingPlanId === null && isCurrentlySubscription) {\n newAttributionValue = RebuyLineItemAttribution.SWITCH_TO_ONE_TIME;\n isSubscriptionStateChange = true;\n } else if (targetSellingPlanId !== null && !isCurrentlySubscription) {\n newAttributionValue = RebuyLineItemAttribution.SWITCH_TO_SUBSCRIPTION;\n isSubscriptionStateChange = true;\n }\n let keysToRemove: string[] = [];\n\n if (isSubscriptionStateChange) {\n keysToRemove = [LineItemAttributeKey.ATTRIBUTION, LineItemAttributeKey.SOURCE].filter((key) =>\n currentAttributes?.find(\n (attr) =>\n attr.key === key &&\n (attr.value === RebuyLineItemAttribution.SWITCH_TO_SUBSCRIPTION ||\n attr.value === RebuyLineItemAttribution.SWITCH_TO_ONE_TIME ||\n attr.value === 'Rebuy')\n )\n );\n }\n const cleanedAttributes = removeAttributes(currentAttributes, keysToRemove);\n\n if (newAttributionValue) {\n const stsAttributes: StorefrontAttribute[] = [\n { key: LineItemAttributeKey.SOURCE, value: 'Rebuy' },\n { key: LineItemAttributeKey.ATTRIBUTION, value: newAttributionValue },\n ];\n finalAttributesArray = mergeAttributes(cleanedAttributes, stsAttributes);\n } else {\n finalAttributesArray = cleanedAttributes;\n }\n } else {\n finalAttributesArray = currentAttributes;\n }\n const finalAttributesInput = mapCartAttributes(finalAttributesArray);\n rebuyDebugLog.log(\n DebugKey.SC_CART_ITEM_FEATURES,\n `Preparing subscription switch for ${line.id} to plan ${targetSellingPlanId ?? 'one-time'}.`\n );\n\n return { attributes: finalAttributesInput, lineId: line.id, sellingPlanId: targetSellingPlanId };\n },\n [line, isCurrentlySubscription]\n );\n\n // --- Return the hook's public interface ---\n return useMemo(\n () => ({\n actions: {\n prepareAdjustBMSMQuantity,\n prepareDecreaseQuantity,\n prepareIncreaseQuantity,\n prepareRemoveItem,\n prepareSubscriptionSwitch,\n toggleBundle,\n },\n bmsm: {\n dynamicText: bmsmDynamicText,\n getButtonText: (tier: BmsmTier) => getBMSMButtonText(tier, config),\n isButtonMode: isBmsmButtonMode,\n isEnabledAndApplicable: isBmsmEnabledAndApplicable,\n nextApplicableTiers: bmsmNextApplicableTiers,\n },\n bundle: {\n isBundleParent: isBundleParent,\n itemCount: bundleItemCount,\n showToggle: showBundleToggle,\n },\n isBundleExpanded,\n meta: {\n ariaLabel: productTitle,\n attributeCssClasses,\n baseCssClasses,\n imageAltText,\n imageUrl,\n itemUrl,\n linkLabel,\n productTitle,\n tagCssClasses,\n variantTitle,\n },\n pricing: pricing,\n properties: {\n deliveryFrequency,\n hasVisibleProperties,\n visibleProperties: allVisibleProperties,\n },\n shouldHideQuantitySelector,\n sts: {\n availableFrequencies: stsAvailableFrequencies,\n canDowngrade: canStsDowngrade,\n getDowngradingLabel: () =>\n getSwitchToSubscriptionLabelWithDiscount(\n 'downgrading_label',\n config,\n 0,\n 'Switching to One-Time...'\n ),\n getGroupLabel: () =>\n getSwitchToSubscriptionLabelWithDiscount(\n 'subscription_option_group_label',\n config,\n defaultSellingPlanDiscountPercent,\n 'Subscribe & Save {{subscription_discount}}%'\n ),\n getLoadingLabel: (direction?: 'upgrading' | 'downgrading' | null) => {\n const key =\n direction === 'upgrading'\n ? 'upgrading_label'\n : direction === 'downgrading'\n ? 'downgrading_label'\n : '';\n const fallback =\n direction === 'upgrading'\n ? 'Switching to Subscription...'\n : direction === 'downgrading'\n ? 'Switching to One-Time...'\n : 'Updating...';\n\n return key\n ? getSwitchToSubscriptionLabelWithDiscount(\n key as keyof SwitchToSubscriptionLanguage,\n config,\n 0,\n fallback\n )\n : fallback;\n },\n getOneTimeGroupLabel: () =>\n getSwitchToSubscriptionLabelWithDiscount(\n 'onetime_option_group_label',\n config,\n 0,\n 'Purchase Options'\n ),\n getOneTimeLabel: () =>\n getSwitchToSubscriptionLabelWithDiscount('onetime_option_label', config, 0, 'One-Time Purchase'),\n getOptionLabel: (frequencyId: string) => {\n const plan = stsAvailableFrequencies.find((f) => f.id === frequencyId);\n\n return plan?.name ?? frequencyId;\n },\n getUpgradeButtonLabel: () => {\n const key =\n defaultSellingPlanDiscountPercent > 0\n ? 'upgrade_to_subscription_label'\n : 'upgrade_to_subscription_without_discount_label';\n const fallback =\n defaultSellingPlanDiscountPercent > 0\n ? 'Switch & Save {{subscription_discount}}%'\n : 'Switch to Subscription';\n\n return getSwitchToSubscriptionLabelWithDiscount(\n key,\n config,\n defaultSellingPlanDiscountPercent,\n fallback\n );\n },\n getUpgradingLabel: () =>\n getSwitchToSubscriptionLabelWithDiscount(\n 'upgrading_label',\n config,\n 0,\n 'Switching to Subscription...'\n ),\n isCurrentlySubscription: isCurrentlySubscription,\n isEnabledAndApplicable: isStsEnabledAndApplicable,\n },\n }),\n [\n isBundleExpanded,\n prepareIncreaseQuantity,\n prepareDecreaseQuantity,\n prepareRemoveItem,\n prepareAdjustBMSMQuantity,\n toggleBundle,\n prepareSubscriptionSwitch,\n isBmsmEnabledAndApplicable,\n isBmsmButtonMode,\n bmsmNextApplicableTiers,\n config,\n bmsmDynamicText,\n isStsEnabledAndApplicable,\n isCurrentlySubscription,\n canStsDowngrade,\n stsAvailableFrequencies,\n getStsLabel,\n line,\n isBundleParent,\n showBundleToggle,\n bundleItemCount,\n allVisibleProperties,\n deliveryFrequency,\n hasVisibleProperties,\n pricing,\n productTitle,\n variantTitle,\n imageUrl,\n itemUrl,\n imageAltText,\n linkLabel,\n baseCssClasses,\n tagCssClasses,\n attributeCssClasses,\n defaultSellingPlanDiscountPercent,\n shouldHideQuantitySelector,\n ]\n );\n};\n\nexport type UseCartItemFeaturesReturn = ReturnType<typeof useCartItemFeatures>;\n", "// ~/smart-cart/utils/imageUtils.ts\n\n// TODO: REMOVE THIS AND USE npm-rebuy utils instead\nimport { NO_IMAGE_SHOPIFY_PLACEHOLDER } from '~/smart-cart/constants';\n\nexport const sizeImage = (src: string | undefined | null, size: string): string => {\n const safeSrc = src || NO_IMAGE_SHOPIFY_PLACEHOLDER;\n\n // Handle cases where the src might already have query parameters\n const [baseSrc, queryParams] = safeSrc.split('?');\n const extensionMatch = baseSrc.match(/\\.(jpg|jpeg|gif|png|bmp|webp)(\\?.*)?$/i);\n\n if (!extensionMatch) {\n // Cannot determine extension, return original or placeholder\n return safeSrc;\n }\n\n const extension = extensionMatch[1];\n // Remove existing size modifiers like _small, _large, _100x100, etc.\n const cleanedBase = baseSrc.replace(\n /_(pico|icon|thumb|small|compact|medium|large|grande|original|master|(\\d+)x(\\d)*|x(\\d+)|(\\d+)x)@?\\d?x?\\.(jpg|jpeg|gif|png|bmp|webp)/,\n `.${extension}`\n );\n\n const sizeModifier = size ? `_${size}` : '';\n const finalBase = cleanedBase.replace(`.${extension}`, `${sizeModifier}.${extension}`);\n\n return queryParams ? `${finalBase}?${queryParams}` : finalBase;\n};\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/smart-cart/components/CartItem/CartItem.css\";\n const result = {\"rebuy-cart-item\":\"CartItem_rebuy-cart-item\",\"rebuy-cart-item__media\":\"CartItem_rebuy-cart-item__media\",\"rebuy-cart-item__info\":\"CartItem_rebuy-cart-item__info\",\"rebuy-cart-item__remove-button\":\"CartItem_rebuy-cart-item__remove-button\",\"rebuy-cart-item__product-title\":\"CartItem_rebuy-cart-item__product-title\",\"rebuy-cart-item__variant-title\":\"CartItem_rebuy-cart-item__variant-title\",\"rebuy-cart-item__property--discount-message\":\"CartItem_rebuy-cart-item__property--discount-message\",\"rebuy-cart-item__properties-list\":\"CartItem_rebuy-cart-item__properties-list\",\"rebuy-cart-item__property\":\"CartItem_rebuy-cart-item__property\",\"rebuy-cart-item__property--delivery-frequency\":\"CartItem_rebuy-cart-item__property--delivery-frequency\",\"rebuy-cart-item__property-key\":\"CartItem_rebuy-cart-item__property-key\",\"rebuy-cart-item__property-separator\":\"CartItem_rebuy-cart-item__property-separator\",\"rebuy-cart-item__property-value\":\"CartItem_rebuy-cart-item__property-value\",\"rebuy-cart-item__price-details\":\"CartItem_rebuy-cart-item__price-details\",\"rebuy-cart-item__quantity-selector-area\":\"CartItem_rebuy-cart-item__quantity-selector-area\",\"rebuy-cart-item__quantity-selector\":\"CartItem_rebuy-cart-item__quantity-selector\",\"rebuy-cart-item__quantity-selector-label\":\"CartItem_rebuy-cart-item__quantity-selector-label\",\"rebuy-cart-item__quantity-selector-button\":\"CartItem_rebuy-cart-item__quantity-selector-button\",\"rebuy-cart-item__spinner\":\"CartItem_rebuy-cart-item__spinner\",\"rebuy-cart-item__money\":\"CartItem_rebuy-cart-item__money\",\"rebuy-cart-item__money--sale\":\"CartItem_rebuy-cart-item__money--sale\",\"rebuy-cart-item__money--compare-at\":\"CartItem_rebuy-cart-item__money--compare-at\",\"rebuy-cart-item__bmsm-section\":\"CartItem_rebuy-cart-item__bmsm-section\",\"rebuy-cart-item__sts-section\":\"CartItem_rebuy-cart-item__sts-section\",\"rebuy-cart-item__bundle-section\":\"CartItem_rebuy-cart-item__bundle-section\",\"rebuy-cart-item__bmsm-button-wrapper\":\"CartItem_rebuy-cart-item__bmsm-button-wrapper\",\"rebuy-cart-item__bmsm-button\":\"CartItem_rebuy-cart-item__bmsm-button\",\"rebuy-cart-item__bmsm-dynamic-message\":\"CartItem_rebuy-cart-item__bmsm-dynamic-message\",\"rebuy-cart-item__sts-action-button\":\"CartItem_rebuy-cart-item__sts-action-button\",\"rebuy-cart-item__sts-select\":\"CartItem_rebuy-cart-item__sts-select\",\"rebuy-cart-item__sts-loading-replacement\":\"CartItem_rebuy-cart-item__sts-loading-replacement\",\"rebuy-cart-item__bundle-toggle-button\":\"CartItem_rebuy-cart-item__bundle-toggle-button\",\"rebuy-cart-item__bundle-chev-icon\":\"CartItem_rebuy-cart-item__bundle-chev-icon\",\"rebuy-cart-item__bundle-children-list\":\"CartItem_rebuy-cart-item__bundle-children-list\",\"rebuy-cart-item__bundle-child-item\":\"CartItem_rebuy-cart-item__bundle-child-item\",\"rebuy-cart-item__bundle-child-media-wrapper\":\"CartItem_rebuy-cart-item__bundle-child-media-wrapper\",\"rebuy-cart-item__bundle-child-image-wrapper\":\"CartItem_rebuy-cart-item__bundle-child-image-wrapper\",\"rebuy-cart-item__bundle-child-image\":\"CartItem_rebuy-cart-item__bundle-child-image\",\"rebuy-cart-item__bundle-child-details\":\"CartItem_rebuy-cart-item__bundle-child-details\",\"rebuy-cart-item__bundle-child-title\":\"CartItem_rebuy-cart-item__bundle-child-title\",\"rebuy-cart-item__bundle-child-value\":\"CartItem_rebuy-cart-item__bundle-child-value\",\"rebuy-cart-item--updating\":\"CartItem_rebuy-cart-item--updating\"};\n export default result;\n ", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/smart-cart/components/EmptyCart/EmptyCart.css\";\n const result = {\"rebuy-empty-cart-message\":\"EmptyCart_rebuy-empty-cart-message\"};\n export default result;\n ", "// ~/smart-cart/components/EmptyCart/EmptyCart.tsx\n\nimport type React from 'react';\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\n\n/* eslint-disable-next-line no-restricted-imports */\nimport styles from './EmptyCart.module.css';\n\nexport const EmptyCart: React.FC = () => {\n const { config } = useSmartCart();\n const emptyCartMarkup = config?.empty_cart_markup || '<p>Your cart is empty.</p>';\n\n return <div className={styles['rebuy-empty-cart-message']} dangerouslySetInnerHTML={{ __html: emptyCartMarkup }} />;\n};\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/smart-cart/components/CartItemList/CartItemList.css\";\n const result = {\"rebuy-cart-item-list__container\":\"CartItemList_rebuy-cart-item-list__container\",\"rebuy-cart-item-list\":\"CartItemList_rebuy-cart-item-list\"};\n export default result;\n ", "// ~/smart-cart/components/CartItemList/CartItemList.tsx\n\nimport type { CartLine } from '@shopify/hydrogen/storefront-api-types';\nimport type React from 'react';\nimport { CartItem } from '~/smart-cart/components/CartItem/CartItem';\nimport { EmptyCart } from '~/smart-cart/components/EmptyCart/EmptyCart';\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport type { SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\nimport { isCartItemHiddenByStandardLogic, isTieredProgressBarGiftItem } from '~/smart-cart/utils/cartItemUtils';\n\n/* eslint-disable-next-line no-restricted-imports */\nimport styles from './CartItemList.module.css';\n\ntype CartItemListProps = {\n componentConfig: Extract<SmartCartComponentConfig, { type: 'cart_items' }>;\n};\n\nexport const CartItemList: React.FC<CartItemListProps> = ({ componentConfig }) => {\n const { cartData, isLoading: isCartLoading, isProgressBarLineItemMode } = useSmartCart();\n\n // Access lines directly from cartData.lines.nodes.\n // We assume cartData.lines.nodes, if it exists, is an array of CartLine-compatible objects.\n // The type annotation CartLine[] helps TypeScript, but the actual objects\n // must conform to this shape for runtime correctness.\n const lines = (cartData?.lines?.nodes ?? []) as CartLine[];\n\n const visibleLines = lines.filter((line) => {\n if (!line || !line.id || !line.merchandise) return false;\n\n if (isCartItemHiddenByStandardLogic(line)) return false;\n\n if (!isProgressBarLineItemMode && isTieredProgressBarGiftItem(line)) return false;\n\n return true;\n });\n\n const hasVisibleItems = visibleLines.length > 0;\n\n return (\n <div\n className={styles['rebuy-cart-item-list__container']}\n data-rebuy-component=\"cart-items\"\n data-rebuy-component-id={componentConfig.component_id}\n >\n {hasVisibleItems ? (\n <ul className={styles['rebuy-cart-item-list']} data-smartcart-items=\"\" role=\"group\" tabIndex={0}>\n {/* Now map directly over `line` as it's already the CartLine object */}\n {visibleLines.map((line) => (\n <CartItem key={line.id} line={line} />\n ))}\n </ul>\n ) : (\n !isCartLoading && <EmptyCart />\n )}\n </div>\n );\n};\n", "import clsx from 'clsx';\nimport React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; // Added useMemo\nimport { useFetcher } from 'react-router';\n\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport type { SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\nimport type { JsonValue } from '~/types/common';\n\n/* eslint-disable-next-line no-restricted-imports */\nimport styles from './CartNoteInput.module.css';\n\ntype CartNoteInputProps = {\n componentConfig: Extract<SmartCartComponentConfig, { type: 'notes' }>;\n};\n\ntype SaveMessage = {\n text: string;\n type: 'success' | 'error';\n};\n\nexport const CartNoteInput = React.memo(({ componentConfig }: CartNoteInputProps) => {\n const {\n cartData,\n getItemCount,\n isHydrogenReact,\n isLoading: isGlobalCartLoading,\n updateCartNote: hrUpdateCartNote,\n } = useSmartCart();\n\n const noteFetcher = useFetcher<{ cart?: typeof cartData; error?: string; userErrors?: { message: string }[] }>();\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n const isTextareaFocusedRef = useRef(false); // Ref to track focus state without causing re-renders\n\n const settings = componentConfig.settings || {};\n const label = settings?.language?.notes_label ?? 'Add a note (optional)';\n const placeholder = settings?.language?.notes_placeholder ?? 'Your notes...';\n const limitChars = settings?.limit_characters ?? true;\n const maxLength = settings?.max_length ?? 200;\n\n // Initialize currentNoteValue from cartData.note only ONCE on mount,\n // or when cartData.note changes AND the textarea is NOT focused and not saving.\n const [currentNoteValue, setCurrentNoteValue] = useState(cartData?.note || '');\n const [isTextareaVisible, setIsTextareaVisible] = useState(!!cartData?.note);\n const [isSaving, setIsSaving] = useState(false);\n const [saveMessage, setSaveMessage] = useState<SaveMessage | null>(null);\n const saveMessageTimerRef = useRef<NodeJS.Timeout | null>(null);\n\n const currentCartNoteFromCtx = cartData?.note || '';\n // isNoteChanged should compare the current input value with the last known *saved* value (from context)\n const isNoteChanged = currentNoteValue.trim() !== currentCartNoteFromCtx.trim();\n const hasItems = getItemCount() > 0;\n\n const isLoadingCombined = useMemo(() => {\n if (isHydrogenReact) return isGlobalCartLoading || isSaving;\n\n return noteFetcher.state !== 'idle' || isSaving;\n }, [isHydrogenReact, isGlobalCartLoading, noteFetcher.state, isSaving]);\n\n const canSave = isNoteChanged && !isLoadingCombined;\n\n // Effect to update local state when cartData.note changes externally (e.g. after save or from another source)\n // Only update if the textarea is not focused and we are not in the middle of a save operation.\n useEffect(() => {\n const noteFromCart = cartData?.note || '';\n\n if (!isTextareaFocusedRef.current && !isSaving && noteFromCart !== currentNoteValue) {\n setCurrentNoteValue(noteFromCart);\n }\n\n // Also, if a note appears in the cart and the toggle is off, make it visible\n // (unless the user has explicitly closed it *after* a note was present)\n // This part might need more nuanced UX logic if it causes unwanted opening.\n if (noteFromCart && !isTextareaVisible && !isSaving) {\n // Let's be less aggressive about opening it automatically.\n // User can open it with the toggle.\n // setIsTextareaVisible(true);\n } else if (!noteFromCart && isTextareaVisible && !isSaving && !currentNoteValue.trim()) {\n // If cart note is empty, and local value is also empty, and it's visible,\n // we might consider closing it if that's the desired UX after clearing.\n // For now, let user control visibility via toggle primarily.\n }\n }, [cartData?.note, isSaving, currentNoteValue, isTextareaVisible]); // Removed currentNoteValue from deps to avoid loop on typing\n\n useEffect(() => {\n return () => {\n if (saveMessageTimerRef.current) clearTimeout(saveMessageTimerRef.current);\n };\n }, []);\n\n const displaySaveMessage = (text: string, type: 'success' | 'error') => {\n setSaveMessage({ text, type });\n\n if (saveMessageTimerRef.current) clearTimeout(saveMessageTimerRef.current);\n saveMessageTimerRef.current = setTimeout(() => setSaveMessage(null), 3000);\n };\n\n const handleToggle = useCallback(\n (event: React.ChangeEvent<HTMLInputElement>) => {\n const checked = event.target.checked;\n setIsTextareaVisible(checked);\n setSaveMessage(null);\n\n if (!checked && currentNoteValue.trim()) {\n setIsSaving(true);\n const noteToClear = ''; // Always send empty string to clear\n setCurrentNoteValue(noteToClear); // Update local state immediately for visual feedback\n\n if (isHydrogenReact) {\n hrUpdateCartNote(noteToClear);\n } else {\n noteFetcher.submit({ action: 'noteUpdate', data: { note: noteToClear } } as JsonValue, {\n action: '/cart',\n encType: 'application/json',\n method: 'POST',\n });\n }\n } else if (checked) {\n setTimeout(() => textareaRef.current?.focus(), 50);\n }\n },\n [currentNoteValue, isHydrogenReact, hrUpdateCartNote, noteFetcher] // currentNoteValue IS needed here\n );\n\n const handleInputChange = useCallback(\n (event: React.ChangeEvent<HTMLTextAreaElement>) => {\n let value = event.target.value;\n\n if (limitChars && value.length > maxLength) value = value.substring(0, maxLength);\n setCurrentNoteValue(value);\n setSaveMessage(null);\n },\n [limitChars, maxLength]\n );\n\n const handleTextareaFocus = () => {\n isTextareaFocusedRef.current = true;\n };\n\n const handleTextareaBlur = () => {\n isTextareaFocusedRef.current = false;\n // Optional: If you want to auto-save on blur if changed:\n // if (isNoteChanged && canSave && !isSaving) {\n // handleSave();\n // }\n };\n\n const handleSave = useCallback(() => {\n if (!canSave) return; // canSave already checks isLoadingCombined\n\n setIsSaving(true);\n const noteToSave = currentNoteValue.trim();\n\n if (isHydrogenReact) {\n hrUpdateCartNote(noteToSave);\n } else {\n noteFetcher.submit({ action: 'noteUpdate', data: { note: noteToSave } } as JsonValue, {\n action: '/cart',\n encType: 'application/json',\n method: 'POST',\n });\n }\n }, [canSave, currentNoteValue, isHydrogenReact, hrUpdateCartNote, noteFetcher]);\n\n const handleKeyDown = useCallback(\n (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault();\n handleSave();\n }\n },\n [handleSave]\n );\n\n useEffect(() => {\n if (isHydrogenReact) {\n if (!isGlobalCartLoading && isSaving) {\n setIsSaving(false);\n // For H-React, we assume cartData.note is the source of truth after operation\n const noteSuccessfullySaved = (cartData?.note || '') === currentNoteValue.trim();\n\n if (noteSuccessfullySaved) {\n displaySaveMessage('Saved', 'success');\n } else {\n // This could happen if there was an error not reflected in isGlobalCartLoading\n // or if cartData update is lagging. More robust error handling might be needed.\n displaySaveMessage('Note updated', 'success'); // More generic message\n }\n }\n } else {\n if (noteFetcher.state === 'idle' && isSaving) {\n setIsSaving(false);\n const fetchData = noteFetcher.data;\n\n if (fetchData?.error || fetchData?.userErrors?.length) {\n displaySaveMessage(\n fetchData.error || fetchData.userErrors?.[0]?.message || 'Error saving note',\n 'error'\n );\n } else {\n displaySaveMessage('Saved', 'success');\n // If save was successful (no error), and the fetcher returns the updated cart,\n // currentNoteValue should align with cartData.note due to the other useEffect.\n }\n }\n }\n }, [\n isHydrogenReact,\n isGlobalCartLoading,\n noteFetcher.state,\n noteFetcher.data,\n isSaving,\n cartData?.note,\n currentNoteValue, // currentNoteValue needed for comparison\n ]);\n\n if (!hasItems) return null;\n\n const remainingChars = limitChars ? Math.max(0, maxLength - currentNoteValue.length) : null;\n const buttonClasses = clsx(\n styles['rebuy-cart-note-input__save-button'],\n isNoteChanged && styles['rebuy-cart-note-input__save-button--visible'], // Show if changed\n saveMessage?.type === 'success' && styles['rebuy-cart-note-input__save-button--saved'],\n saveMessage?.type === 'error' && styles['rebuy-cart-note-input__save-button--error'],\n isSaving && styles['rebuy-cart-note-input__save-button--saving']\n );\n const buttonContent = isSaving ? 'Saving...' : saveMessage?.text || 'Save';\n const helpTextId = `rebuy-cart-note-help-${componentConfig.component_id}`;\n const remainingCharsId = `rebuy-cart-note-remaining-${componentConfig.component_id}`;\n const describedByIds = [remainingChars !== null && currentNoteValue ? remainingCharsId : null, helpTextId]\n .filter(Boolean)\n .join(' ');\n\n return (\n <div\n className={styles['rebuy-cart-note-input']}\n data-rebuy-component=\"notes\"\n data-rebuy-component-id={componentConfig.component_id ?? 'notes'}\n >\n <label className={styles['rebuy-cart-note-input__toggle-control']}>\n <input\n checked={isTextareaVisible}\n className={styles['rebuy-cart-note-input__toggle-checkbox']}\n disabled={isLoadingCombined && isSaving}\n onChange={handleToggle}\n type=\"checkbox\"\n />\n <span\n className={styles['rebuy-cart-note-input__toggle-label']}\n dangerouslySetInnerHTML={{ __html: label }}\n />\n </label>\n\n {isTextareaVisible && (\n <div className={styles['rebuy-cart-note-input__content-area']}>\n <div className={styles['rebuy-cart-note-input__textarea-wrapper']}>\n <textarea\n aria-describedby={describedByIds || undefined}\n aria-label={label}\n className={styles['rebuy-cart-note-input__textarea']}\n disabled={isLoadingCombined}\n maxLength={limitChars ? maxLength : undefined}\n onBlur={handleTextareaBlur} // Track blur\n onChange={handleInputChange}\n onFocus={handleTextareaFocus} // Track focus\n onKeyDown={handleKeyDown}\n placeholder={placeholder}\n ref={textareaRef}\n rows={2}\n value={currentNoteValue} // Controlled component\n />\n <button\n aria-label={\n saveMessage?.text || (isNoteChanged ? 'Save note changes' : 'Note is up to date')\n }\n className={buttonClasses} // Make sure this is defined or use your existing logic\n disabled={!canSave || isSaving}\n onClick={handleSave}\n type=\"button\"\n >\n {buttonContent}\n </button>\n </div>\n <div\n className={clsx(\n styles['rebuy-cart-note-input__meta-info'],\n !isNoteChanged && !saveMessage && styles['rebuy-cart-note-input__meta-info--hidden']\n )}\n >\n {limitChars && currentNoteValue.length > 0 && remainingChars !== null && (\n <small\n aria-live=\"polite\"\n className={styles['rebuy-cart-note-input__remaining-chars-indicator']}\n id={remainingCharsId}\n >\n {`You have ${remainingChars} characters remaining.`}\n </small>\n )}\n <small className={styles['rebuy-cart-note-input__help-text']} id={helpTextId}>\n Press Enter to save, Shift+Enter for new line.\n </small>\n </div>\n </div>\n )}\n </div>\n );\n});\nCartNoteInput.displayName = 'CartNoteInput';\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/smart-cart/components/CartNoteInput/CartNoteInput.css\";\n const result = {\"rebuy-cart-note-input\":\"CartNoteInput_rebuy-cart-note-input\",\"rebuy-cart-note-input__toggle-control\":\"CartNoteInput_rebuy-cart-note-input__toggle-control\",\"rebuy-cart-note-input__toggle-checkbox\":\"CartNoteInput_rebuy-cart-note-input__toggle-checkbox\",\"rebuy-cart-note-input__toggle-label\":\"CartNoteInput_rebuy-cart-note-input__toggle-label\",\"rebuy-cart-note-input__textarea-wrapper\":\"CartNoteInput_rebuy-cart-note-input__textarea-wrapper\",\"rebuy-cart-note-input__textarea\":\"CartNoteInput_rebuy-cart-note-input__textarea\",\"rebuy-cart-note-input__save-button\":\"CartNoteInput_rebuy-cart-note-input__save-button\",\"rebuy-cart-note-input__save-button--visible\":\"CartNoteInput_rebuy-cart-note-input__save-button--visible\",\"rebuy-cart-note-input__save-button--saving\":\"CartNoteInput_rebuy-cart-note-input__save-button--saving\",\"rebuy-cart-note-input__save-button--saved\":\"CartNoteInput_rebuy-cart-note-input__save-button--saved\",\"rebuy-cart-note-input__save-button--error\":\"CartNoteInput_rebuy-cart-note-input__save-button--error\",\"rebuy-cart-note-input__meta-info\":\"CartNoteInput_rebuy-cart-note-input__meta-info\",\"rebuy-cart-note-input__meta-info--hidden\":\"CartNoteInput_rebuy-cart-note-input__meta-info--hidden\",\"rebuy-cart-note-input__remaining-chars-indicator\":\"CartNoteInput_rebuy-cart-note-input__remaining-chars-indicator\",\"rebuy-cart-note-input__help-text\":\"CartNoteInput_rebuy-cart-note-input__help-text\",\"rebuy-cart-note-input__content-area\":\"CartNoteInput_rebuy-cart-note-input__content-area\"};\n export default result;\n ", "// ~/smart-cart/components/CartSubtotal/CartSubtotal.tsx\nimport clsx from 'clsx';\nimport React, { useCallback, useMemo, useState } from 'react';\n\nimport { ScreenReaderText } from '~/smart-cart/components/ScreenReaderText/ScreenReaderText';\nimport { CartExclusionProductTag } from '~/smart-cart/constants';\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport type {\n StorefrontAutomaticDiscountAllocation,\n StorefrontCodeDiscountAllocation,\n StorefrontCustomDiscountAllocation,\n StorefrontTypedDiscountAllocation,\n} from '~/smart-cart/types/rebuy-storefront-cart';\nimport type { CartSubtotalSettings, SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\nimport { formatMoney } from '~/smart-cart/utils/moneyUtils';\n\n/* eslint-disable-next-line no-restricted-imports */\nimport styles from './CartSubtotal.module.css';\n\ntype FormattedDiscountItem = { amount: string; title: string };\ntype CartSubtotalProps = {\n componentConfig: Extract<SmartCartComponentConfig, { type: 'cart_subtotal' }>;\n};\n\n/**\n * Gets the display title for a discount allocation\n *\n * @param {StorefrontTypedDiscountAllocation} alloc - The discount allocation\n *\n * @returns {string} The formatted title for display\n */\nconst getDiscountAllocationTitle = (alloc: StorefrontTypedDiscountAllocation): string => {\n switch (alloc.__typename) {\n case 'CartCodeDiscountAllocation':\n return (alloc as StorefrontCodeDiscountAllocation).code.toUpperCase();\n case 'CartAutomaticDiscountAllocation':\n return (alloc as StorefrontAutomaticDiscountAllocation).title;\n case 'CartCustomDiscountAllocation':\n return (alloc as StorefrontCustomDiscountAllocation).title;\n default:\n return 'Discount';\n }\n};\n\nexport const CartSubtotalComponent = ({ componentConfig }: CartSubtotalProps) => {\n const { cartData } = useSmartCart();\n const [isDiscountSummaryExpanded, setIsDiscountSummaryExpanded] = useState(false);\n const settings = useMemo(\n () => (componentConfig?.settings ?? {}) as CartSubtotalSettings,\n [componentConfig?.settings]\n );\n\n // TODO: Extract all of this calculation logic into a hook that can be used by other components\n\n const allLines = useMemo(() => cartData?.lines?.edges ?? [], [cartData?.lines?.edges]);\n const excludedLines = useMemo(\n () =>\n allLines\n .map((edge) => edge.node)\n .filter((line) =>\n line.merchandise.product.tags?.includes(CartExclusionProductTag.EXCLUDE_FROM_CART_SUBTOTAL)\n ),\n [allLines]\n );\n const excludedLinesValue = useMemo(\n () => excludedLines.reduce((sum, line) => sum + parseFloat(line.cost.subtotalAmount?.amount ?? '0'), 0),\n [excludedLines]\n );\n\n const apiSubtotalAmount = useMemo(\n () => parseFloat(cartData?.cost?.subtotalAmount?.amount ?? '0'),\n [cartData?.cost?.subtotalAmount?.amount]\n );\n\n const apiTotalAmount = useMemo(\n () => parseFloat(cartData?.cost?.totalAmount?.amount ?? '0'),\n [cartData?.cost?.totalAmount?.amount]\n );\n\n const adjustedPreDiscountSubtotal = useMemo(\n () => Math.max(0, apiSubtotalAmount - excludedLinesValue),\n [apiSubtotalAmount, excludedLinesValue]\n );\n\n const adjustedFinalTotal = useMemo(\n () => Math.max(0, apiTotalAmount - excludedLinesValue),\n [apiTotalAmount, excludedLinesValue]\n );\n\n const totalItemCount = useMemo(() => cartData?.totalQuantity ?? 0, [cartData?.totalQuantity]);\n\n const subtotalLabel = useMemo(() => {\n const singular = settings.subtotal_singular_text ?? 'Subtotal ({{item_count}} item)';\n const plural = settings.subtotal_plural_text ?? 'Subtotal ({{item_count}} items)';\n\n return (totalItemCount === 1 ? singular : plural).replace('{{item_count}}', String(totalItemCount));\n }, [totalItemCount, settings.subtotal_singular_text, settings.subtotal_plural_text]);\n\n const currencyCode = useMemo(\n () => cartData?.cost?.subtotalAmount?.currencyCode ?? 'USD',\n [cartData?.cost?.subtotalAmount?.currencyCode]\n );\n\n const hasOrderDiscount = useMemo(\n () => adjustedPreDiscountSubtotal > adjustedFinalTotal,\n [adjustedPreDiscountSubtotal, adjustedFinalTotal]\n );\n\n const formattedFinalTotal = useMemo(\n () => formatMoney(adjustedFinalTotal, currencyCode),\n [adjustedFinalTotal, currencyCode]\n );\n\n const formattedPreDiscountSubtotal = useMemo(\n () => formatMoney(adjustedPreDiscountSubtotal, currencyCode),\n [adjustedPreDiscountSubtotal, currencyCode]\n );\n\n const groupedCartLevelDiscounts = useMemo<FormattedDiscountItem[]>(() => {\n if (!cartData?.discountAllocations) return [];\n\n const grouped = cartData.discountAllocations.reduce<Record<string, number>>((acc, alloc) => {\n const amount = parseFloat(alloc.discountedAmount?.amount ?? '0');\n\n if (amount === 0) return acc;\n\n const title = getDiscountAllocationTitle(alloc);\n acc[title] = (acc[title] ?? 0) + amount;\n\n return acc;\n }, {});\n\n return Object.entries(grouped).map(([title, totalAmount]) => ({\n amount: `- ${formatMoney(totalAmount, currencyCode)}`,\n title,\n }));\n }, [cartData?.discountAllocations, currencyCode]);\n\n const shouldShowDiscountSummary = useMemo(\n () => settings.show_discount_summary === true && groupedCartLevelDiscounts.length > 0,\n [settings.show_discount_summary, groupedCartLevelDiscounts.length]\n );\n\n const discountSummaryCountLabel = useMemo(() => {\n if (!shouldShowDiscountSummary) return '';\n\n const count = groupedCartLevelDiscounts.length;\n const singular = settings.discount_summary_count_label ?? '{{discount_count}} order discount applied';\n const plural = settings.discount_summary_count_label_plural ?? '{{discount_count}} order discounts applied';\n\n return (count === 1 ? singular : plural).replace('{{discount_count}}', String(count));\n }, [\n shouldShowDiscountSummary,\n groupedCartLevelDiscounts.length,\n settings.discount_summary_count_label,\n settings.discount_summary_count_label_plural,\n ]);\n\n const toggleDiscountSummary = useCallback(() => setIsDiscountSummaryExpanded((prev) => !prev), []);\n\n if (totalItemCount === 0) return null; // Hide if cart is empty\n\n const rootClasses = clsx(\n styles['rebuy-cart-subtotal'],\n shouldShowDiscountSummary ? styles['rebuy-cart-subtotal--with-summary'] : styles['rebuy-cart-subtotal--simple']\n );\n const primaryPrice = formattedFinalTotal;\n const compareAtPrice = hasOrderDiscount ? formattedPreDiscountSubtotal : null;\n const summaryId = `rebuy-discount-summary-details-${componentConfig.component_id}`;\n\n return (\n <div\n className={rootClasses}\n data-rebuy-component=\"cart-subtotal\"\n data-rebuy-component-id={componentConfig.component_id}\n >\n {/* Common Row structure for subtotal display */}\n <div className={styles['rebuy-cart-subtotal__row']}>\n <div className={styles['rebuy-cart-subtotal__label']}>\n <span>{subtotalLabel}</span>\n </div>\n <div className={styles['rebuy-cart-subtotal__amount-wrapper']}>\n <ScreenReaderText>Cart subtotal</ScreenReaderText>\n {compareAtPrice ? (\n <>\n <span className={styles['rebuy-cart-subtotal__price--final']}>\n <ScreenReaderText>Final price</ScreenReaderText>\n <span>{primaryPrice}</span>\n </span>\n <span className={styles['rebuy-cart-subtotal__price--compare-at']}>\n <ScreenReaderText>Original price</ScreenReaderText>\n <span>{compareAtPrice}</span>\n </span>\n </>\n ) : (\n <span>{primaryPrice}</span>\n )}\n </div>\n </div>\n\n {shouldShowDiscountSummary && (\n <div\n className={clsx(styles['rebuy-cart-subtotal__discount-summary'], {\n [styles['rebuy-cart-subtotal__discount-summary--expanded']]: isDiscountSummaryExpanded,\n })}\n >\n <button\n aria-controls={summaryId}\n aria-expanded={isDiscountSummaryExpanded}\n className={styles['rebuy-cart-subtotal__discount-summary-header']}\n onClick={toggleDiscountSummary}\n >\n <span>{discountSummaryCountLabel}</span>\n <span aria-hidden=\"true\" className={styles['rebuy-cart-subtotal__discount-summary-icon']}>\n <i>&#9660;</i> {/* Simple arrow. // TODO: replace with SVG icon */}\n </span>\n </button>\n <div\n aria-hidden={!isDiscountSummaryExpanded}\n className={styles['rebuy-cart-subtotal__discount-summary-details']}\n id={summaryId}\n role=\"region\"\n >\n {groupedCartLevelDiscounts.map((discount, index) => (\n <div className={styles['rebuy-cart-subtotal__discount-summary-item']} key={index}>\n <span>{discount.title}</span>\n <span>{discount.amount}</span>\n </div>\n ))}\n </div>\n </div>\n )}\n </div>\n );\n};\n\nexport const CartSubtotal = React.memo(CartSubtotalComponent);\n\nCartSubtotal.displayName = 'CartSubtotal';\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/smart-cart/components/CartSubtotal/CartSubtotal.css\";\n const result = {\"rebuy-cart-subtotal\":\"CartSubtotal_rebuy-cart-subtotal\",\"rebuy-cart-subtotal--simple\":\"CartSubtotal_rebuy-cart-subtotal--simple\",\"rebuy-cart-subtotal__label\":\"CartSubtotal_rebuy-cart-subtotal__label\",\"rebuy-cart-subtotal__amount-wrapper\":\"CartSubtotal_rebuy-cart-subtotal__amount-wrapper\",\"rebuy-cart-subtotal__price--compare-at\":\"CartSubtotal_rebuy-cart-subtotal__price--compare-at\",\"rebuy-cart-subtotal__price--final\":\"CartSubtotal_rebuy-cart-subtotal__price--final\",\"rebuy-cart-subtotal--with-summary\":\"CartSubtotal_rebuy-cart-subtotal--with-summary\",\"rebuy-cart-subtotal__row\":\"CartSubtotal_rebuy-cart-subtotal__row\",\"rebuy-cart-subtotal__discount-summary\":\"CartSubtotal_rebuy-cart-subtotal__discount-summary\",\"rebuy-cart-subtotal__discount-summary-header\":\"CartSubtotal_rebuy-cart-subtotal__discount-summary-header\",\"rebuy-cart-subtotal__discount-summary-icon\":\"CartSubtotal_rebuy-cart-subtotal__discount-summary-icon\",\"rebuy-cart-subtotal__discount-summary--expanded\":\"CartSubtotal_rebuy-cart-subtotal__discount-summary--expanded\",\"rebuy-cart-subtotal__discount-summary-details\":\"CartSubtotal_rebuy-cart-subtotal__discount-summary-details\",\"rebuy-cart-subtotal__discount-summary-item\":\"CartSubtotal_rebuy-cart-subtotal__discount-summary-item\"};\n export default result;\n ", "// ~/smart-cart/components/CartTitleBar/CartTitleBar.tsx\nimport DOMPurify from 'dompurify';\nimport React, { useMemo } from 'react';\n\nimport { ScreenReaderText } from '~/smart-cart/components/ScreenReaderText/ScreenReaderText';\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\n\n/* eslint-disable-next-line no-restricted-imports */\nimport styles from './CartTitleBar.module.css';\n\n/**\n * Renders the Smart Cart Title Bar based on configuration.\n * Fetches settings from the SmartCartContext.\n */\nexport const CartTitleBar = React.memo(() => {\n const { getComponentConfigByType } = useSmartCart();\n const componentConfig = getComponentConfigByType('title_bar');\n\n const title = componentConfig?.settings?.title ?? 'Your Cart';\n const headingTag = componentConfig?.settings?.heading_tag ?? 'h2';\n const screenReaderOnly = componentConfig?.settings?.screen_reader_only ?? false;\n\n const sanitizedTitle = useMemo(() => {\n if (typeof window !== 'undefined') return DOMPurify.sanitize(title);\n\n return title;\n }, [title]);\n\n const DynamicHeadingTag = headingTag as React.ElementType;\n\n if (title === '' && !screenReaderOnly) return null;\n\n if (screenReaderOnly) {\n return (\n <DynamicHeadingTag\n data-rebuy-component-id={componentConfig?.component_id ?? 'title_bar'}\n id=\"rebuy-cart-title\"\n >\n <ScreenReaderText>{sanitizedTitle}</ScreenReaderText>\n </DynamicHeadingTag>\n );\n }\n\n return (\n <DynamicHeadingTag\n className={styles['rebuy-cart-title-bar']}\n dangerouslySetInnerHTML={{ __html: sanitizedTitle }}\n data-rebuy-component=\"title-bar\"\n data-rebuy-component-id={componentConfig?.component_id ?? 'title_bar'}\n id=\"rebuy-cart-title\"\n />\n );\n});\nCartTitleBar.displayName = 'CartTitleBar';\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/smart-cart/components/CartTitleBar/CartTitleBar.css\";\n const result = {\"rebuy-cart-title-bar\":\"CartTitleBar_rebuy-cart-title-bar\"};\n export default result;\n ", "// ~/smart-cart/components/CheckoutArea/CheckoutArea.tsx\nimport React, { useCallback, useEffect, useMemo, useState } from 'react';\nimport { useFetcher } from 'react-router';\n\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport type { StorefrontAttribute } from '~/smart-cart/types/rebuy-storefront-cart';\nimport type { CheckoutSettings, SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\nimport { formatMoney } from '~/smart-cart/utils/moneyUtils';\nimport type { JsonValue } from '~/types/common';\n\n/* eslint-disable-next-line no-restricted-imports */\nimport styles from './CheckoutArea.module.css';\n\ntype CheckoutAreaProps = {\n componentConfig: Extract<SmartCartComponentConfig, { type: 'checkout' }>;\n};\ntype ProcessingSource = 'checkout' | 'view_cart' | 'shop_pay' | 'terms';\n\nexport const CheckoutArea = React.memo(({ componentConfig }: CheckoutAreaProps) => {\n const {\n cartData,\n checkout,\n getItemCount,\n hideCart,\n isHydrogenReact,\n isLoading: isGlobalCartLoading,\n updateCartAttributes: hrUpdateCartAttributes,\n } = useSmartCart();\n\n const termsFetcher = useFetcher<{ cart?: typeof cartData; error?: string; userErrors?: { message: string }[] }>();\n const settings = componentConfig.settings as CheckoutSettings;\n\n const [termsAccepted, setTermsAccepted] = useState(false);\n const [processingSource, setProcessingSource] = useState<ProcessingSource | null>(null);\n\n // Sync termsAccepted with cartData attribute\n useEffect(() => {\n const termsAttr = cartData?.attributes?.find((attr) => attr.key === 'Terms and Conditions');\n const acceptedInCart = termsAttr?.value === 'Accepted';\n\n // Only update if not currently processing a terms change, to avoid race conditions\n if (processingSource !== 'terms' && termsAccepted !== acceptedInCart) {\n setTermsAccepted(acceptedInCart);\n }\n }, [cartData?.attributes, termsAccepted, processingSource]);\n\n const hasItems = getItemCount() > 0;\n const hasTermsEnabled = useMemo(() => !!settings?.terms?.enabled, [settings?.terms?.enabled]);\n\n const isLoadingCombined = useMemo(() => {\n if (isHydrogenReact) return isGlobalCartLoading || processingSource === 'terms';\n\n return termsFetcher.state !== 'idle' || processingSource === 'terms';\n }, [isHydrogenReact, isGlobalCartLoading, termsFetcher.state, processingSource]);\n\n const isAnyCriticalActionProcessing = useMemo(() => {\n if (isHydrogenReact) return isGlobalCartLoading; // H-React has one global loading indicator for cart ops\n\n // For Remix, if we had multiple fetchers for different actions in this component, we'd check all.\n // Here, we only have termsFetcher. Other actions are page navigations.\n return (\n termsFetcher.state !== 'idle' ||\n processingSource === 'checkout' ||\n processingSource === 'shop_pay' ||\n processingSource === 'view_cart'\n );\n }, [isHydrogenReact, isGlobalCartLoading, termsFetcher.state, processingSource]);\n\n const isCheckoutDisabled = useMemo(\n () => !hasItems || isAnyCriticalActionProcessing || (hasTermsEnabled && !termsAccepted),\n [hasItems, isAnyCriticalActionProcessing, hasTermsEnabled, termsAccepted]\n );\n\n const isTermsCheckboxDisabled = useMemo(() => {\n if (isHydrogenReact) return isGlobalCartLoading || processingSource === 'terms';\n\n return termsFetcher.state !== 'idle' || processingSource === 'terms';\n }, [isHydrogenReact, isGlobalCartLoading, termsFetcher.state, processingSource]);\n\n const hasCheckoutButton = useMemo(() => !!settings?.checkout_button?.enabled, [settings?.checkout_button?.enabled]);\n const hasViewCartButton = useMemo(\n () => !!settings?.view_cart_button?.enabled,\n [settings?.view_cart_button?.enabled]\n );\n const hasContinueShoppingButton = useMemo(\n () => !!settings?.continue_shopping_button?.enabled,\n [settings?.continue_shopping_button?.enabled]\n );\n const hasShopPayButton = useMemo(() => !!settings?.shop_pay?.enabled, [settings?.shop_pay?.enabled]);\n const hasInstallments = useMemo(\n () => settings?.installments?.enabled && settings?.installments?.provider,\n [settings?.installments?.enabled, settings?.installments?.provider]\n );\n const hasPrePurchase = useMemo(\n () => settings?.pre_purchase?.enabled && settings?.pre_purchase?.widget_id,\n [settings?.pre_purchase?.enabled, settings?.pre_purchase?.widget_id]\n );\n const checkoutLabel = useMemo(\n () =>\n processingSource === 'checkout'\n ? (settings?.language?.checking_out_label ?? 'Checking Out...')\n : (settings?.language?.checkout_label ?? 'Checkout \u2192'),\n [processingSource, settings?.language]\n );\n const viewCartLabel = useMemo(\n () =>\n processingSource === 'view_cart'\n ? (settings?.language?.view_cart_working_label ?? 'Redirecting...')\n : (settings?.language?.view_cart_label ?? 'View Cart'),\n [processingSource, settings?.language]\n );\n const continueShoppingLabel = useMemo(\n () => settings?.language?.continue_shopping_label ?? 'Continue Shopping',\n [settings?.language?.continue_shopping_label]\n );\n const termsLabel = useMemo(\n () => settings?.language?.terms_and_conditions_label ?? 'I agree to the terms and conditions',\n [settings?.language?.terms_and_conditions_label]\n );\n const installmentsMessage = useMemo(() => {\n const totalAmountData = cartData?.cost?.totalAmount;\n\n if (!hasInstallments || !totalAmountData?.amount || !totalAmountData?.currencyCode) return '';\n const paymentCount = parseInt(settings?.installments?.payment_count ?? '4', 10);\n\n if (isNaN(paymentCount) || paymentCount <= 0) return '';\n const totalAmount = parseFloat(totalAmountData.amount);\n\n if (isNaN(totalAmount)) return '';\n const paymentAmount = totalAmount / paymentCount;\n const formattedPayment = formatMoney(paymentAmount, totalAmountData.currencyCode);\n const provider = settings?.installments?.provider ?? 'Installments Provider';\n const termsUrl = settings?.installments?.terms_url ?? '#';\n\n return `or ${paymentCount} interest-free installments of ${formattedPayment} by <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"${termsUrl}\">${provider}</a>`;\n }, [hasInstallments, cartData?.cost?.totalAmount, settings?.installments]);\n\n const handleTermsChange = useCallback(async () => {\n if (!hasTermsEnabled || isTermsCheckboxDisabled || !hasItems) return;\n\n setProcessingSource('terms');\n const newAcceptedState = !termsAccepted;\n setTermsAccepted(newAcceptedState);\n\n const attribute: StorefrontAttribute = {\n key: 'Terms and Conditions',\n value: newAcceptedState ? 'Accepted' : '',\n };\n\n const otherAttributes = cartData?.attributes?.filter((attr) => attr.key !== 'Terms and Conditions') || [];\n const attributesToUpdate = [...otherAttributes, attribute];\n\n if (isHydrogenReact) {\n try {\n await hrUpdateCartAttributes(attributesToUpdate);\n } catch (error) {\n console.error('[CheckoutArea H-React] Error updating terms:', error);\n setTermsAccepted(!newAcceptedState);\n }\n } else {\n termsFetcher.submit(\n { action: 'cartAttributesUpdate', data: { attributes: attributesToUpdate } } as JsonValue,\n { action: '/cart', encType: 'application/json', method: 'POST' }\n );\n }\n }, [\n hasTermsEnabled,\n isTermsCheckboxDisabled,\n hasItems,\n termsAccepted,\n isHydrogenReact,\n hrUpdateCartAttributes,\n termsFetcher,\n cartData?.attributes,\n ]);\n\n // Effect to reset processingSource for terms when operation completes\n useEffect(() => {\n if (processingSource === 'terms') {\n if (isHydrogenReact && !isGlobalCartLoading) {\n setProcessingSource(null);\n // Verify if the change persisted from cartData\n const termsAttr = cartData?.attributes?.find((attr) => attr.key === 'Terms and Conditions');\n const acceptedInCart = termsAttr?.value === 'Accepted';\n\n if (termsAccepted !== acceptedInCart) {\n console.warn('[CheckoutArea H-React] Terms state discrepancy after update.');\n setTermsAccepted(acceptedInCart); // Force sync\n }\n } else if (!isHydrogenReact && termsFetcher.state === 'idle') {\n setProcessingSource(null);\n\n if (termsFetcher.data?.error || termsFetcher.data?.userErrors?.length) {\n console.error(\n '[CheckoutArea Remix] Error updating terms:',\n termsFetcher.data.error || termsFetcher.data.userErrors\n );\n // Revert optimistic update if there was an error\n setTermsAccepted((prev) => !prev);\n } else {\n // Verify from returned cart data if possible\n const termsAttr = termsFetcher.data?.cart?.attributes?.find(\n (attr: StorefrontAttribute) => attr.key === 'Terms and Conditions'\n );\n const acceptedInFetcherCart = termsAttr?.value === 'Accepted';\n\n if (termsAccepted !== acceptedInFetcherCart && termsFetcher.data?.cart) {\n console.warn('[CheckoutArea Remix] Terms state discrepancy after fetcher update.');\n setTermsAccepted(acceptedInFetcherCart); // Force sync\n }\n }\n }\n }\n }, [\n isHydrogenReact,\n isGlobalCartLoading,\n termsFetcher.state,\n termsFetcher.data,\n processingSource,\n termsAccepted,\n cartData?.attributes,\n ]);\n\n const handleCheckoutClick = useCallback(() => {\n if (isCheckoutDisabled) return;\n setProcessingSource('checkout');\n const routing = settings?.checkout_button?.routing ?? 'automatic';\n const routingLink = settings?.checkout_button?.routing_link ?? '';\n try {\n if (routing === 'custom' && routingLink) window.location.href = routingLink;\n else if (routing === 'shopify') window.location.href = '/checkout';\n else if (routing === 'recharge') checkout();\n else checkout();\n } catch (error) {\n console.error('Checkout Error:', error);\n setProcessingSource(null); // Reset on error\n }\n }, [isCheckoutDisabled, settings?.checkout_button, checkout]);\n\n const handleViewCartClick = useCallback(() => {\n if (isAnyCriticalActionProcessing && processingSource !== 'terms') return;\n setProcessingSource('view_cart');\n window.location.href = '/cart';\n }, [isAnyCriticalActionProcessing, processingSource]);\n\n const handleContinueShoppingClick = useCallback(() => {\n if (isAnyCriticalActionProcessing && processingSource !== 'terms') return;\n hideCart();\n }, [isAnyCriticalActionProcessing, processingSource, hideCart]);\n\n const handleShopPayClick = useCallback(() => {\n if (isLoadingCombined || (!!processingSource && processingSource !== 'terms') || !hasItems) return;\n setProcessingSource('shop_pay');\n try {\n const checkoutUrl = cartData?.checkoutUrl;\n\n if (checkoutUrl) {\n const shopPayUrl = new URL(checkoutUrl);\n shopPayUrl.searchParams.set('payment', 'shop_pay');\n window.location.href = shopPayUrl.toString();\n } else {\n setProcessingSource(null); // Reset if no URL\n }\n } catch (error) {\n console.error('Shop Pay Error:', error);\n setProcessingSource(null); // Reset on error\n }\n }, [isLoadingCombined, processingSource, hasItems, cartData?.checkoutUrl]);\n\n const shopPaySvg = useMemo(\n () => ({\n __html: `<?xml version=\"1.0\" encoding=\"UTF-8\"?><svg width=\"80\" height=\"30\" fill=\"none\" viewBox=\"0 0 4317 1037\" xmlns=\"http://www.w3.org/2000/svg\"><g clip-path=\"url(#a)\" fill=\"#fff\"><path d=\"m1106 326.19c-34.62-72.633-100.26-119.55-199.17-119.55-30.36 0.529-60.193 8.026-87.198 21.908-27.003 13.884-50.46 33.785-68.555 58.168l-3.61 4.398v-284.67c0-1.6452-0.653-3.2229-1.817-4.3862-1.163-1.1633-2.742-1.817-4.387-1.817h-139.85c-1.625 0.029561-3.173 0.69609-4.312 1.8562-1.14 1.1601-1.778 2.7211-1.778 4.3469v816.56c0 1.615 0.643 3.163 1.785 4.305 1.142 1.143 2.69 1.785 4.305 1.785h149.78c1.626 0 3.187-0.637 4.347-1.778 1.16-1.139 1.826-2.687 1.856-4.312v-348.16c0-67.67 45.113-115.6 117.3-115.6 78.949 0 98.912 64.964 98.912 131.17v332.6c0 1.615 0.641 3.163 1.783 4.305 1.142 1.143 2.692 1.785 4.307 1.785h149.44c1.63 0 3.19-0.637 4.35-1.778 1.16-1.139 1.83-2.687 1.86-4.312v-352.45c0-12.068 0-23.911-1.58-35.414-2.57-37.698-11.97-74.616-27.75-108.95z\"/><path d=\"m358.09 447.21s-76.242-17.933-104.32-25.151c-28.084-7.218-77.145-22.557-77.145-59.663s39.587-48.949 79.739-48.949c40.151 0 84.814 9.7 88.31 54.25 0.141 1.606 0.88 3.098 2.07 4.186 1.191 1.086 2.746 1.684 4.358 1.679l147.63-0.564c0.869 2e-3 1.729-0.175 2.526-0.52s1.514-0.851 2.107-1.487c0.593-0.634 1.049-1.385 1.338-2.204 0.289-0.82 0.408-1.69 0.345-2.557-9.135-142.56-134.21-193.54-249.59-193.54-136.81 0-236.85 90.227-236.85 189.7 0 72.633 20.527 140.76 181.92 188.12 28.309 8.233 66.769 18.947 100.38 28.309 40.376 11.279 62.143 28.309 62.143 55.151 0 31.128-45.113 52.782-89.437 52.782-64.174 0-109.74-23.797-113.46-66.543-0.194-1.563-0.955-3.003-2.141-4.043-1.185-1.04-2.711-1.608-4.288-1.596l-147.3 0.677c-0.86355 0-1.7182 0.173-2.5133 0.511-0.79503 0.337-1.514 0.83-2.114 1.452-0.6 0.62-1.0688 1.356-1.3783 2.162-0.30948 0.807-0.45331 1.667-0.42301 2.53 6.767 134.55 136.69 207.07 257.83 207.07 180.45 0 262-101.5 262-196.58 0.226-44.663-10.038-146.39-161.73-185.19z\"/><path d=\"m2257.4 206.41c-74.99 0-137.82 41.504-178.31 91.582v-85.717c0-1.596-0.63-3.129-1.75-4.267-1.1-1.139-2.63-1.794-4.23-1.822h-140.07c-1.61 0-3.17 0.64-4.31 1.782-1.14 1.143-1.79 2.693-1.79 4.307v800.77c0.04 1.59 0.7 3.12 1.84 4.23 1.14 1.12 2.67 1.75 4.26 1.75h149.89c1.58 0 3.1-0.63 4.22-1.75s1.75-2.65 1.75-4.23v-263.24h2.26c23.79 36.315 88.87 79.851 173.92 79.851 159.91 0 293.23-132.63 293.23-311.85 0.12-172-132.52-311.4-300.91-311.4zm-13.87 470.65c-31.56 0.784-62.67-7.857-89.3-24.819-26.63-16.964-47.62-41.479-60.27-70.418-12.64-28.94-16.38-60.991-10.72-92.063 5.64-31.072 20.43-59.755 42.45-82.388 22.03-22.636 50.3-38.194 81.21-44.69 30.9-6.496 63.04-3.637 92.31 8.214 29.28 11.85 54.35 32.155 72.04 58.322 17.68 26.168 27.16 57.009 27.25 88.591 0.32 20.643-3.44 41.149-11.05 60.339s-18.95 36.686-33.35 51.483c-14.39 14.797-31.57 26.604-50.56 34.743-18.97 8.14-39.36 12.45-60.01 12.686z\"/><path d=\"m1483.3 171.23c-139.74 0-209.44 47.482-265.39 85.491l-1.69 1.127c-2.88 1.974-4.91 4.966-5.69 8.374-0.77 3.409-0.23 6.983 1.52 10.01l55.26 95.188c1.04 1.782 2.46 3.313 4.15 4.482 1.7 1.17 3.63 1.951 5.67 2.286 1.99 0.359 4.03 0.272 5.98-0.255s3.76-1.478 5.3-2.791l4.39-3.608c28.76-24.136 74.89-56.393 186.55-65.19 62.14-4.961 115.83 11.279 155.41 48.272 43.54 40.152 69.6 105 69.6 173.46 0 125.98-74.22 205.15-193.43 206.73-98.24-0.564-164.22-51.768-164.22-127.45 0-40.152 18.16-66.317 53.58-92.483 2.7-1.934 4.61-4.781 5.38-8.015s0.34-6.637-1.21-9.579l-49.63-93.837c-0.91-1.679-2.15-3.161-3.64-4.361s-3.2-2.094-5.04-2.631c-1.88-0.559-3.85-0.717-5.79-0.466-1.95 0.253-3.82 0.911-5.49 1.933-55.71 33.045-124.06 93.497-120.34 209.66 4.51 147.86 127.45 260.76 287.26 265.38h18.95c189.92-6.204 327.07-147.18 327.07-338.35 0-175.49-127.9-363.39-364.51-363.39z\"/><path d=\"m3148.9 261.46h-95.2c-2.22 0.029-4.36 0.93-5.94 2.509-1.59 1.58-2.49 3.715-2.5 5.95v199.74c0.01 2.225 0.92 4.346 2.51 5.908 1.58 1.562 3.71 2.439 5.93 2.439h95.2c57.97 0 100.72-45.678 100.72-108.27s-42.75-108.27-100.72-108.27z\"/><path d=\"m3441.4 614.8c0 28.985 24.47 45.113 67.1 45.113 57.97 0 92.25-31.354 92.25-86.957v-16.014l-86.83 4.511c-45.8 2.255-72.52 21.317-72.52 53.347z\"/><path d=\"m4146.3 2.0498h-1279c-20.97-2e-5 -41.76 4.1346-61.13 12.167-19.39 8.0328-37 19.806-51.82 34.648-14.84 14.842-26.6 32.46-34.62 51.85-8.03 19.389-12.14 40.168-12.12 61.15v700.16c0 42.366 16.82 82.999 46.77 112.97 29.95 29.968 70.57 46.818 112.92 46.848h1279c21.01 0.06 41.83-4.02 61.26-12.01 19.42-7.99 37.08-19.737 51.97-34.557 14.87-14.823 26.7-32.434 34.78-51.828 8.07-19.393 12.23-40.187 12.27-61.193v-700.16c0.03-21.048-4.08-41.898-12.12-61.35-8.04-19.452-19.85-37.122-34.74-51.995-14.89-14.873-32.58-26.655-52.04-34.668-19.46-8.0136-40.32-12.101-61.38-12.026zm-992.5 554.56h-100.6c-2.24 0-4.38 0.89-5.98 2.476-1.58 1.587-2.48 3.739-2.48 5.983v143.23c0 2.243-0.89 4.395-2.47 5.981-1.59 1.587-3.74 2.478-5.98 2.478h-70.84c-2.22-0.029-4.37-0.93-5.95-2.511-1.58-1.578-2.46-3.713-2.5-5.948v-516.66c0-2.242 0.89-4.394 2.49-5.981 1.58-1.586 3.72-2.477 5.96-2.477h188.35c106.7 0 183.05 77.708 183.05 186.77s-75.79 186.88-182.47 186.88l-0.58-0.224zm530.09 151.58c0.02 1.12-0.18 2.231-0.61 3.271-0.42 1.039-1.04 1.986-1.82 2.783-0.8 0.797-1.73 1.431-2.77 1.863-1.02 0.431-2.14 0.654-3.26 0.654h-66.88c-1.12 0-2.23-0.223-3.26-0.654-1.04-0.432-1.98-1.066-2.76-1.863s-1.41-1.744-1.82-2.783c-0.42-1.04-0.63-2.151-0.61-3.271v-15.451c0.1-1.357-0.22-2.713-0.95-3.865-0.71-1.154-1.78-2.045-3.06-2.54-1.26-0.494-2.65-0.565-3.96-0.203-1.33 0.36-2.48 1.135-3.31 2.209-19.97 21.767-52.45 37.556-104.22 37.556-76.23 0-126.66-39.699-126.66-108.27-0.73-16.72 2.72-33.359 10.05-48.408 7.32-15.046 18.3-28.026 31.92-37.758 27.51-20.64 70.14-31.354 133.41-33.836l67.1-2.255v-19.626c0-39.587-26.61-56.391-69.36-56.391-42.74 0-69.7 15.113-76 39.813-0.51 1.744-1.58 3.27-3.06 4.333-1.46 1.064-3.25 1.602-5.07 1.531h-66.2c-1.22 0.031-2.43-0.207-3.55-0.693-1.1-0.488-2.11-1.214-2.92-2.128-0.8-0.915-1.4-1.992-1.74-3.162-0.35-1.169-0.44-2.398-0.25-3.603 9.93-58.648 58.42-103.2 161.85-103.2 109.85 0 149.43 51.092 149.43 148.65l0.34 207.3zm416.63-335.2-148.87 397.11c-33.84 92.256-93.06 115.94-157.91 115.94-12.21 0.298-24.41-1.184-36.2-4.398-1.84-0.495-3.45-1.579-4.63-3.089-1.15-1.507-1.78-3.355-1.8-5.258v-60.34c0-1.262 0.27-2.51 0.8-3.654 0.54-1.144 1.31-2.157 2.28-2.964 0.98-0.809 2.11-1.392 3.33-1.71s2.5-0.363 3.74-0.131c10.23 1.94 20.61 2.922 31.02 2.934 17.93 0.899 35.65-4.247 50.32-14.615 14.65-10.368 25.41-25.358 30.54-42.567l4.41-13.873c0.68-1.856 0.68-3.894 0-5.752l-139.19-357.52c-0.42-1.278-0.54-2.64-0.34-3.972 0.21-1.333 0.72-2.6 1.48-3.698 0.79-1.098 1.82-1.997 3.01-2.625 1.19-0.627 2.52-0.965 3.86-0.984h67.68c1.73 0.017 3.41 0.551 4.84 1.537 1.43 0.984 2.53 2.374 3.16 3.99l94.52 252.18c0.63 1.647 1.73 3.066 3.18 4.067 1.46 1.003 3.17 1.538 4.94 1.538 1.75 0 3.49-0.535 4.93-1.538 1.45-1.001 2.57-2.42 3.18-4.067l82.01-251.51c0.54-1.715 1.63-3.209 3.09-4.264 1.46-1.056 3.21-1.617 5.01-1.601h69.38c1.33-6e-3 2.65 0.306 3.86 0.904 1.19 0.6 2.24 1.472 3.04 2.547s1.33 2.322 1.56 3.643c0.24 1.319 0.16 2.675-0.23 3.958v-0.226z\"/></g><defs><clipPath id=\"a\"><rect transform=\"translate(0 .24023)\" width=\"4317\" height=\"1036.8\" fill=\"#fff\"/></clipPath></defs></svg>`,\n }),\n []\n );\n\n if (!settings) return null;\n\n return (\n <div\n className={styles['rebuy-checkout-area']}\n data-rebuy-component=\"checkout-area\"\n data-rebuy-component-id={componentConfig.component_id}\n >\n {hasTermsEnabled && (\n <div className={styles['rebuy-checkout-area__terms']}>\n <input\n checked={termsAccepted}\n className={styles['rebuy-checkout-area__terms-checkbox']}\n disabled={isTermsCheckboxDisabled || !hasItems}\n id={`rebuy-terms-checkbox-${componentConfig.component_id}`}\n name=\"rebuy-terms-checkbox\"\n onChange={handleTermsChange}\n type=\"checkbox\"\n />\n <label\n className={styles['rebuy-checkout-area__terms-label']}\n dangerouslySetInnerHTML={{ __html: termsLabel }}\n htmlFor={`rebuy-terms-checkbox-${componentConfig.component_id}`}\n />\n </div>\n )}\n\n {hasCheckoutButton && (\n <button\n className={styles['rebuy-checkout-area__checkout-button']}\n disabled={isCheckoutDisabled}\n onClick={handleCheckoutClick}\n type=\"button\"\n >\n <span dangerouslySetInnerHTML={{ __html: checkoutLabel }} />\n </button>\n )}\n\n {hasViewCartButton && (\n <button\n className={styles['rebuy-checkout-area__view-cart-button']}\n disabled={isAnyCriticalActionProcessing && processingSource !== 'terms'}\n onClick={handleViewCartClick}\n type=\"button\"\n >\n <span dangerouslySetInnerHTML={{ __html: viewCartLabel }} />\n </button>\n )}\n\n {hasContinueShoppingButton && (\n <button\n className={styles['rebuy-checkout-area__continue-shopping-button']}\n disabled={isAnyCriticalActionProcessing && processingSource !== 'terms'}\n onClick={handleContinueShoppingClick}\n type=\"button\"\n >\n <span\n dangerouslySetInnerHTML={{\n __html: continueShoppingLabel,\n }}\n />\n </button>\n )}\n\n {hasShopPayButton && (\n <button\n aria-label=\"Checkout with Shop Pay\"\n className={styles['rebuy-checkout-area__shop-pay-button']}\n dangerouslySetInnerHTML={shopPaySvg}\n disabled={isCheckoutDisabled}\n onClick={handleShopPayClick}\n />\n )}\n\n {hasInstallments && installmentsMessage && hasItems && (\n <div\n className={styles['rebuy-checkout-area__installments-message']}\n dangerouslySetInnerHTML={{\n __html: installmentsMessage,\n }}\n />\n )}\n\n {/* // TODO: Consider how this will need to be different in the NPM Rebuy Hydrogen package */}\n {/* Pre-Purchase Widget Trigger */}\n {hasPrePurchase && hasItems && <div data-rebuy-id={settings.pre_purchase.widget_id} />}\n </div>\n );\n});\n\nCheckoutArea.displayName = 'CheckoutArea';\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/smart-cart/components/CheckoutArea/CheckoutArea.css\";\n const result = {\"rebuy-checkout-area\":\"CheckoutArea_rebuy-checkout-area\",\"rebuy-checkout-area__terms\":\"CheckoutArea_rebuy-checkout-area__terms\",\"rebuy-checkout-area__terms-checkbox\":\"CheckoutArea_rebuy-checkout-area__terms-checkbox\",\"rebuy-checkout-area__terms-label\":\"CheckoutArea_rebuy-checkout-area__terms-label\",\"rebuy-checkout-area__installments-message\":\"CheckoutArea_rebuy-checkout-area__installments-message\",\"rebuy-checkout-area__checkout-button\":\"CheckoutArea_rebuy-checkout-area__checkout-button\",\"rebuy-checkout-area__view-cart-button\":\"CheckoutArea_rebuy-checkout-area__view-cart-button\",\"rebuy-checkout-area__continue-shopping-button\":\"CheckoutArea_rebuy-checkout-area__continue-shopping-button\",\"rebuy-checkout-area__shop-pay-button\":\"CheckoutArea_rebuy-checkout-area__shop-pay-button\"};\n export default result;\n ", "/* eslint-disable import/order */\nimport { RebuyClient } from '@rebuy/rebuy';\nimport * as Utilities from '@rebuy/rebuy/utilities';\nimport { flattenConnection } from '@shopify/hydrogen';\nimport { useContext, useEffect, useMemo, useRef, useState } from 'react';\nimport { Close } from '~/assets/Close';\nimport { useRebuyConfig } from '~/context/RebuyConfigContext';\nimport { RebuyContext } from '~/context/RebuyContext';\nimport { useBreakpoint } from '~/hooks/useBreakpoint';\nimport { usePopupTrigger } from '~/hooks/usePopupTrigger';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport type {\n CartItem,\n CustomEndpointQueryParams,\n RebuyProduct,\n RecommendedEndpointQueryParams,\n} from '~/types/rebuyCustom';\nimport { widgetSettingsSchema, type WidgetSettings } from '~/types/widgets';\nimport { filterContextForWidgetEndpoints } from '~/utils/filterContextUtils';\nimport type { RebuyWidgetProps } from './types';\nimport { WidgetContent } from './WidgetContent';\n\nimport { DebugKey } from '~/constants/debug';\nimport styles from './RebuyWidget.module.css';\n\nexport const RebuyWidget = (props: RebuyWidgetProps) => {\n const {\n addToCartCallback,\n customTitle,\n customTitleLevel = 'h2',\n customTitleStyle,\n isCrossSell,\n popupTriggerId,\n product,\n productId,\n variant,\n variantId,\n widgetId,\n } = props;\n\n // Get API key and config from the new config context\n const { apiKey: apiKeyFromConfig, loadingStatus: configLoadingStatus, rebuyConfig } = useRebuyConfig();\n\n const [settings, setSettings] = useState<WidgetSettings | null>(null);\n const [loadingSettings, setLoadingSettings] = useState<boolean>(true);\n const [error, setError] = useState<string | null>(null);\n const [showPopup, setShowPopup] = useState<boolean>(false);\n const [popupShownOnce, setPopupShownOnce] = useState<boolean>(false);\n const popupRef = useRef<HTMLDivElement>(null);\n const [clientInstance, setClientInstance] = useState<RebuyClient | null>(null);\n\n // Get general context parameters (for things like cart data, customer info, etc.)\n const rebuyGeneralContext = useContext(RebuyContext);\n const generalContextParams = rebuyGeneralContext?.contextParameters;\n\n // Cache key should primarily come from rebuyConfig, with fallback to general context\n const mainCacheKey = rebuyConfig?.shop?.cache_key;\n const generalContextCacheKey = generalContextParams?.cache_key;\n const cacheKeyToUse = mainCacheKey || generalContextCacheKey || '';\n\n const [initialized, setInitialized] = useState(false);\n const shopifyProductId = product?.id ?? productId ?? null;\n const shopifyVariantId = variant?.id ?? variantId ?? null;\n const [products, setProducts] = useState<RebuyProduct[]>([]);\n\n // Get current breakpoint to check if widget should be displayed\n const currentBreakpoint = useBreakpoint(settings);\n\n // Check if layout style is \"none\" for current breakpoint\n const shouldHideWidget = settings?.layout?.[currentBreakpoint]?.style === 'none';\n\n // Use the custom hook for popup triggers\n usePopupTrigger(settings, popupTriggerId, widgetId, popupShownOnce, showPopup, setShowPopup, setPopupShownOnce);\n\n // Initialize Rebuy API client\n useEffect(() => {\n if (!clientInstance && apiKeyFromConfig && configLoadingStatus === 'success') {\n const client = new RebuyClient(apiKeyFromConfig);\n\n // Set general context parameters if available, using default filter (CustomEndpoint)\n // as settings.endpoint is not yet known here.\n if (generalContextParams) {\n const filteredParams = filterContextForWidgetEndpoints(generalContextParams, undefined);\n client.setContextParameters(filteredParams as Record<string, unknown>);\n }\n\n setClientInstance(client);\n setInitialized(true);\n }\n }, [clientInstance, apiKeyFromConfig, configLoadingStatus, generalContextParams]);\n\n // Update context parameters whenever they change, or when settings are available/change\n useEffect(() => {\n if (!clientInstance || !generalContextParams) return;\n\n // Now filter based on settings.endpoint if available, otherwise default filter.\n const filteredParams = filterContextForWidgetEndpoints(generalContextParams, settings?.endpoint);\n clientInstance.setContextParameters(filteredParams as Record<string, unknown>);\n }, [clientInstance, generalContextParams, settings]);\n\n // Fetch widget settings\n useEffect(() => {\n // Don't proceed if config is still loading\n if (configLoadingStatus === 'loading') {\n return;\n }\n\n // Exit early if essential dependencies for fetching settings are not ready\n if (!widgetId) {\n setError('Widget ID is missing.');\n setSettings(null);\n setLoadingSettings(false);\n\n return;\n }\n\n if (configLoadingStatus === 'error') {\n setError('Rebuy configuration failed to load.');\n setSettings(null);\n setLoadingSettings(false);\n\n return;\n }\n\n if (!apiKeyFromConfig && configLoadingStatus === 'success') {\n setError('Rebuy API Key is missing.');\n setSettings(null);\n setLoadingSettings(false);\n\n return;\n }\n\n if (!clientInstance || !initialized) {\n // Don't set error here - just return and wait for initialization\n return;\n }\n\n const fetchSettings = async () => {\n setLoadingSettings(true);\n setError(null); // Clear previous errors before a new fetch attempt\n try {\n const settingsParams: Record<string, unknown> = { id: widgetId };\n\n if (cacheKeyToUse) {\n settingsParams.cache_key = cacheKeyToUse;\n }\n const settingsResponse = (await clientInstance.getShieldedAsset(\n '/api/v1/widgets/settings',\n settingsParams\n )) as unknown as {\n data: unknown;\n };\n\n // Parse settings data using Zod schema\n const parseResult = widgetSettingsSchema.safeParse(settingsResponse?.data);\n\n if (!parseResult.success) {\n throw new Error(`Invalid settings data: ${parseResult.error.message}`);\n }\n\n const fetchedWidgetSettings = parseResult.data;\n\n if (!fetchedWidgetSettings.endpoint || fetchedWidgetSettings.endpoint.trim() === '') {\n throw new Error('Received invalid settings data: endpoint is missing or invalid.');\n }\n\n setSettings({\n ...fetchedWidgetSettings,\n hide_quantity_selector: fetchedWidgetSettings.hide_quantity_selector ?? false,\n });\n } catch (e) {\n console.error(`[RebuyWidget] Error fetching widget settings for ID ${widgetId}:`, e);\n setError(e instanceof Error ? e.message : 'Failed to load widget configuration.');\n setSettings(null); // Reset settings on error\n } finally {\n setLoadingSettings(false);\n }\n };\n fetchSettings();\n }, [widgetId, clientInstance, configLoadingStatus, apiKeyFromConfig, cacheKeyToUse, initialized]);\n\n // Extract cart product and variant IDs from generalContextParams\n // These IDs are typically numeric in the `contextParameters.cart` object.\n const cartProductIds = useMemo(() => {\n return (generalContextParams?.cart?.items || [])\n .map((item: CartItem) => item.product_id)\n .filter(Boolean)\n .join(',');\n }, [generalContextParams?.cart?.items]);\n\n const cartVariantIds = useMemo(() => {\n return (generalContextParams?.cart?.items || [])\n .map((item: CartItem) => item.variant_id)\n .filter(Boolean)\n .join(',');\n }, [generalContextParams?.cart?.items]);\n\n // Memoize request object on prop changes (e.g. product)\n const request = useMemo(() => {\n const req = {\n endpoint: settings?.endpoint || '/api/v1/products/recommended',\n params: {} as CustomEndpointQueryParams | RecommendedEndpointQueryParams,\n };\n\n if (shopifyProductId) {\n const pId = Utilities.getIdFromGraphUrl(shopifyProductId, 'Product');\n\n if (pId !== null) req.params.shopify_product_ids = pId.toString();\n }\n\n if (shopifyVariantId) {\n const vId = Utilities.getIdFromGraphUrl(shopifyVariantId, 'ProductVariant');\n\n if (vId !== null) req.params.shopify_variant_ids = vId.toString();\n }\n\n if (settings?.limit) {\n req.params.limit = settings.limit;\n }\n\n /* Cart widgets may refresh their products when the cart changes */\n if (settings?.type?.toLowerCase() === 'cart') {\n if (cartProductIds) {\n const existingPids = req.params.shopify_product_ids ? req.params.shopify_product_ids.split(',') : [];\n const cartPidsArray = cartProductIds.split(',');\n req.params.shopify_product_ids = [...new Set([...existingPids, ...cartPidsArray])].join(',');\n }\n\n if (cartVariantIds) {\n const existingVids = req.params.shopify_variant_ids ? req.params.shopify_variant_ids.split(',') : [];\n const cartVidsArray = cartVariantIds.split(',');\n req.params.shopify_variant_ids = [...new Set([...existingVids, ...cartVidsArray])].join(',');\n }\n }\n\n return req;\n }, [settings, shopifyProductId, shopifyVariantId, cartProductIds, cartVariantIds]);\n\n // Update product recommendations on cart or request change\n useEffect(() => {\n let isMounted = true;\n\n if (!clientInstance || !initialized || !settings || configLoadingStatus !== 'success') return;\n\n const fetchData = async () => {\n try {\n // Copy params to avoid mutation. Client context parameters are handled separately.\n const paramsForApi: CustomEndpointQueryParams | RecommendedEndpointQueryParams = {\n ...request.params,\n };\n\n // Ensure we have the cache key\n if (cacheKeyToUse) {\n paramsForApi.cache_key = cacheKeyToUse;\n }\n\n // Add a uuid for cache busting\n paramsForApi.uuid = crypto.randomUUID?.() || Math.random().toString(36).substring(2);\n\n // Make sure API key is included in params sent directly to getStorefrontData,\n // as client contextParameters might not include 'key' by design of the filter.\n if (apiKeyFromConfig) {\n paramsForApi.key = apiKeyFromConfig;\n }\n\n // Fix endpoint if needed\n let endpointToUse = request.endpoint;\n\n if (endpointToUse && endpointToUse.startsWith('/') && !endpointToUse.startsWith('/api/v1/')) {\n if (endpointToUse.startsWith('/custom') || endpointToUse.startsWith('/rules')) {\n endpointToUse = `/api/v1${endpointToUse}`;\n }\n }\n\n const { data } = (await clientInstance.getStorefrontData(endpointToUse, paramsForApi)) as {\n data: RebuyProduct[];\n };\n\n // Set state only if component is still mounted\n if (isMounted) {\n setProducts(\n Array.isArray(data)\n ? data.map((p) => ({\n ...p,\n variants: { nodes: p.variants ? flattenConnection(p.variants) : [] },\n }))\n : []\n );\n }\n } catch (e) {\n console.error(`Error fetching products for widget ID ${widgetId}`, e);\n\n if (isMounted) {\n setProducts([]);\n setError(e instanceof Error ? e.message : 'Failed to load products.');\n }\n }\n };\n\n fetchData();\n\n return () => {\n isMounted = false;\n };\n }, [\n clientInstance,\n initialized,\n request,\n widgetId,\n settings,\n configLoadingStatus,\n apiKeyFromConfig,\n cacheKeyToUse,\n ]);\n\n // Handle click outside popup to close\n useEffect(() => {\n if (!showPopup) return;\n\n const handleClickOutside = (event: MouseEvent) => {\n if (popupRef.current && !popupRef.current.contains(event.target as Node)) {\n setShowPopup(false);\n }\n };\n\n document.addEventListener('mousedown', handleClickOutside);\n\n return () => {\n document.removeEventListener('mousedown', handleClickOutside);\n };\n }, [showPopup]);\n\n const closePopup = () => {\n setShowPopup(false);\n };\n\n if (configLoadingStatus === 'loading') return null;\n\n if (configLoadingStatus === 'error') {\n console.error('Rebuy configuration failed to load');\n\n return null;\n }\n\n // If products array is empty AND settings are loaded AND not currently loading settings,\n // then we can confidently say there are no products.\n if (products?.length === 0 && settings && !loadingSettings) {\n rebuyDebugLog.log(DebugKey.WIDGET, 'No products to render for widgetId:', widgetId);\n\n return null;\n }\n\n if (error && !products?.length) {\n // Only return null for error if there are no products to show\n console.error('[RebuyWidget] Error state:', error);\n\n return null;\n }\n\n // If layout style is \"none\" for current breakpoint, don't render anything\n if (settings && !loadingSettings && shouldHideWidget) {\n return null;\n }\n\n return (\n <>\n {/* Render only if not loading settings, and either products exist or settings are not yet fully processed (to avoid flicker) */}\n {(settings || products?.length > 0) && !loadingSettings && (\n <div className={styles['rebuy-widget__container']} id={`rebuy-widget-${widgetId}`}>\n {settings?.display_type === 'popup' &&\n (settings.popup_trigger !== 'add_to_cart' ||\n (settings.popup_trigger === 'add_to_cart' && popupTriggerId)) ? (\n <div>\n {showPopup && (\n <div className={styles['rebuy-widget__popup-overlay']}>\n <div className={styles['rebuy-widget__popup-content']} ref={popupRef}>\n <div className={styles['rebuy-widget__content']}>\n <button\n aria-label=\"close modal\"\n className={styles['rebuy-widget__modal-close']}\n onClick={closePopup}\n >\n <Close />\n </button>\n <WidgetContent\n addToCartCallback={() => {\n addToCartCallback?.();\n // Set timeout is required: Do not touch\n setTimeout(() => {\n closePopup();\n }, 0);\n }}\n cartCount={generalContextParams?.cart_count || 0}\n checkoutUrl={generalContextParams?.checkoutUrl}\n customTitle={customTitle}\n customTitleLevel={customTitleLevel}\n customTitleStyle={customTitleStyle}\n isHydrogenReact={\n rebuyGeneralContext?.contextParameters?.isHydrogenReact\n }\n isInPopup={true} // Explicitly true for popup\n onDismiss={closePopup}\n products={products}\n settings={settings!} // settings will be non-null here\n />\n </div>\n </div>\n </div>\n )}\n </div>\n ) : (\n <div className={styles['rebuy-widget__content']}>\n <WidgetContent\n addToCartCallback={addToCartCallback}\n checkoutUrl={generalContextParams?.checkoutUrl}\n customTitle={customTitle}\n customTitleLevel={customTitleLevel}\n customTitleStyle={customTitleStyle}\n isCrossSell={isCrossSell} // Only present in embedded to support in cart widgets\n isHydrogenReact={rebuyGeneralContext?.contextParameters?.isHydrogenReact}\n isInPopup={settings?.display_type === 'popup'} // Correctly reflect if it's a popup type\n products={products}\n settings={settings!} // settings will be non-null here due to outer check\n />\n </div>\n )}\n </div>\n )}\n </>\n );\n};\n", "export const Close = () => {\n return (\n <svg height=\"1em\" viewBox=\"0 0 352 512\" width=\"1em\">\n <path d=\"M242.72 256l100.07-100.07c12.28-12.28 12.28-32.19 0-44.48l-22.24-22.24c-12.28-12.28-32.19-12.28-44.48 0L176 189.28 75.93 89.21c-12.28-12.28-32.19-12.28-44.48 0L9.21 111.45c-12.28 12.28-12.28 32.19 0 44.48L109.28 256 9.21 356.07c-12.28 12.28-12.28 32.19 0 44.48l22.24 22.24c12.28 12.28 32.19 12.28 44.48 0L176 322.72l100.07 100.07c12.28 12.28 32.19 12.28 44.48 0l22.24-22.24c12.28-12.28 12.28-32.19 0-44.48L242.72 256z\" />\n </svg>\n );\n};\n", "import { useEffect, useState } from 'react';\nimport type { WidgetSettings } from '~/types/widgets';\n\ntype Breakpoint = 'small' | 'medium' | 'large';\n\nexport const useBreakpoint = (settings: WidgetSettings | null): Breakpoint => {\n const [breakpoint, setBreakpoint] = useState<Breakpoint>('medium');\n\n useEffect(() => {\n if (!settings?.breakpoints) return;\n\n const handleResize = () => {\n const width = window.innerWidth;\n\n // Convert breakpoint values to numbers for comparison\n const mediumMax =\n typeof settings.breakpoints.medium.max === 'number'\n ? settings.breakpoints.medium.max\n : parseFloat(settings.breakpoints.medium.max) || 0;\n const mediumMin =\n typeof settings.breakpoints.medium.min === 'number'\n ? settings.breakpoints.medium.min\n : parseFloat(settings.breakpoints.medium.min) || 0;\n\n if (width <= mediumMax) {\n if (width >= mediumMin) {\n setBreakpoint('medium');\n } else {\n setBreakpoint('small');\n }\n } else {\n setBreakpoint('large');\n }\n };\n\n // Set initial breakpoint\n handleResize();\n\n // Debounce configuration\n const debounceDelay = 150; // ms\n let timeoutId: ReturnType<typeof setTimeout>;\n\n // Debounced resize handler\n const debouncedHandleResize = () => {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(handleResize, debounceDelay);\n };\n\n // Add resize listener with debounce\n window.addEventListener('resize', debouncedHandleResize);\n\n // Clean up\n return () => {\n window.removeEventListener('resize', debouncedHandleResize);\n clearTimeout(timeoutId);\n };\n }, [settings]);\n\n return breakpoint;\n};\n", "import { useCallback, useEffect } from 'react';\nimport type { WidgetSettings } from '~/types/widgets';\n\nexport const usePopupTrigger = (\n settings: WidgetSettings | null,\n popupTriggerId: string | undefined,\n widgetId: string,\n popupShownOnce: boolean,\n showPopup: boolean,\n setShowPopup: (show: boolean) => void,\n setPopupShownOnce: (shown: boolean) => void\n) => {\n const delayInMs = settings?.display_type === 'popup' ? (settings?.popup_delay || 0) * 1000 : 0;\n const popupTrigger = settings?.popup_trigger;\n\n const showPopupWithDelay = useCallback(() => {\n if (!settings || settings.display_type !== 'popup') return;\n\n setTimeout(() => {\n setShowPopup(true);\n setPopupShownOnce(true);\n }, delayInMs);\n }, [delayInMs, setShowPopup, setPopupShownOnce, settings]);\n\n // Handle load trigger\n useEffect(() => {\n if (!settings || settings.display_type !== 'popup' || popupTrigger !== 'load' || popupShownOnce) return;\n\n const timer = setTimeout(() => {\n setShowPopup(true);\n setPopupShownOnce(true);\n }, delayInMs);\n\n return () => clearTimeout(timer);\n }, [popupTrigger, popupShownOnce, delayInMs, setShowPopup, setPopupShownOnce, settings]);\n\n // Handle add_to_cart trigger\n useEffect(() => {\n if (!settings || settings.display_type !== 'popup' || popupTrigger !== 'add_to_cart' || !popupTriggerId) return;\n\n const selector = `#${popupTriggerId}`;\n const handleCartAdd = () => {\n if (!showPopup) {\n showPopupWithDelay();\n }\n };\n\n // Setup a mutation observer to watch for the element if it's not immediately available\n const observer = new MutationObserver(() => {\n const elements = document.querySelectorAll(selector);\n\n if (elements.length) {\n elements.forEach((el) => {\n el.addEventListener('click', handleCartAdd);\n });\n observer.disconnect();\n }\n });\n\n // First check if element already exists\n const elements = document.querySelectorAll(selector);\n\n if (elements.length) {\n elements.forEach((el) => {\n el.addEventListener('click', handleCartAdd);\n });\n } else {\n // If not, start observing\n observer.observe(document.body, { childList: true, subtree: true });\n }\n\n return () => {\n observer.disconnect();\n document.querySelectorAll(selector).forEach((el) => {\n el.removeEventListener('click', handleCartAdd);\n });\n };\n }, [popupTrigger, popupTriggerId, showPopup, showPopupWithDelay, settings]);\n\n // Handle form submit trigger\n useEffect(() => {\n if (!settings || settings.display_type !== 'popup' || popupTrigger !== 'submit') return;\n\n const selector = 'form';\n const handleSubmit = () => {\n showPopupWithDelay();\n };\n\n const forms = document.querySelectorAll(selector);\n forms.forEach((form) => {\n form.addEventListener('submit', handleSubmit);\n });\n\n return () => {\n forms.forEach((form) => {\n form.removeEventListener('submit', handleSubmit);\n });\n };\n }, [popupTrigger, showPopupWithDelay, settings]);\n\n // Handle exit intent trigger\n useEffect(() => {\n if (!settings || settings.display_type !== 'popup' || popupTrigger !== 'exit') return;\n\n const handleExitIntent = (e: MouseEvent) => {\n if (e.clientY <= 0 && !popupShownOnce) {\n showPopupWithDelay();\n }\n };\n\n const handleVisibilityChange = () => {\n if (document.visibilityState === 'hidden' && !popupShownOnce) {\n const shouldShowOnFocus = true;\n localStorage.setItem(`rebuy-popup-pending-${widgetId}`, shouldShowOnFocus.toString());\n } else if (document.visibilityState === 'visible') {\n const pendingPopup = localStorage.getItem(`rebuy-popup-pending-${widgetId}`);\n\n if (pendingPopup === 'true' && !popupShownOnce) {\n showPopupWithDelay();\n localStorage.removeItem(`rebuy-popup-pending-${widgetId}`);\n }\n }\n };\n\n document.addEventListener('mouseleave', handleExitIntent);\n document.addEventListener('visibilitychange', handleVisibilityChange);\n\n // Check visibility state on mount\n if (document.visibilityState === 'visible') {\n const pendingPopup = localStorage.getItem(`rebuy-popup-pending-${widgetId}`);\n\n if (pendingPopup === 'true' && !popupShownOnce) {\n showPopupWithDelay();\n localStorage.removeItem(`rebuy-popup-pending-${widgetId}`);\n }\n }\n\n return () => {\n document.removeEventListener('mouseleave', handleExitIntent);\n document.removeEventListener('visibilitychange', handleVisibilityChange);\n };\n }, [popupTrigger, popupShownOnce, showPopupWithDelay, widgetId, settings]);\n};\n", "import { z } from 'zod';\nimport { type RebuyProduct, type RebuyProductVariant, type RebuyWidgetMetadata } from '~/types/rebuyCustom';\nimport type { HydrogenProduct } from '~/types/shopify';\n\nconst integrationsSchema = z.object({\n judgeme: z.boolean(),\n junip: z.boolean(),\n klaviyo: z.boolean(),\n loox: z.boolean(),\n okendo: z.boolean(),\n opinew: z.boolean(),\n recharge: z.boolean(),\n reviewsio: z.boolean(),\n stamped: z.boolean(),\n yotpo: z.boolean(),\n});\n\nconst discountSchema = z.object({\n amount: z.union([z.string(), z.number()]),\n bundle_protection: z\n .object({\n allowed_removals: z.number(),\n disable_atc_on_incomplete: z.boolean(),\n enabled: z.boolean(),\n })\n .optional(),\n discount_protection: z\n .object({\n enabled: z.boolean(),\n minimum_items_to_get_discount: z.number(),\n })\n .optional(),\n discounted_by: z.string().optional(),\n discounted_from: z.string().optional(),\n discountedBy: z.string().optional(),\n discountedFrom: z.string().optional(),\n message: z.string().optional(),\n quantity: z.number().optional(),\n show_saving_amount: z.boolean().optional(),\n showSavingAmount: z.boolean().optional(),\n type: z.string(),\n});\n\nconst excludeItemsSchema = z.object({\n digital_items: z.boolean(),\n gift_cards: z.boolean(),\n});\n\nconst timerSchema = z.object({\n action: z.enum(['dismiss', 'checkout', 'cart', 'stop']),\n duration_minutes: z.union([z.number(), z.null()]),\n duration_seconds: z.union([z.number(), z.null()]),\n enabled: z.boolean(),\n});\n\nconst layoutSizeSchema = z.object({\n carousel: z.boolean(),\n columns: z.number(),\n show_paginations: z.boolean(),\n style: z.string(),\n});\n\nconst layoutSchema = z.object({\n large: layoutSizeSchema,\n medium: layoutSizeSchema,\n small: layoutSizeSchema,\n});\n\nconst productOptionsSchema = z.object({\n hide_out_of_stock_variants: z.boolean(),\n match_on_selling_plan: z.boolean().optional(),\n match_variant: z.boolean(),\n match_variant_out_of_stock: z.boolean().optional(),\n show_product_description: z.enum(['show', 'hide']),\n show_subscription_options: z.string(),\n show_variant_options: z.enum(['default', 'never', 'always', 'dynamic']),\n show_variant_title: z.enum(['show', 'hide']),\n show_variants_as_products: z.boolean(),\n variant_display_limit: z.string(),\n});\n\nconst viewOptionsSchema = z.object({\n cookie_days: z.number(),\n display_actions: z.boolean(),\n limit_views: z.boolean(),\n max_views: z.number(),\n variant_selector: z.string(),\n});\n\nconst imagesSchema = z.object({\n border_radius: z.number(),\n border_radius_unit: z.string(),\n fixed_height: z.boolean(),\n fixed_width: z.boolean(),\n height: z.number(),\n source: z.string(),\n width: z.number(),\n});\n\nconst breakpointSizeSchema = z.object({\n max: z.union([z.string(), z.number()]),\n min: z.union([z.string(), z.number()]),\n});\n\nconst breakpointsSchema = z.object({\n large: breakpointSizeSchema,\n medium: breakpointSizeSchema,\n small: breakpointSizeSchema,\n});\n\nconst placementSizeSchema = z.object({\n enabled: z.boolean(),\n location: z.string(),\n selector: z.string().nullable(),\n});\n\nconst placementSchema = z.object({\n large: placementSizeSchema,\n medium: placementSizeSchema,\n small: placementSizeSchema,\n});\n\nconst languageSchema = z.object({\n add_to_cart: z.string(),\n added_to_cart: z.string(),\n adding_to_cart: z.string(),\n cart_switch_to_onetime: z.string(),\n cart_switch_to_subscription: z.string(),\n cart_switch_to_subscription_footer: z.string(),\n checkout: z.string(),\n continue: z.string(),\n decline: z.string(),\n delivery_frequency_label: z.string(),\n description: z.string(),\n learn_more_label: z.string(),\n remove_body: z.string(),\n remove_confirm: z.string(),\n remove_deny: z.string(),\n remove_from_cart: z.string(),\n remove_title: z.string(),\n removed_from_cart: z.string(),\n removing_from_cart: z.string(),\n saving_amount_text: z.string(),\n sold_out_label: z.string(),\n super_title: z.string(),\n thank_you_button: z.string(),\n thank_you_description: z.string(),\n thank_you_title: z.string(),\n timer_title: z.string(),\n title: z.string(),\n total_price_label: z.string(),\n upgrade_to_subscription: z.string(),\n variant_option: z.string(),\n variant_options: z.string(),\n});\n\nconst quantityInputsSchema = z.object({\n default_quantity: z.number(),\n enabled: z.boolean(),\n max_value: z.number(),\n min_value: z.number(),\n});\n\nconst stylesSchema = z.object({\n background_color: z.string(),\n border_color: z.string(),\n button_background: z.string(),\n button_border_color: z.string(),\n button_border_width: z.union([z.string(), z.number()]),\n button_radius: z.union([z.string(), z.number()]),\n button_text: z.string(),\n carousel_control_background: z.string(),\n carousel_control_text: z.string(),\n carousel_paging_dots: z.string(),\n compare_price: z.string(),\n custom_css: z.string(),\n description: z.string(),\n input_background: z.string(),\n input_border: z.string(),\n input_text: z.string(),\n price: z.string(),\n product_description: z.string(),\n product_title: z.string(),\n reviews_background: z.string(),\n reviews_foreground: z.string(),\n reviews_text: z.string(),\n sale_price: z.string(),\n supertitle: z.string(),\n title: z.string(),\n});\n\nconst trackingSchema = z.object({\n enable_attribution: z.boolean(),\n enable_product_discovery: z.boolean(),\n enable_source: z.boolean(),\n enable_widget: z.boolean(),\n});\n\nconst callbackSchema = z.object({\n enabled: z.boolean(),\n function: z.string(),\n});\n\nconst callbacksSchema = z.object({\n add: callbackSchema,\n alternativePaymentsRefresh: callbackSchema,\n beforeAdd: callbackSchema,\n beforeChange: callbackSchema,\n beforeDecline: callbackSchema,\n beforeHide: callbackSchema,\n beforeProductsChange: callbackSchema,\n beforeReady: callbackSchema,\n beforeRemove: callbackSchema,\n beforeShow: callbackSchema,\n change: callbackSchema,\n decline: callbackSchema,\n hide: callbackSchema,\n init: callbackSchema,\n productsChange: callbackSchema,\n ready: callbackSchema,\n refresh: callbackSchema,\n remove: callbackSchema,\n selectedVariantChange: callbackSchema,\n shippingRateRefresh: callbackSchema,\n show: callbackSchema,\n view: callbackSchema,\n});\n\nconst shopSchema = z.object({\n currency: z.string(),\n money_format: z.string(),\n myshopify_domain: z.string(),\n});\n\nexport const widgetSettingsSchema = z\n .object({\n advance: z.union([z.array(z.any()), z.object({}).passthrough()]).optional(),\n allow_gifts_without_purchase: z.boolean().optional(),\n allow_remove: z.boolean().optional(),\n breakpoints: breakpointsSchema,\n callbacks: callbacksSchema,\n close_redirect: z.string().optional(),\n decline_redirect: z.string().optional(),\n discount: discountSchema,\n display_type: z.string().optional(),\n endpoint: z.string().min(1),\n exclude_items: excludeItemsSchema,\n hide_quantity_selector: z.boolean().optional(),\n images: imagesSchema,\n integrations: integrationsSchema.optional(),\n key: z.string().optional(),\n language: languageSchema,\n layout: layoutSchema,\n learn_more: z.string().optional(),\n limit: z.number().optional(),\n metafields: z.boolean().optional(),\n placement: placementSchema,\n popup_delay: z.number().optional(),\n popup_trigger: z.string().optional(),\n popup_trigger_selector: z.string().optional(),\n preview_mode: z.boolean().optional(),\n product_options: productOptionsSchema,\n product_type: z.string().optional(),\n quantity_inputs: quantityInputsSchema,\n redirect: z.string().optional(),\n remove_redirect: z.string().optional(),\n shipping: z.union([z.array(z.any()), z.object({}).passthrough()]).optional(),\n shop: shopSchema.optional(),\n show_continue_button: z.boolean().optional(),\n styles: stylesSchema,\n subscription: z.union([z.array(z.any()), z.object({}).passthrough()]).optional(),\n subscription_is_default: z.boolean().optional(),\n theme: z.string().optional(),\n timer: timerSchema,\n tracking: trackingSchema,\n type: z.string().optional(),\n variant_metafields: z.boolean().optional(),\n view_options: viewOptionsSchema,\n })\n .passthrough();\n\nexport const widgetConfigSettingsSchema = z.object({\n config: widgetSettingsSchema,\n});\n\nexport const widgetNestedConfigSettingsSchema = z.object({\n data: z.object({\n config: widgetSettingsSchema,\n }),\n});\n\nexport const widgetConfigUnionSettingsSchema = z.union([widgetConfigSettingsSchema, widgetNestedConfigSettingsSchema]);\n\nexport type WidgetSettings = z.infer<typeof widgetSettingsSchema>;\nexport type WidgetConfig = z.infer<typeof widgetConfigSettingsSchema>;\nexport type WidgetConfigUnionSettings = z.infer<typeof widgetConfigUnionSettingsSchema>;\n\nexport type RebuyWidgetContextType = {\n apiKey?: string;\n cacheKey?: string;\n dataSource: string;\n isHydrogenReact: boolean;\n key: string;\n limit: number;\n metadata: RebuyWidgetMetadata;\n options: Record<string, unknown>;\n product?: HydrogenProduct;\n productId?: string;\n products: RebuyProduct[];\n variant?: RebuyProductVariant;\n variantId?: string;\n};\n\nexport type WidgetChildProps = {\n addToCartCallback?: () => void;\n cacheKey?: string;\n customTitle?: string;\n customTitleLevel?: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';\n customTitleStyle?: React.CSSProperties;\n};\n", "import type { ContextParameters, CustomEndpointQueryParams, RecommendedEndpointQueryParams } from '~/types/rebuyCustom';\n\n// Helper function to filter context parameters\nexport const filterContextForWidgetEndpoints = (\n sourceParams: Readonly<ContextParameters> | undefined | null,\n endpointUrl?: string // Optional endpoint URL\n): Partial<CustomEndpointQueryParams | RecommendedEndpointQueryParams> => {\n if (!sourceParams) {\n return {};\n }\n\n const filtered: Partial<CustomEndpointQueryParams | RecommendedEndpointQueryParams> = {};\n let allowedKeys: string[];\n\n if (endpointUrl === '/api/v1/products/recommended') {\n allowedKeys = [\n 'shopify_product_ids',\n 'shopify_collection_id',\n 'shopify_variant_ids',\n 'metafields',\n 'variant_metafields',\n 'bust_cache',\n 'format',\n 'limit',\n 'any_variant_price_less_than',\n 'any_variant_price_less_than_or_equal_to',\n 'any_variant_price_equal_to',\n 'variant_price_greater_than',\n 'variant_price_greater_than_or_equal_to',\n 'unset_variants',\n 'filter_oos',\n 'context',\n 'country_code',\n ];\n } else {\n // Default to CustomEndpointQueryParams keys for custom data sources or if endpoint is initially unknown\n allowedKeys = [\n 'shopify_product_ids',\n 'shopify_variant_ids',\n 'shopify_customer_id',\n 'cart_subtotal',\n 'cart_line_count',\n 'cart_item_count',\n 'metafields',\n 'variant_metafields',\n 'time',\n 'limit',\n 'url',\n 'format',\n 'country_code',\n ];\n }\n\n for (const key of allowedKeys) {\n if (key === 'cart_item_count' && endpointUrl !== '/api/v1/products/recommended') {\n if (\n Object.prototype.hasOwnProperty.call(sourceParams, 'cart_item_count') &&\n sourceParams.cart_item_count !== undefined\n ) {\n (filtered as Partial<CustomEndpointQueryParams>).cart_item_count = sourceParams.cart_item_count;\n } else if (\n Object.prototype.hasOwnProperty.call(sourceParams, 'cart_count') &&\n sourceParams.cart_count !== undefined\n ) {\n (filtered as Partial<CustomEndpointQueryParams>).cart_item_count = sourceParams.cart_count;\n }\n } else if (Object.prototype.hasOwnProperty.call(sourceParams, key)) {\n const value = (sourceParams as Record<string, unknown>)[key];\n\n if (value !== undefined) {\n (filtered as Record<string, unknown>)[key] = value;\n }\n }\n }\n\n return filtered;\n};\n", "import type { ProductCardSettings } from './types';\n\nexport const defaultProductCardSettings: ProductCardSettings = {\n layoutStyle: 'grid',\n productOptions: {\n hide_out_of_stock_variants: false,\n match_variant: false,\n match_variant_out_of_stock: false,\n show_product_description: 'hide',\n show_subscription_options: 'always',\n show_variant_options: 'always',\n show_variant_title: 'show',\n show_variants_as_products: false,\n variant_display_limit: 'product_limit',\n },\n quantityInput: {\n default_quantity: 1,\n enabled: true,\n max_value: 11,\n min_value: 1,\n },\n settingsDiscount: {\n amount: 0,\n bundle_protection: {\n allowed_removals: 0,\n disable_atc_on_incomplete: false,\n enabled: false,\n },\n discount_protection: {\n enabled: false,\n minimum_items_to_get_discount: 2,\n },\n discounted_by: 'other',\n discounted_from: 'original_price',\n message: '',\n quantity: 1,\n show_saving_amount: false,\n type: 'none',\n },\n variantSelector: 'select',\n};\n", "import { Image } from '@shopify/hydrogen';\nimport { useCallback, useMemo, useState } from 'react';\n\nimport { AddToCartBtn } from '~/components/AddToCartBtn';\nimport { defaultProductCardSettings } from '~/components/ProductCard/defaultSettings';\nimport type { ProductCardProps } from '~/components/ProductCard/types';\nimport { RebuyProductPrice } from '~/components/ProductPrice/ProductPrice';\nimport { QuantityInput } from '~/components/QuantityInput';\nimport { RebuyLink } from '~/components/RebuyLink';\nimport { VariantSelect } from '~/components/VariantSelect';\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport type { RebuyProduct } from '~/types/rebuyCustom';\nimport { Title } from '../Title';\nimport styles from './ProductCard.module.css';\n\ntype ProductInteractionStatus = 'ready' | 'selecting';\n\nexport const ProductCard = ({\n addToCartBtnText,\n addToCartCallback,\n isCrossSell,\n isHydrogenReact,\n isInPopup,\n onPopupDismiss,\n product,\n productCardTitleLevel,\n settings = defaultProductCardSettings,\n variantOptionsText,\n}: ProductCardProps) => {\n const [selectedVariant, setSelectedVariant] = useState(product.variants.nodes[0]);\n const [selectedQuantity, setSelectedQuantity] = useState<number>(settings?.quantityInput?.default_quantity || 1);\n const [interactionStatus, setInteractionStatus] = useState<ProductInteractionStatus>('ready');\n\n const { toggleCart } = useSmartCart();\n\n const displayImage = selectedVariant.image || product.featuredImage;\n\n const handleSelectedVariant = useCallback((product: RebuyProduct, variant_id: string) => {\n const updatedVariant = product.variants.nodes.find((variant) => variant.id === variant_id);\n\n if (updatedVariant) {\n setSelectedVariant(updatedVariant);\n }\n }, []);\n\n const handleSelectedQuantity = useCallback((quantity: number) => {\n setSelectedQuantity(quantity);\n }, []);\n\n const handleLinkClick = useCallback(() => {\n if (isCrossSell) {\n toggleCart();\n }\n\n if (isInPopup && onPopupDismiss) {\n onPopupDismiss();\n }\n }, [isInPopup, onPopupDismiss]);\n\n const cardLayout = settings?.layoutStyle || 'grid';\n const productOptions = settings?.productOptions;\n const showVariantOptionsSetting = productOptions?.show_variant_options || 'always';\n\n const showVariantSelect = useMemo(() => {\n if (product?.variants.nodes.length <= 1) {\n const firstVariantTitle = product.variants.nodes[0]?.title?.toLowerCase();\n\n if (firstVariantTitle === 'default title' || firstVariantTitle === 'default') {\n return false;\n }\n\n return showVariantOptionsSetting === 'always';\n }\n\n switch (showVariantOptionsSetting) {\n case 'always':\n return true;\n case 'never':\n return false;\n case 'dynamic':\n return interactionStatus === 'selecting';\n case 'default':\n default:\n if (cardLayout === 'line') {\n return interactionStatus === 'selecting';\n }\n\n return true;\n }\n }, [product?.variants.nodes, showVariantOptionsSetting, interactionStatus, cardLayout]);\n\n const isSelectionRequiredBeforeAddToCart = useMemo(() => {\n return product?.variants.nodes.length > 1 && !showVariantSelect && interactionStatus === 'ready';\n }, [product?.variants.nodes, showVariantSelect, interactionStatus]);\n\n const atcButtonLabel = useMemo(() => {\n if (isSelectionRequiredBeforeAddToCart) {\n if (product.options && product.options.length === 1) {\n return `${product.options[0].name}`;\n }\n\n return variantOptionsText || 'Options';\n }\n\n return addToCartBtnText || 'Add to Cart';\n }, [isSelectionRequiredBeforeAddToCart, product.options, variantOptionsText, addToCartBtnText]);\n\n const handlePrimaryAction = useCallback(() => {\n if (isSelectionRequiredBeforeAddToCart) {\n setInteractionStatus('selecting');\n } else {\n // If addToCartCallback exists, it will be called by the AddToCartBtn after successful Shopify add\n if (isInPopup) {\n onPopupDismiss?.();\n }\n }\n }, [isSelectionRequiredBeforeAddToCart, isInPopup, onPopupDismiss]);\n\n const showVariantTitle =\n settings?.productOptions?.show_variant_title === 'show' &&\n selectedVariant.title.toLowerCase() !== 'default title';\n const showReviews = product.reviews && product?.reviews?.review_count && product?.reviews?.review_count > 0;\n const productReviewsRating = product.reviews?.star_rating;\n const showProductDescription =\n settings?.productOptions?.show_product_description === 'show' &&\n product.description !== '' &&\n product.description !== null;\n const showQuantityInput =\n settings?.quantityInput?.enabled &&\n settings?.quantityInput?.max_value !== null &&\n settings?.quantityInput?.min_value !== null;\n\n return (\n <div className={styles['rebuy-product-card__container']}>\n <div className={styles['rebuy-product-card']} data-layout={cardLayout}>\n <div>\n <RebuyLink\n ariaLabel={`View ${product.title}`}\n className={styles['rebuy-product-card__media-link']}\n handle={`/products/${product.handle}`}\n onClick={handleLinkClick}\n >\n <Image\n alt={displayImage?.altText ?? `Picture of ${product.title}`}\n className={styles['rebuy-product-card__image']}\n data={displayImage}\n sizes=\"(max-width: 320px) 280px, (max-width: 768px) 720px, 1440px\"\n />\n </RebuyLink>\n\n {settings?.layoutStyle === 'grid' && (\n <div className={styles['rebuy-product-card__content']}>\n <div className={styles['rebuy-product-card__header']}>\n {product.vendor && (\n <p className={styles['rebuy-product-card__vendor']}>{product.vendor}</p>\n )}\n <RebuyLink\n ariaLabel={`View ${product.title}`}\n className={styles['rebuy-product-card__title-link']}\n handle={`/products/${product.handle}`}\n onClick={handleLinkClick}\n >\n <Title\n className={styles['rebuy-product-card__title']}\n level={productCardTitleLevel}\n text={product.title}\n />\n </RebuyLink>\n {showVariantTitle && (\n <div className={styles['rebuy-product-card__variant-title']}>\n {selectedVariant.title}\n </div>\n )}\n </div>\n\n <RebuyProductPrice\n selectedVariant={selectedVariant}\n settingsDiscount={settings?.settingsDiscount}\n />\n\n {showReviews && (\n <div aria-label=\"product star rating\" className={styles['rebuy-product-card__review']}>\n <span className={styles['rebuy-product-card__star-rating']}>\n {productReviewsRating && (\n <span className={styles['rebuy-product-card__star-rating-value']}>\n {productReviewsRating} stars out of 5 stars\n </span>\n )}\n <span className={styles['rebuy-product-card__star-rating-background']}></span>\n <span\n className={styles['rebuy-product-card__star-rating-foreground']}\n style={\n productReviewsRating\n ? { width: (productReviewsRating / 5) * 100 + '%' }\n : {}\n }\n ></span>\n </span>\n {product.reviews?.review_count && (\n <span className={styles['rebuy-product-card__review-count']}>\n ({product.reviews.review_count})\n </span>\n )}\n </div>\n )}\n {showProductDescription && (\n <div className={styles['rebuy-product-card__description']}>\n <p>{product.description}</p>\n </div>\n )}\n </div>\n )}\n </div>\n <div className={styles['rebuy-product-card__info']}>\n {settings?.layoutStyle !== 'grid' && (\n <div className={styles['rebuy-product-card__content']}>\n <div className={styles['rebuy-product-card__header']}>\n {product.vendor && (\n <p className={styles['rebuy-product-card__vendor']}>{product.vendor}</p>\n )}\n <RebuyLink\n ariaLabel={`View ${product.title}`}\n className={styles['rebuy-product-card__title-link']}\n handle={`/products/${product.handle}`}\n onClick={handleLinkClick}\n >\n <Title\n className={styles['rebuy-product-card__title']}\n level={productCardTitleLevel}\n text={product.title}\n />\n </RebuyLink>\n {showVariantTitle && (\n <div className={styles['rebuy-product-card__variant-title']}>\n {selectedVariant.title}\n </div>\n )}\n </div>\n\n <RebuyProductPrice\n selectedVariant={selectedVariant}\n settingsDiscount={settings?.settingsDiscount}\n />\n\n {showReviews && (\n <div aria-label=\"product star rating\" className={styles['rebuy-product-card__review']}>\n <span className={styles['rebuy-product-card__star-rating']}>\n {productReviewsRating && (\n <span className={styles['rebuy-product-card__star-rating-value']}>\n {productReviewsRating} stars out of 5 stars\n </span>\n )}\n <span className={styles['rebuy-product-card__star-rating-background']}></span>\n <span\n className={styles['rebuy-product-card__star-rating-foreground']}\n style={\n productReviewsRating\n ? { width: (productReviewsRating / 5) * 100 + '%' }\n : {}\n }\n ></span>\n </span>\n {product.reviews?.review_count && (\n <span className={styles['rebuy-product-card__review-count']}>\n ({product.reviews.review_count})\n </span>\n )}\n </div>\n )}\n {showProductDescription && (\n <div className={styles['rebuy-product-card__description']}>\n <p>{product.description}</p>\n </div>\n )}\n </div>\n )}\n <div className={styles['rebuy-product-card__actions']}>\n {showVariantSelect && cardLayout !== 'line' && (\n <div\n className={styles['rebuy-product-card__actions-variant-select']}\n data-layout={cardLayout}\n >\n <VariantSelect\n handleSelectedVariant={handleSelectedVariant}\n product={product}\n selectedId={selectedVariant.id}\n style={settings?.variantSelector}\n />\n </div>\n )}\n {showQuantityInput && (\n <div className={styles['rebuy-product-card__actions-quantity']}>\n <QuantityInput\n defaultQuantity={settings?.quantityInput?.default_quantity}\n handleSelectedQuantity={handleSelectedQuantity}\n maxValue={settings?.quantityInput?.max_value}\n minValue={settings?.quantityInput?.min_value}\n />\n </div>\n )}\n <div className={styles['rebuy-product-card__actions-button']}>\n <AddToCartBtn\n addToCartBtnText={atcButtonLabel}\n addToCartCallback={addToCartCallback}\n disableShopifyAddAction={isSelectionRequiredBeforeAddToCart}\n isHydrogenReact={isHydrogenReact}\n onClickAction={isSelectionRequiredBeforeAddToCart ? handlePrimaryAction : undefined}\n quantity={selectedQuantity}\n selectedVariants={isSelectionRequiredBeforeAddToCart ? [] : [selectedVariant]}\n />\n </div>\n </div>\n </div>\n </div>\n {showVariantSelect && cardLayout === 'line' && (\n <div className={styles['rebuy-product-card__variant-select']} data-layout={cardLayout}>\n <VariantSelect\n handleSelectedVariant={handleSelectedVariant}\n product={product}\n selectedId={selectedVariant.id}\n style={settings?.variantSelector}\n />\n </div>\n )}\n </div>\n );\n};\n", "import { CartForm, Money } from '@shopify/hydrogen';\nimport { type FetcherWithComponents } from 'react-router';\n\nimport type { btnProps } from '~/components/AddToCartBtn/types';\nimport styles from './AddToCartBtn.module.css';\n\nexport const HydrogenAddToCartBtn = ({\n addToCartBtnText,\n addToCartCallback,\n disableShopifyAddAction,\n disabled,\n linesToAdd,\n moneyData,\n onClickAction,\n}: btnProps) => {\n const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {\n // First, execute the click action if provided\n if (onClickAction) {\n onClickAction();\n }\n\n // If we should disable the Shopify add action, prevent form submission\n if (disableShopifyAddAction) {\n event.preventDefault();\n\n return;\n }\n\n // Otherwise, let the form submission proceed normally\n // The addToCartCallback will be called after successful submission\n if (addToCartCallback) {\n addToCartCallback();\n }\n };\n\n return (\n <div className={styles['rebuy-cart-button__container']}>\n <CartForm\n action={CartForm.ACTIONS.LinesAdd}\n inputs={{\n lines: linesToAdd,\n }}\n route=\"/cart\"\n >\n {(fetcher: FetcherWithComponents<unknown>) => (\n <>\n <button\n className={styles['rebuy-cart-button']}\n disabled={disabled || fetcher.state !== 'idle'}\n onClick={handleClick}\n type=\"submit\"\n >\n {addToCartBtnText}\n {moneyData && (\n <>\n <span> | </span>\n <Money data={moneyData} withoutTrailingZeros />\n </>\n )}\n </button>\n </>\n )}\n </CartForm>\n </div>\n );\n};\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/components/AddToCartBtn/AddToCartBtn.css\";\n const result = {\"rebuy-cart-button\":\"AddToCartBtn_rebuy-cart-button\",\"rebuy-cart-button__container\":\"AddToCartBtn_rebuy-cart-button__container\"};\n export default result;\n ", "import { Money, useCart } from '@shopify/hydrogen-react';\n\nimport type { btnProps } from '~/components/AddToCartBtn/types';\nimport styles from './AddToCartBtn.module.css';\n\nexport const HydrogenReactAddToCartBtn = ({\n addToCartBtnText,\n addToCartCallback,\n disableShopifyAddAction,\n disabled,\n linesToAdd,\n moneyData,\n onClickAction,\n}: btnProps) => {\n const { linesAdd } = useCart();\n\n const handleAddToCart = () => {\n // First, execute the click action if provided\n if (onClickAction) {\n onClickAction();\n }\n\n // If we should disable the Shopify add action, return early\n if (disableShopifyAddAction) {\n return;\n }\n\n // Otherwise, proceed with adding to cart\n linesAdd(linesToAdd);\n\n // Call the callback after successful add\n if (addToCartCallback) {\n addToCartCallback();\n }\n };\n\n return (\n <button className={styles['rebuy-cart-button']} disabled={disabled} onClick={handleAddToCart} type=\"button\">\n {addToCartBtnText}\n {moneyData && (\n <>\n {/* Consider a BEM element class if this needs specific styling */}\n {/* e.g., styles['rebuy-add-to-cart-btn__separator'] */}\n <span> | </span>\n {/* Consider a BEM element class if this needs specific styling */}\n {/* e.g., styles['rebuy-add-to-cart-btn__price'] */}\n <Money data={moneyData} withoutTrailingZeros />\n </>\n )}\n </button>\n );\n};\n", "import type { AddToCartBtnProps } from '~/components/AddToCartBtn/types';\nimport { HydrogenAddToCartBtn } from './HydrogenAddToCartBtn';\nimport { HydrogenReactAddToCartBtn } from './HydrogenReactAddToCartBtn';\n\nexport const AddToCartBtn = ({\n addToCartBtnText,\n addToCartCallback,\n disableShopifyAddAction,\n disabled,\n isHydrogenReact,\n moneyData,\n onClickAction,\n quantity,\n selectedVariants,\n}: AddToCartBtnProps) => {\n const linesToAdd = selectedVariants.map((variant) => ({\n attributes: [\n { key: '_source', value: 'Rebuy' },\n { key: '_attribution', value: 'Rebuy Product Recommendations' },\n ],\n merchandiseId: variant.id,\n quantity: quantity || 1,\n selectedVariant: variant,\n }));\n\n if (isHydrogenReact) {\n return (\n <HydrogenReactAddToCartBtn\n addToCartBtnText={addToCartBtnText}\n addToCartCallback={addToCartCallback}\n disabled={disabled}\n disableShopifyAddAction={disableShopifyAddAction}\n linesToAdd={linesToAdd}\n moneyData={moneyData}\n onClickAction={onClickAction}\n />\n );\n }\n\n return (\n <HydrogenAddToCartBtn\n addToCartBtnText={addToCartBtnText}\n addToCartCallback={addToCartCallback}\n disabled={disabled}\n disableShopifyAddAction={disableShopifyAddAction}\n linesToAdd={linesToAdd}\n moneyData={moneyData}\n onClickAction={onClickAction}\n />\n );\n};\n", "import { Money } from '@shopify/hydrogen';\nimport type { MoneyV2 } from '@shopify/hydrogen-react/storefront-api-types';\nimport clsx from 'clsx';\nimport type { ProductPriceProps } from './types';\n\nimport styles from './ProductPrice.module.css';\n\n// TODO: Add support for settingsDiscount\nexport const RebuyProductPrice = ({ selectedVariant, settingsDiscount }: ProductPriceProps) => {\n if (!selectedVariant) return null;\n const { compareAtPriceV2: compareAtPrice, priceV2: price } = selectedVariant;\n\n const isDiscounted = (price: MoneyV2 | null, compareAtPrice: MoneyV2 | null) =>\n Number(compareAtPrice?.amount) > Number(price?.amount);\n\n const currentPriceIsOnSale = compareAtPrice && isDiscounted(price, compareAtPrice);\n\n const CompareAtPrice = ({ data: compareAtPriceData }: { data: MoneyV2 | null }) => {\n return (\n compareAtPriceData && (\n <Money\n as=\"span\"\n className={styles['rebuy-product-price__compare-at']}\n data={compareAtPriceData}\n withoutTrailingZeros\n />\n )\n );\n };\n\n return (\n price && (\n <div className={styles['rebuy-product-price']}>\n <Money\n as=\"span\"\n className={clsx(\n styles['rebuy-product-price__current'],\n currentPriceIsOnSale && styles['rebuy-product-price__current--sale']\n )}\n data={price}\n withoutTrailingZeros\n />\n {currentPriceIsOnSale && <CompareAtPrice data={compareAtPrice} />}\n </div>\n )\n );\n};\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/components/ProductPrice/ProductPrice.css\";\n const result = {\"rebuy-product-price\":\"ProductPrice_rebuy-product-price\",\"rebuy-product-price__current\":\"ProductPrice_rebuy-product-price__current\",\"rebuy-product-price__current--sale\":\"ProductPrice_rebuy-product-price__current--sale\",\"rebuy-product-price__compare-at\":\"ProductPrice_rebuy-product-price__compare-at\"};\n export default result;\n ", "import { useState } from 'react';\nimport type { QuantityInputProps } from '~/components/QuantityInput/types';\nimport styles from './QuantityInput.module.css';\n\nexport const QuantityInput = ({\n defaultQuantity = 1,\n handleSelectedQuantity,\n maxValue = 10,\n minValue = 1,\n}: QuantityInputProps) => {\n const [quantity, setQuantity] = useState<number>(defaultQuantity);\n\n const handleChange = (event: React.ChangeEvent<HTMLSelectElement>) => {\n const newValue = parseInt(event.target.value, 10);\n setQuantity(newValue);\n\n // Call the callback with new value\n if (handleSelectedQuantity) {\n handleSelectedQuantity(newValue);\n }\n };\n\n // Generate array of quantity options from minValue to maxValue\n const quantityOptions = Array.from({ length: maxValue - minValue + 1 }, (_, i) => minValue + i);\n\n return (\n <div className={styles['rebuy-quantity__container']}>\n <select\n aria-label=\"Product quantity\"\n className={styles['rebuy-quantity__select']}\n name=\"quantity\"\n onChange={handleChange}\n value={quantity}\n >\n {quantityOptions.map((value) => (\n <option key={`quantity-${value}`} value={value}>\n {value}\n </option>\n ))}\n </select>\n </div>\n );\n};\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/components/QuantityInput/QuantityInput.css\";\n const result = {\"rebuy-quantity__container\":\"QuantityInput_rebuy-quantity__container\",\"rebuy-quantity__select\":\"QuantityInput_rebuy-quantity__select\"};\n export default result;\n ", "import clsx from 'clsx';\nimport { useEffect, useState } from 'react';\nimport type { VariantSelectProps } from '~/components/VariantSelect/types';\nimport styles from './VariantSelect.module.css';\n\nexport const VariantSelect = ({ handleSelectedVariant, product, selectedId, style = 'select' }: VariantSelectProps) => {\n const [selectedVariantId, setSelectedVariantId] = useState(selectedId || product.variants.nodes[0]?.id);\n\n useEffect(() => {\n if (selectedId && selectedId !== selectedVariantId) {\n setSelectedVariantId(selectedId);\n }\n }, [selectedId, selectedVariantId]);\n\n const handleLocalVariantChange = (variantId: string) => {\n setSelectedVariantId(variantId);\n handleSelectedVariant(product, variantId);\n };\n\n if (!product?.variants?.nodes || product.variants.nodes.length <= 1) {\n return null;\n }\n\n return (\n <div className={styles['rebuy-variant__container']}>\n {style === 'select' ? (\n <select\n aria-label=\"Select variant\"\n className={styles['rebuy-variant__select']}\n onChange={(e) => handleLocalVariantChange(e.target.value)}\n value={selectedVariantId}\n >\n {product.variants.nodes.map(({ id, title }) => (\n <option\n className={styles['rebuy-variant__select-option']}\n key={`${id}-variant-option`}\n value={id}\n >\n {title}\n </option>\n ))}\n </select>\n ) : (\n <div className={styles['rebuy-variant__buttons']}>\n {product.variants.nodes.map(({ id, title }) => (\n <button\n aria-pressed={id === selectedVariantId}\n className={clsx(\n styles['rebuy-variant__button'],\n id === selectedVariantId && styles['rebuy-variant__button--selected']\n )}\n key={`${id}-variant-button`}\n onClick={() => handleLocalVariantChange(id)}\n type=\"button\"\n >\n {title}\n </button>\n ))}\n </div>\n )}\n </div>\n );\n};\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/components/VariantSelect/VariantSelect.css\";\n const result = {\"rebuy-variant__container\":\"VariantSelect_rebuy-variant__container\",\"rebuy-variant__select\":\"VariantSelect_rebuy-variant__select\",\"rebuy-variant__select-option\":\"VariantSelect_rebuy-variant__select-option\",\"rebuy-variant__buttons\":\"VariantSelect_rebuy-variant__buttons\",\"rebuy-variant__button\":\"VariantSelect_rebuy-variant__button\",\"rebuy-variant__button--selected\":\"VariantSelect_rebuy-variant__button--selected\"};\n export default result;\n ", "import clsx from 'clsx';\nimport type { TitleProps } from '~/components/Title/types';\nimport styles from './Title.module.css';\n\nexport const Title = ({ className, level, style, text }: TitleProps) => {\n const combinedClassName = clsx(styles['rebuy-title'], className);\n\n switch (level) {\n case 'h1':\n return (\n <h1 className={combinedClassName} style={style}>\n {text}\n </h1>\n );\n default:\n case 'h2':\n return (\n <h2 className={combinedClassName} style={style}>\n {text}\n </h2>\n );\n case 'h3':\n return (\n <h3 className={combinedClassName} style={style}>\n {text}\n </h3>\n );\n case 'h4':\n return (\n <h4 className={combinedClassName} style={style}>\n {text}\n </h4>\n );\n case 'h5':\n return (\n <h5 className={combinedClassName} style={style}>\n {text}\n </h5>\n );\n case 'h6':\n return (\n <h6 className={combinedClassName} style={style}>\n {text}\n </h6>\n );\n }\n};\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/components/Title/Title.css\";\n const result = {\"rebuy-title\":\"Title_rebuy-title\"};\n export default result;\n ", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/components/ProductCard/ProductCard.css\";\n const result = {\"rebuy-product-card__container\":\"ProductCard_rebuy-product-card__container\",\"rebuy-product-card\":\"ProductCard_rebuy-product-card\",\"rebuy-product-card__content\":\"ProductCard_rebuy-product-card__content\",\"rebuy-product-card__header\":\"ProductCard_rebuy-product-card__header\",\"rebuy-product-card__info\":\"ProductCard_rebuy-product-card__info\",\"rebuy-product-card__actions\":\"ProductCard_rebuy-product-card__actions\",\"rebuy-product-card__media-link\":\"ProductCard_rebuy-product-card__media-link\",\"rebuy-product-card__image\":\"ProductCard_rebuy-product-card__image\",\"rebuy-product-card__title\":\"ProductCard_rebuy-product-card__title\",\"rebuy-product-card__title-link\":\"ProductCard_rebuy-product-card__title-link\",\"rebuy-product-card__actions-variant-select\":\"ProductCard_rebuy-product-card__actions-variant-select\",\"rebuy-product-card__variant-select\":\"ProductCard_rebuy-product-card__variant-select\",\"rebuy-product-card__actions-quantity\":\"ProductCard_rebuy-product-card__actions-quantity\",\"rebuy-product-card__actions-button\":\"ProductCard_rebuy-product-card__actions-button\",\"rebuy-product-card__vendor\":\"ProductCard_rebuy-product-card__vendor\",\"rebuy-product-card__variant-title\":\"ProductCard_rebuy-product-card__variant-title\",\"rebuy-product-card__review\":\"ProductCard_rebuy-product-card__review\",\"rebuy-product-card__star-rating\":\"ProductCard_rebuy-product-card__star-rating\",\"rebuy-product-card__star-rating-value\":\"ProductCard_rebuy-product-card__star-rating-value\",\"rebuy-product-card__star-rating-background\":\"ProductCard_rebuy-product-card__star-rating-background\",\"rebuy-product-card__star-rating-foreground\":\"ProductCard_rebuy-product-card__star-rating-foreground\",\"rebuy-product-card__review-count\":\"ProductCard_rebuy-product-card__review-count\",\"rebuy-product-card__review-count-parenthesis\":\"ProductCard_rebuy-product-card__review-count-parenthesis\",\"rebuy-product-card__review-count-number\":\"ProductCard_rebuy-product-card__review-count-number\",\"rebuy-product-card__review-count-label\":\"ProductCard_rebuy-product-card__review-count-label\",\"rebuy-product-card__description\":\"ProductCard_rebuy-product-card__description\"};\n export default result;\n ", "import { useEffect, useState } from 'react';\nimport { ProductCard } from '~/components/ProductCard';\nimport type { RebuyProduct } from '~/types/rebuyCustom';\nimport type { ProductCarouselProps } from './types';\nimport styles from './ProductCarousel.module.css';\n\nexport const ProductCarousel = ({\n addToCartBtnText,\n addToCartCallback,\n columns,\n isCrossSell,\n isHydrogenReact,\n isInPopup,\n onPopupDismiss,\n productCardTitleLevel,\n products,\n settings,\n showPagination = true,\n variantOptionsText,\n}: ProductCarouselProps) => {\n const [currentSlide, setCurrentSlide] = useState(0);\n const [totalSlides, setTotalSlides] = useState(0);\n const [repeatedProducts, setRepeatedProducts] = useState<RebuyProduct[]>([]);\n\n // Create an array of repeated products to ensure all slides are fully populated\n useEffect(() => {\n if (products.length === 0) {\n setRepeatedProducts([]);\n\n return;\n }\n\n const productsNeeded = Math.ceil(products.length / columns) * columns;\n let repeated: RebuyProduct[] = [...products];\n\n while (repeated.length < productsNeeded) {\n const remaining = productsNeeded - repeated.length;\n repeated = [...repeated, ...products.slice(0, remaining)];\n }\n\n setRepeatedProducts(repeated);\n }, [products, columns]);\n\n // Calculate total number of slides based on repeated products and columns\n useEffect(() => {\n if (repeatedProducts.length && columns) {\n setTotalSlides(Math.ceil(repeatedProducts.length / columns));\n }\n }, [repeatedProducts.length, columns]);\n\n const nextSlide = () => {\n setCurrentSlide((prev) => (prev + 1) % totalSlides);\n };\n\n const prevSlide = () => {\n setCurrentSlide((prev) => (prev - 1 + totalSlides) % totalSlides);\n };\n\n const goToSlide = (slideIndex: number) => {\n setCurrentSlide(slideIndex);\n };\n\n // Group products into slides based on column count\n const slides = [];\n for (let i = 0; i < repeatedProducts.length; i += columns) {\n slides.push(repeatedProducts.slice(i, i + columns));\n }\n\n return (\n <div className={styles['rebuy-carousel']}>\n <div\n className={styles['rebuy-carousel__container']}\n style={{ transform: `translateX(-${currentSlide * 100}%)` }}\n >\n {slides.map((slideProducts, index) => (\n <div className={styles['rebuy-carousel__slide']} key={index}>\n <div className={styles['rebuy-carousel__grid']} data-columns={columns}>\n {slideProducts.map((product, productIndex) => (\n <ProductCard\n addToCartBtnText={addToCartBtnText}\n addToCartCallback={addToCartCallback}\n isCrossSell={isCrossSell}\n isHydrogenReact={isHydrogenReact}\n isInPopup={isInPopup}\n key={`${product.id}-${index}-${productIndex}`}\n onPopupDismiss={onPopupDismiss}\n product={product}\n productCardTitleLevel={productCardTitleLevel}\n settings={settings}\n variantOptionsText={variantOptionsText}\n />\n ))}\n </div>\n </div>\n ))}\n </div>\n\n {totalSlides > 1 && (\n <div className={styles['rebuy-carousel__controls']}>\n <button className={styles['rebuy-carousel__prev']} onClick={prevSlide} type=\"button\">\n \u2190\n </button>\n <button className={styles['rebuy-carousel__next']} onClick={nextSlide} type=\"button\">\n \u2192\n </button>\n </div>\n )}\n\n {showPagination && totalSlides > 1 && (\n <div className={styles['rebuy-carousel__pagination']}>\n {Array.from({ length: totalSlides }).map((_, index) => (\n <button\n className={styles['rebuy-carousel__dot']}\n data-active={index === currentSlide ? 'true' : 'false'}\n key={index}\n onClick={() => goToSlide(index)}\n type=\"button\"\n />\n ))}\n </div>\n )}\n </div>\n );\n};\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/components/ProductCarousel/ProductCarousel.css\";\n const result = {\"rebuy-carousel\":\"ProductCarousel_rebuy-carousel\",\"rebuy-carousel__container\":\"ProductCarousel_rebuy-carousel__container\",\"rebuy-carousel__slide\":\"ProductCarousel_rebuy-carousel__slide\",\"rebuy-carousel__controls\":\"ProductCarousel_rebuy-carousel__controls\",\"rebuy-carousel__prev\":\"ProductCarousel_rebuy-carousel__prev\",\"rebuy-carousel__next\":\"ProductCarousel_rebuy-carousel__next\",\"rebuy-carousel__pagination\":\"ProductCarousel_rebuy-carousel__pagination\",\"rebuy-carousel__dot\":\"ProductCarousel_rebuy-carousel__dot\",\"rebuy-carousel__grid\":\"ProductCarousel_rebuy-carousel__grid\"};\n export default result;\n ", "import clsx from 'clsx';\nimport { useCallback, useEffect, useState } from 'react';\nimport type { TimerProps } from './types';\n\nimport styles from './Timer.module.css';\n\nexport const Timer = ({\n action,\n cartCount,\n checkoutUrl,\n durationMinutes,\n durationSeconds,\n isPopup = false,\n onDismiss,\n title,\n}: TimerProps) => {\n // Calculate total seconds from minutes and seconds\n const initialTotalSeconds = (durationMinutes || 0) * 60 + (durationSeconds || 0);\n const [totalSeconds, setTotalSeconds] = useState(initialTotalSeconds);\n const [timerActive, setTimerActive] = useState(true);\n\n // Format remaining time into minutes and seconds\n const minutes = Math.floor(totalSeconds / 60);\n const seconds = totalSeconds % 60;\n\n const formattedMinutes = String(minutes).padStart(2, '0');\n const formattedSeconds = String(seconds).padStart(2, '0');\n\n // Handle the action when the timer ends\n const handleTimerEnd = useCallback(() => {\n setTimerActive(false);\n\n switch (action) {\n case 'dismiss':\n if (isPopup && onDismiss) {\n onDismiss();\n }\n break;\n case 'checkout':\n // This check is to verify checkoutUrl exists and cartCount is greater than 0.\n if (checkoutUrl && cartCount && cartCount > 0) {\n window.location.href = checkoutUrl;\n } else {\n console.warn('Timer: No checkout URL available for checkout action');\n\n // Fallback to dismiss if checkout URL is not available and a popup is displayed\n if (isPopup && onDismiss) {\n onDismiss();\n }\n }\n break;\n case 'cart':\n window.location.href = '/cart';\n break;\n case 'stop':\n default:\n break;\n }\n }, [action, checkoutUrl, isPopup, onDismiss]);\n\n useEffect(() => {\n // Only proceed if the timer is active\n if (!timerActive) return;\n\n // Create interval to count down\n const interval = setInterval(() => {\n setTotalSeconds((prevSeconds: number) => {\n // If we're at zero, clear the interval and handle the timer action\n if (prevSeconds <= 0) {\n clearInterval(interval);\n handleTimerEnd();\n\n return 0;\n }\n\n return prevSeconds - 1;\n });\n }, 1000);\n\n // Clean up the interval\n return () => clearInterval(interval);\n }, [timerActive, handleTimerEnd]);\n\n const isUrgent = totalSeconds < 10;\n\n return (\n <div className={styles['rebuy-timer__container']}>\n <p className={styles['rebuy-timer__text']}>\n <span className={styles['rebuy-timer__title']}>{title}</span>\n <span\n className={clsx(styles['rebuy-timer__display'], isUrgent && styles['rebuy-timer__display--urgent'])}\n >\n <span className={styles['rebuy-timer__minutes']}>{formattedMinutes}</span>\n <span className={styles['rebuy-timer__separator']}>:</span>\n <span className={styles['rebuy-timer__seconds']}>{formattedSeconds}</span>\n </span>\n </p>\n </div>\n );\n};\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/components/Timer/Timer.css\";\n const result = {\"rebuy-timer__container\":\"Timer_rebuy-timer__container\",\"rebuy-timer__text\":\"Timer_rebuy-timer__text\",\"rebuy-timer__title\":\"Timer_rebuy-timer__title\",\"rebuy-timer__display\":\"Timer_rebuy-timer__display\",\"rebuy-timer__display--urgent\":\"Timer_rebuy-timer__display--urgent\",\"rebuy-timer__minutes\":\"Timer_rebuy-timer__minutes\",\"rebuy-timer__seconds\":\"Timer_rebuy-timer__seconds\",\"rebuy-timer__separator\":\"Timer_rebuy-timer__separator\"};\n export default result;\n ", "import { ProductCardTitleLevel } from '~/types/common';\n\n// Convert the string header level to enum\nexport const getTitleLevel = (level: string, decreaseLevel: boolean = false): ProductCardTitleLevel => {\n switch (level) {\n case 'h1':\n if (decreaseLevel) {\n return ProductCardTitleLevel.H2;\n }\n\n return ProductCardTitleLevel.H1;\n case 'h2':\n if (decreaseLevel) {\n return ProductCardTitleLevel.H3;\n }\n\n return ProductCardTitleLevel.H2;\n case 'h3':\n if (decreaseLevel) {\n return ProductCardTitleLevel.H4;\n }\n\n return ProductCardTitleLevel.H3;\n case 'h4':\n if (decreaseLevel) {\n return ProductCardTitleLevel.H5;\n }\n\n return ProductCardTitleLevel.H4;\n case 'h5':\n if (decreaseLevel) {\n return ProductCardTitleLevel.H6;\n }\n\n return ProductCardTitleLevel.H5;\n case 'h6':\n if (decreaseLevel) {\n return ProductCardTitleLevel.H6;\n }\n\n return ProductCardTitleLevel.H6;\n default:\n return ProductCardTitleLevel.H2;\n }\n};\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/widgets/RebuyWidget/RebuyWidget.css\";\n const result = {\"rebuy-widget__container\":\"RebuyWidget_rebuy-widget__container\",\"rebuy-widget__popup-overlay\":\"RebuyWidget_rebuy-widget__popup-overlay\",\"rebuy-widget__popup-content\":\"RebuyWidget_rebuy-widget__popup-content\",\"rebuy-widget__content\":\"RebuyWidget_rebuy-widget__content\",\"rebuy-widget__inner-content\":\"RebuyWidget_rebuy-widget__inner-content\",\"rebuy-widget__description\":\"RebuyWidget_rebuy-widget__description\",\"rebuy-widget__modal-close\":\"RebuyWidget_rebuy-widget__modal-close\",\"rebuy-widget__product-grid\":\"RebuyWidget_rebuy-widget__product-grid\"};\n export default result;\n ", "import { ProductCard } from '~/components/ProductCard';\nimport type { ProductCardSettings } from '~/components/ProductCard/types';\nimport { ProductCarousel } from '~/components/ProductCarousel';\nimport { Timer } from '~/components/Timer';\nimport { Title } from '~/components/Title';\nimport { getTitleLevel } from '~/hooks/titleLevel';\nimport { useBreakpoint } from '~/hooks/useBreakpoint';\nimport type { RebuyProduct } from '~/types/rebuyCustom';\nimport type { WidgetContentProps } from '~/widgets/RebuyWidget/types';\nimport styles from './RebuyWidget.module.css';\n\nexport const WidgetContent = ({\n addToCartCallback,\n cartCount,\n checkoutUrl,\n customTitle,\n customTitleLevel,\n customTitleStyle,\n isCrossSell,\n isHydrogenReact,\n isInPopup,\n onDismiss,\n products,\n settings,\n}: WidgetContentProps) => {\n const currentBreakpoint = useBreakpoint(settings);\n const hasTimer =\n settings &&\n settings.timer.enabled &&\n settings.language.timer_title !== '' &&\n (settings.timer.duration_minutes !== null || settings.timer.duration_seconds !== null);\n const hasSuperTitle = settings?.language.super_title !== '';\n\n // Use customTitle if provided, otherwise use settings title\n const primaryTitle = customTitle || settings?.language.title || '';\n const hasPrimaryTitle = primaryTitle !== '';\n\n const hasDescription = settings?.language.description !== '';\n\n // Get layout settings based on current breakpoint\n const layoutSettings = settings?.layout?.[currentBreakpoint];\n const isCarousel = layoutSettings?.carousel || false;\n const columns = layoutSettings?.columns || 1;\n const showPagination = layoutSettings?.show_paginations || false;\n\n const productCardSettings: ProductCardSettings = {\n layoutStyle: layoutSettings?.style,\n productOptions: settings?.product_options\n ? {\n ...settings.product_options,\n // Ensure match_variant_out_of_stock is always provided since ProductCardSettings requires it\n match_variant_out_of_stock: settings.product_options.match_variant_out_of_stock ?? false,\n }\n : undefined,\n quantityInput: settings?.quantity_inputs,\n settingsDiscount: settings?.discount\n ? {\n amount:\n typeof settings.discount.amount === 'number'\n ? settings.discount.amount\n : parseFloat(settings.discount.amount) || 0,\n bundle_protection: settings.discount.bundle_protection || {\n allowed_removals: 0,\n disable_atc_on_incomplete: false,\n enabled: false,\n },\n discount_protection: settings.discount.discount_protection || {\n enabled: false,\n minimum_items_to_get_discount: 0,\n },\n discounted_by: settings.discount.discounted_by || settings.discount.discountedBy || '',\n discounted_from: settings.discount.discounted_from || settings.discount.discountedFrom || '',\n message: settings.discount.message || '',\n quantity: settings.discount.quantity || 0,\n show_saving_amount:\n settings.discount.show_saving_amount || settings.discount.showSavingAmount || false,\n type: settings.discount.type,\n }\n : undefined,\n variantSelector: settings?.view_options.variant_selector,\n };\n\n // Determine the correct title level for product cards\n const productCardTitleLevel = hasSuperTitle\n ? getTitleLevel(getTitleLevel(customTitleLevel, true), true)\n : getTitleLevel(customTitleLevel, true);\n\n // Render product listing based on layout style and carousel settings\n const renderProducts = () => {\n if (!products || products.length === 0) {\n return null;\n }\n\n if (isCarousel) {\n return (\n <ProductCarousel\n addToCartBtnText={settings?.language.add_to_cart}\n addToCartCallback={addToCartCallback}\n columns={columns}\n isCrossSell={isCrossSell}\n isHydrogenReact={isHydrogenReact}\n isInPopup={isInPopup}\n onPopupDismiss={onDismiss}\n productCardTitleLevel={productCardTitleLevel}\n products={products}\n settings={productCardSettings}\n showPagination={showPagination}\n variantOptionsText={settings?.language.variant_options}\n />\n );\n }\n\n return (\n <div className={styles['rebuy-widget__product-grid']} data-columns={columns} role=\"list\" tabIndex={0}>\n {products.map((product: RebuyProduct) => (\n <div key={product.id}>\n <ProductCard\n addToCartBtnText={settings?.language.add_to_cart}\n addToCartCallback={addToCartCallback}\n isCrossSell={isCrossSell}\n isHydrogenReact={isHydrogenReact}\n isInPopup={isInPopup}\n onPopupDismiss={onDismiss}\n product={product}\n productCardTitleLevel={productCardTitleLevel}\n settings={productCardSettings}\n variantOptionsText={settings?.language.variant_options}\n />\n </div>\n ))}\n </div>\n );\n };\n\n return (\n <div className={styles['rebuy-widget__inner-content']}>\n {hasTimer && (\n <Timer\n action={settings?.timer.action}\n cartCount={cartCount}\n checkoutUrl={checkoutUrl}\n durationMinutes={settings?.timer.duration_minutes}\n durationSeconds={settings?.timer.duration_seconds}\n isPopup={settings?.display_type === 'popup'}\n onDismiss={onDismiss}\n title={settings?.language.timer_title}\n />\n )}\n {hasSuperTitle && (\n <Title\n level={getTitleLevel(customTitleLevel)}\n style={{ marginBottom: '0', textAlign: 'center' }}\n text={settings.language.super_title}\n />\n )}\n {hasPrimaryTitle && (\n <Title\n level={getTitleLevel(customTitleLevel, hasSuperTitle ? true : false)}\n style={customTitleStyle || { textAlign: 'center' }}\n text={primaryTitle}\n />\n )}\n {hasDescription && <p className={styles['rebuy-widget__description']}>{settings.language.description}</p>}\n\n {renderProducts()}\n </div>\n );\n};\n", "import type { SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\nimport { RebuyWidget } from '~/widgets/RebuyWidget';\nimport './CrossSell.css';\n\ntype CrossSellProps = {\n componentConfig: Extract<SmartCartComponentConfig, { type: 'cross_sell_widget' }>;\n};\n\nexport const CrossSell = ({ componentConfig }: CrossSellProps) => {\n const widgetId = componentConfig.settings.widget_id;\n\n if (!widgetId) {\n console.warn('[CrossSell] Widget ID is missing from component configuration');\n\n return null;\n }\n\n return (\n <div data-rebuy-component=\"cross-sell-widget\" data-rebuy-component-id={widgetId}>\n <RebuyWidget isCrossSell widgetId={widgetId} />\n </div>\n );\n};\n", "// src/onsite/js/modules/SmartCartReact/components/CustomCode/CustomCodeBlock.tsx\nimport React, { useEffect, useMemo, useRef } from 'react';\nimport { DebugKey } from '~/constants/debug';\n\nimport type { SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\nimport { executeScriptsInContainer } from '~/smart-cart/utils/executeScriptsInContainer';\n\n/* eslint-disable-next-line no-restricted-imports */\n\ntype CustomCodeBlockProps = {\n /** The specific configuration object for this Custom Code Block instance. */\n componentConfig: Extract<SmartCartComponentConfig, { type: 'custom_code_block' }>;\n};\n\n/**\n * Renders arbitrary HTML and executes *all* associated <script> tags provided\n * in the component's configuration. Mirrors the legacy CustomCode feature but\n * supports multiple scripts within one block.\n *\n * ! WARNING: This component uses `dangerouslySetInnerHTML` and a script execution\n * ! helper to run user-provided code. This approach avoids `eval()` to comply with\n * ! Content Security Policies (CSP) but still carries risks (e.g., XSS).\n * ! Use with extreme caution and ensure the provided HTML/JS is trusted.\n */\nexport const CustomCodeBlock = React.memo(({ componentConfig }: CustomCodeBlockProps) => {\n const containerRef = useRef<HTMLDivElement>(null);\n const executedCodeRef = useRef<string | null>(null);\n\n const componentId = componentConfig.component_id;\n const htmlCode = useMemo(() => componentConfig.settings?.html_code ?? null, [componentConfig.settings?.html_code]);\n\n useEffect(() => {\n const container = containerRef.current;\n\n if (htmlCode && container && executedCodeRef.current !== htmlCode) {\n // Use setTimeout to defer execution until after the current render cycle.\n // This gives the browser time to ensure all DOM elements, including the\n // body tag with the nonce, are available to be queried.\n const timerId = setTimeout(() => {\n executeScriptsInContainer(\n container,\n DebugKey.SC_CUSTOM_CODE_BLOCK,\n `Custom Code Block (ID: ${componentId})`\n );\n // Mark the code as executed (fixed React Strict Mode issues)\n executedCodeRef.current = htmlCode;\n }, 0);\n\n // Cleanup the timer if the component unmounts before it fires.\n return () => {\n clearTimeout(timerId);\n };\n } else if (!htmlCode) {\n executedCodeRef.current = null;\n }\n }, [htmlCode, componentId]);\n\n // Render null if no htmlCode is configured.\n if (!htmlCode) {\n return null;\n }\n\n return (\n <div\n dangerouslySetInnerHTML={{ __html: htmlCode }}\n data-rebuy-component=\"custom_code_block\"\n data-rebuy-component-id={componentId}\n data-rebuy-custom-code={componentId} // Legacy-specific attribute\n ref={containerRef}\n />\n );\n});\n\nCustomCodeBlock.displayName = 'CustomCodeBlock';\n", "let cachedNonce: string | null | undefined = undefined;\n\n/**\n * Retrieves the CSP nonce from the DOM.\n * It reads the nonce from the `data-csp-nonce` attribute on the <body> tag,\n * then caches it for all subsequent calls during the page's lifetime.\n * This is the most robust method for client-side access.\n *\n * @returns {string | null} The found nonce, or null if none exists.\n */\nexport const getNonce = (): string | null => {\n if (cachedNonce !== undefined) {\n return cachedNonce;\n }\n\n // Query the body tag for our specific data attribute.\n const bodyElement = document.querySelector('body[data-nonce]');\n cachedNonce = bodyElement ? bodyElement.getAttribute('data-nonce') : null;\n\n return cachedNonce;\n};\n", "import type { DebugKey } from '~/constants/debug';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport { getNonce } from '~/utils/nonceManager';\n\n/**\n * Finds all <script> elements within a given container, creates new executable\n * script elements from them, and appends them to the container to trigger execution.\n * This method avoids `eval()` and is designed to work with Content Security Policies\n * that use nonces by attempting to copy a nonce from an existing script on the page.\n *\n * @param {HTMLElement} container The HTML element to search within.\n * @param {DebugKey} debugKey The debug key for logging.\n * @param {string} debugContext A string providing context for log messages (e.g., component ID).\n * @returns {void}\n */\nexport const executeScriptsInContainer = (container: HTMLElement, debugKey: DebugKey, debugContext: string) => {\n rebuyDebugLog.log(debugKey, `[executeScripts] Called for: ${debugContext}`);\n\n // Get the nonce from our reliable, cached source.\n const nonce = getNonce();\n\n rebuyDebugLog.log(debugKey, `[executeScripts] Nonce discovery result:`, {\n hasNonce: !!nonce,\n nonce: nonce ? `${nonce.substring(0, 10)}...` : 'null',\n scriptElementsWithNonce: document.querySelectorAll('script[nonce]').length,\n });\n\n if (nonce) {\n rebuyDebugLog.log(debugKey, `[executeScripts] Using CSP nonce: ${nonce.substring(0, 10)}...`);\n } else {\n rebuyDebugLog.warn(\n debugKey,\n `[executeScripts] Could not find a CSP nonce. Dynamic scripts will likely be blocked by CSP.`\n );\n console.warn(`[Rebuy] Could not find a CSP nonce. Dynamic scripts will likely be blocked by CSP.`);\n }\n\n const scriptElements = container.querySelectorAll('script');\n\n rebuyDebugLog.log(debugKey, `[executeScripts] Script elements found:`, {\n containerHtml: container.innerHTML.substring(0, 200) + '...',\n count: scriptElements.length,\n scriptContents: Array.from(scriptElements).map((el) => ({\n attributes: Array.from(el.attributes)\n .map((attr) => `${attr.name}=\"${attr.value}\"`)\n .join(' '),\n innerHTML: el.innerHTML.substring(0, 100) + '...',\n })),\n });\n\n if (scriptElements.length > 0) {\n rebuyDebugLog.log(debugKey, `Found ${scriptElements.length} script(s) in ${debugContext}. Executing...`);\n\n scriptElements.forEach((scriptElement, index) => {\n rebuyDebugLog.log(debugKey, `[executeScripts] Processing script ${index + 1}/${scriptElements.length}:`, {\n attributes: Array.from(scriptElement.attributes)\n .map((attr) => `${attr.name}=\"${attr.value}\"`)\n .join(' '),\n hasParent: !!scriptElement.parentNode,\n innerHTML: scriptElement.innerHTML.substring(0, 100) + '...',\n });\n\n const newScript = document.createElement('script');\n newScript.innerHTML = scriptElement.innerHTML;\n\n for (const attr of Array.from(scriptElement.attributes)) {\n newScript.setAttribute(attr.name, attr.value);\n }\n\n if (nonce) {\n newScript.setAttribute('nonce', nonce);\n }\n\n try {\n scriptElement.parentNode?.replaceChild(newScript, scriptElement);\n rebuyDebugLog.log(debugKey, `[executeScripts] Successfully replaced script ${index + 1}`);\n } catch (error) {\n console.error(`[Rebuy] Failed to replace script ${index + 1}:`, error);\n }\n });\n\n rebuyDebugLog.log(\n debugKey,\n `[executeScripts] Finished processing all ${scriptElements.length} scripts in ${debugContext}`\n );\n } else {\n rebuyDebugLog.log(debugKey, `[executeScripts] No script elements found in ${debugContext}`);\n }\n};\n", "// ~/smart-cart/components/DiscountCodeInput/DiscountCodeInput.tsx\nimport type { CartUserError, Cart as StorefrontCart } from '@shopify/hydrogen/storefront-api-types';\nimport clsx from 'clsx';\nimport React, { useCallback, useEffect, useMemo, useRef, useState, type FormEvent } from 'react';\nimport { useFetcher } from 'react-router';\n\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport { useDiscountManager } from '~/smart-cart/hooks/useDiscountManager';\nimport { formatMoney } from '~/smart-cart/utils/moneyUtils';\nimport type { JsonValue } from '~/types/common';\n\n/* eslint-disable-next-line no-restricted-imports */\nimport styles from './DiscountCodeInput.module.css';\n\ntype DiscountCodeInputProps = { componentConfig: { component_id: string } };\n\nexport const DiscountCodeInputComponent = ({ componentConfig }: DiscountCodeInputProps) => {\n const {\n applyDiscountCodes: hrApplyDiscountCodes,\n cartData,\n getItemCount,\n isHydrogenReact,\n isLoading: isGlobalCartLoading,\n } = useSmartCart();\n\n const discountFetcher = useFetcher<{\n cart?: StorefrontCart | null;\n errors?: CartUserError[];\n warnings?: any[]; // eslint-disable-line @typescript-eslint/no-explicit-any\n }>();\n\n const {\n appliedCodes,\n error: discountManagerError,\n prepareApplyCode,\n prepareRemoveCode,\n processActionResult,\n setCurrentError: setDiscountManagerError,\n setIsProcessing: setDiscountManagerIsProcessing,\n settings,\n } = useDiscountManager();\n\n const [inputValue, setInputValue] = useState('');\n const [isInputFocused, setIsInputFocused] = useState(false);\n const [isLocallyProcessing, setIsLocallyProcessing] = useState(false);\n const inputRef = useRef<HTMLInputElement>(null);\n const hasItems = getItemCount() > 0;\n\n const lang = useMemo(\n () => ({\n // applyingLabel: settings?.language?.discount_applying_label ?? 'Applying...',\n buttonLabel: settings?.language?.discount_button_label ?? 'Apply',\n inputLabel: settings?.language?.discount_code_label ?? 'Discount Code',\n }),\n [settings]\n );\n\n const isLoadingCombined = useMemo(() => {\n if (isHydrogenReact) return isGlobalCartLoading || isLocallyProcessing;\n\n return discountFetcher.state !== 'idle' || isLocallyProcessing;\n }, [isHydrogenReact, isGlobalCartLoading, discountFetcher.state, isLocallyProcessing]);\n\n const shouldShowTags = appliedCodes.length > 0;\n const discountTotalAmount = useMemo(() => {\n if (!cartData || !shouldShowTags || !Array.isArray(cartData.discountAllocations)) {\n return 0;\n }\n\n return cartData.discountAllocations\n .filter((alloc) => alloc.__typename === 'CartCodeDiscountAllocation') // Filter out non-code allocations\n .reduce((sum, alloc) => sum + parseFloat(alloc.discountedAmount.amount), 0);\n }, [cartData, shouldShowTags]);\n\n const _formattedDiscountTotal = useMemo(() => {\n if (discountTotalAmount <= 0) return '';\n\n const currencyCode = cartData?.cost?.totalAmount?.currencyCode ?? 'USD';\n\n return `- ${formatMoney(discountTotalAmount, undefined, currencyCode)}`;\n }, [discountTotalAmount, cartData, appliedCodes]);\n\n const handleApply = useCallback(\n (event: FormEvent) => {\n event.preventDefault();\n\n if (!inputValue.trim() || isLoadingCombined) return;\n\n const payloadFromManager = prepareApplyCode(inputValue); // This returns { codes: string[] }\n\n if (!payloadFromManager) return;\n\n setIsLocallyProcessing(true);\n setDiscountManagerIsProcessing(true);\n setDiscountManagerError(null);\n\n if (isHydrogenReact) {\n hrApplyDiscountCodes(payloadFromManager.codes);\n } else {\n discountFetcher.submit(\n {\n action: 'discountCodesUpdate',\n data: { discountCodes: payloadFromManager.codes }, // Key changed from 'codes' to 'discountCodes'\n } as JsonValue,\n {\n action: '/cart',\n encType: 'application/json',\n method: 'POST',\n }\n );\n }\n },\n [\n inputValue,\n isLoadingCombined,\n prepareApplyCode,\n isHydrogenReact,\n hrApplyDiscountCodes,\n discountFetcher,\n setDiscountManagerIsProcessing,\n setDiscountManagerError,\n ]\n );\n\n const handleRemove = useCallback(\n (code: string) => {\n if (isLoadingCombined) return;\n\n const payloadFromManager = prepareRemoveCode(code);\n setIsLocallyProcessing(true);\n setDiscountManagerIsProcessing(true);\n setDiscountManagerError(null);\n\n if (isHydrogenReact) {\n hrApplyDiscountCodes(payloadFromManager.codes);\n } else {\n discountFetcher.submit(\n {\n action: 'discountCodesUpdate',\n data: { discountCodes: payloadFromManager.codes },\n } as JsonValue,\n {\n action: '/cart',\n encType: 'application/json',\n method: 'POST',\n }\n );\n }\n },\n [\n isLoadingCombined,\n prepareRemoveCode,\n isHydrogenReact,\n hrApplyDiscountCodes,\n discountFetcher,\n setDiscountManagerIsProcessing,\n setDiscountManagerError,\n ]\n );\n\n // Effect to handle results and reset loading states\n useEffect(() => {\n if (isHydrogenReact) {\n if (!isGlobalCartLoading && isLocallyProcessing) {\n setIsLocallyProcessing(false);\n setDiscountManagerIsProcessing(false);\n\n if (cartData && inputValue) {\n const attemptedCode = inputValue.trim().toUpperCase();\n const found = cartData.discountCodes?.find(\n (dc) => dc.code.toUpperCase() === attemptedCode && dc.applicable\n );\n\n if (!found && cartData.discountCodes?.some((dc) => dc.code.toUpperCase() === attemptedCode)) {\n processActionResult(cartData, attemptedCode);\n } else if (\n cartData.discountCodes?.some((dc) => dc.code.toUpperCase() === attemptedCode && dc.applicable)\n ) {\n setInputValue('');\n }\n }\n }\n } else {\n if (discountFetcher.state === 'idle' && isLocallyProcessing) {\n setIsLocallyProcessing(false);\n setDiscountManagerIsProcessing(false);\n const fetcherData = discountFetcher.data;\n\n if (fetcherData?.errors?.length) {\n setDiscountManagerError(fetcherData.errors[0]?.message || 'Failed to apply discount.');\n } else if (fetcherData?.cart) {\n processActionResult(fetcherData.cart, inputValue.trim());\n\n if (!discountManagerError) {\n setInputValue('');\n }\n } else {\n if (!discountManagerError) {\n setInputValue('');\n }\n }\n }\n }\n }, [\n isHydrogenReact,\n isGlobalCartLoading,\n discountFetcher.state,\n discountFetcher.data,\n isLocallyProcessing,\n setDiscountManagerIsProcessing,\n processActionResult,\n inputValue,\n setDiscountManagerError,\n discountManagerError,\n cartData,\n ]);\n\n if (!hasItems) return null;\n\n return (\n <div\n className={styles['rebuy-discount-code-input']}\n data-rebuy-component=\"discount-input\"\n data-rebuy-component-id={componentConfig.component_id}\n >\n <form className={styles['rebuy-discount-code-input__form']} onSubmit={handleApply}>\n <div\n className={clsx(styles['rebuy-discount-code-input__input-wrapper'], {\n [styles['rebuy-discount-code-input__input-wrapper--show-label']]:\n !!inputValue || isInputFocused,\n })}\n >\n <input\n aria-label={lang.inputLabel}\n autoCapitalize=\"characters\"\n autoComplete=\"off\"\n className={styles['rebuy-discount-code-input__input-field']}\n disabled={isLoadingCombined}\n id={`rebuy-discount-input-${componentConfig.component_id}`}\n onBlur={() => setIsInputFocused(false)}\n onChange={(e) => {\n setInputValue(e.target.value);\n setDiscountManagerError(null);\n }}\n onFocus={() => setIsInputFocused(true)}\n placeholder={lang.inputLabel}\n ref={inputRef}\n type=\"text\"\n value={inputValue}\n />\n <label\n className={styles['rebuy-discount-code-input__input-label']}\n htmlFor={`rebuy-discount-input-${componentConfig.component_id}`}\n >\n {lang.inputLabel}\n </label>\n </div>\n <button\n className={styles['rebuy-discount-code-input__apply-button']}\n disabled={isLoadingCombined || !inputValue.trim()}\n type=\"submit\"\n >\n {/* {isLoadingCombined && isLocallyProcessing ? lang.applyingLabel : lang.buttonLabel} */}\n {lang.buttonLabel}\n </button>\n </form>\n\n {discountManagerError && (\n <div className={styles['rebuy-discount-code-input__error-message']}>{discountManagerError}</div>\n )}\n\n {shouldShowTags && (\n <div className={styles['rebuy-discount-code-input__tags-list']}>\n {appliedCodes.map((code) => (\n <div className={styles['rebuy-discount-code-input__tag']} key={code}>\n <span className={styles['rebuy-discount-code-input__tag-icon']}>\n <svg fill=\"currentColor\" height=\"14\" viewBox=\"0 0 24 24\" width=\"14\">\n <path d=\"M21.41 11.58l-9-9C12.05 2.22 11.55 2 11 2H4c-1.1 0-2 .9-2 2v7c0 .55.22 1.05.59 1.42l9 9c.36.36.86.58 1.41.58.55 0 1.05-.22 1.41-.59l7-7c.37-.36.59-.86.59-1.41 0-.55-.23-1.06-.59-1.42zM5.5 7C4.67 7 4 6.33 4 5.5S4.67 4 5.5 4 7 4.67 7 5.5 6.33 7 5.5 7z\" />\n </svg>\n </span>\n <span className={styles['rebuy-discount-code-input__tag-text']}>{code}</span>\n <button\n aria-label={`Remove discount code ${code}`}\n className={styles['rebuy-discount-code-input__tag-remove-button']}\n disabled={isLoadingCombined}\n onClick={() => handleRemove(code)}\n type=\"button\"\n >\n \u2715\n </button>\n </div>\n ))}\n </div>\n )}\n </div>\n );\n};\n\nexport const DiscountCodeInput = React.memo(DiscountCodeInputComponent);\nDiscountCodeInput.displayName = 'DiscountCodeInput';\n", "// ~/smart-cart/hooks/useDiscountManager.ts\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { DebugKey } from '~/constants/debug';\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\n\nexport type ApplyCodesPayload = { codes: string[] };\n\nconst GENERIC_ERROR_CODE_MESSAGE = '{{code}} is not valid for this cart.';\n\n/**\n * Manages discount code state and interactions for the Smart Cart (Storefront API ONLY).\n */\nexport const useDiscountManager = () => {\n const { cartData, error: cartErrorFromCtx, getComponentConfigByType } = useSmartCart();\n\n const [isProcessing, setIsProcessing] = useState(false); // Local processing for this hook\n const [currentError, setCurrentError] = useState<string | null>(null);\n const [appliedCodesState, setAppliedCodesState] = useState<string[]>([]);\n\n const componentConfig = useMemo(() => getComponentConfigByType('discount_code'), [getComponentConfigByType]);\n const settings = useMemo(() => componentConfig?.settings ?? null, [componentConfig]);\n\n useEffect(() => {\n const codesFromApi = cartData?.discountCodes?.filter((dc) => dc.applicable).map((dc) => dc.code) ?? [];\n\n if (JSON.stringify(codesFromApi) !== JSON.stringify(appliedCodesState)) {\n setAppliedCodesState(codesFromApi);\n\n // Don't clear currentError here if it came from a direct failed attempt,\n // only if the cartData sync shows the code is no longer an issue.\n // This needs careful handling based on how errors from H-React vs Fetcher are propagated.\n // For now, let's assume if codesFromApi changes, the previous local error might be stale.\n if (codesFromApi.every((code) => !currentError?.includes(code))) {\n setCurrentError(null);\n }\n rebuyDebugLog.log(DebugKey.SC_DISCOUNT_MANAGER, 'Synced codes from API cart:', codesFromApi);\n }\n }, [cartData?.discountCodes, appliedCodesState, currentError]);\n\n // Prioritize local error from an operation, then context error.\n const errorToDisplay = currentError ?? cartErrorFromCtx;\n\n const prepareApplyCode = useCallback(\n (code: string): ApplyCodesPayload | null => {\n if (!code) return null;\n const codeUpper = code.trim().toUpperCase();\n // Optimistically include it for the payload, server will validate\n const codesToApply = [...new Set([...appliedCodesState, codeUpper])];\n\n return { codes: codesToApply };\n },\n [appliedCodesState]\n );\n\n const prepareRemoveCode = useCallback(\n (codeToRemove: string): ApplyCodesPayload => {\n const codeUpper = codeToRemove.trim().toUpperCase();\n const codesToKeep = appliedCodesState.filter((c) => c.toUpperCase() !== codeUpper);\n\n return { codes: codesToKeep };\n },\n [appliedCodesState]\n );\n\n const prepareRemoveAllCodes = useCallback((): ApplyCodesPayload => {\n return { codes: [] };\n }, []);\n\n // This function is now for the component to call after a fetcher/H-React action\n // to interpret the result if it's not directly reflected in cartData yet.\n // For Remix, this might be called with fetcher.data.\n // For H-React, this might be less necessary if cartData updates promptly.\n const processActionResult = (resultCart: typeof cartData | null | undefined, attemptedCode?: string) => {\n if (!resultCart && attemptedCode) {\n const errorMsg = GENERIC_ERROR_CODE_MESSAGE.replace('{{code}}', attemptedCode.toUpperCase());\n setCurrentError(errorMsg);\n\n return;\n }\n\n if (attemptedCode && resultCart?.discountCodes) {\n const applied = resultCart.discountCodes.find(\n (dc) => dc.code.toUpperCase() === attemptedCode.toUpperCase() && dc.applicable\n );\n\n if (!applied) {\n const errorMsg = GENERIC_ERROR_CODE_MESSAGE.replace('{{code}}', attemptedCode.toUpperCase());\n setCurrentError(errorMsg);\n } else {\n setCurrentError(null); // Code was applied successfully\n }\n } else if (!attemptedCode) {\n // For removeAll or successful remove single\n setCurrentError(null);\n }\n // appliedCodesState will be updated by the useEffect watching cartData.discountCodes\n };\n\n return {\n appliedCodes: appliedCodesState,\n error: errorToDisplay,\n isProcessing, // This state will be set by the consuming component\n prepareApplyCode,\n prepareRemoveAllCodes,\n prepareRemoveCode,\n processActionResult, // For component to report results\n setCurrentError, // Allow component to set this directly too\n setIsProcessing, // Allow component to set this\n settings,\n };\n};\n\nexport type UseDiscountManagerReturn = ReturnType<typeof useDiscountManager>;\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/smart-cart/components/DiscountCodeInput/DiscountCodeInput.css\";\n const result = {\"rebuy-discount-code-input\":\"DiscountCodeInput_rebuy-discount-code-input\",\"rebuy-discount-code-input__form\":\"DiscountCodeInput_rebuy-discount-code-input__form\",\"rebuy-discount-code-input__input-wrapper\":\"DiscountCodeInput_rebuy-discount-code-input__input-wrapper\",\"rebuy-discount-code-input__input-label\":\"DiscountCodeInput_rebuy-discount-code-input__input-label\",\"rebuy-discount-code-input__input-wrapper--show-label\":\"DiscountCodeInput_rebuy-discount-code-input__input-wrapper--show-label\",\"rebuy-discount-code-input__input-field\":\"DiscountCodeInput_rebuy-discount-code-input__input-field\",\"rebuy-discount-code-input__apply-button\":\"DiscountCodeInput_rebuy-discount-code-input__apply-button\",\"rebuy-discount-code-input__error-message\":\"DiscountCodeInput_rebuy-discount-code-input__error-message\",\"rebuy-discount-code-input__tags-list\":\"DiscountCodeInput_rebuy-discount-code-input__tags-list\",\"rebuy-discount-code-input__tag\":\"DiscountCodeInput_rebuy-discount-code-input__tag\",\"rebuy-discount-code-input__tag-icon\":\"DiscountCodeInput_rebuy-discount-code-input__tag-icon\",\"rebuy-discount-code-input__tag-text\":\"DiscountCodeInput_rebuy-discount-code-input__tag-text\",\"rebuy-discount-code-input__tag-remove-button\":\"DiscountCodeInput_rebuy-discount-code-input__tag-remove-button\",\"rebuy-discount-code-input__total-discount-amount\":\"DiscountCodeInput_rebuy-discount-code-input__total-discount-amount\"};\n export default result;\n ", "// ~/smart-cart/components/LoginButton/LoginButton.tsx\nimport React from 'react';\n\nimport { RebuyLink } from '~/components/RebuyLink';\nimport { DebugKey } from '~/constants/debug';\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\n\n/* eslint-disable-next-line no-restricted-imports */\nimport styles from './LoginButton.module.css';\n\nexport const LoginButton = React.memo(() => {\n const { cartData, getComponentConfigByType } = useSmartCart();\n const componentConfig = getComponentConfigByType('login');\n\n const isLoggedInViaApi = !!cartData?.buyerIdentity?.customer?.id;\n\n rebuyDebugLog.log(DebugKey.SC_LOGIN_BUTTON, 'Login status', {\n buyerIdentity: cartData?.buyerIdentity,\n isLoggedInViaApi,\n });\n\n if (isLoggedInViaApi || !componentConfig) {\n return null;\n }\n\n const loginLabel = componentConfig?.settings?.language?.title ?? 'Login';\n const loginUrl = componentConfig?.settings?.url ?? '/account/login';\n\n return (\n <RebuyLink\n ariaLabel={loginLabel}\n className={styles['rebuy-login-button']}\n data-rebuy-component=\"login\"\n data-rebuy-component-id={componentConfig.component_id ?? 'login'}\n handle={loginUrl}\n >\n {loginLabel}\n </RebuyLink>\n );\n});\nLoginButton.displayName = 'LoginButton';\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/smart-cart/components/LoginButton/LoginButton.css\";\n const result = {\"rebuy-login-button\":\"LoginButton_rebuy-login-button\"};\n export default result;\n ", "// src/onsite/js/modules/SmartCartReact/components/SmartCartApp/SmartCartApp.tsx\nimport React, { useEffect, useMemo, useRef } from 'react';\nimport { DebugKey } from '~/constants/debug';\n\nimport { useSmartCartApps } from '~/smart-cart/hooks/useSmartCartApps';\nimport type { EnabledSmartCartApp } from '~/smart-cart/types/smart-cart-app';\nimport type { SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport { executeScriptsInContainer } from '~/smart-cart/utils/executeScriptsInContainer';\n\ntype SmartCartAppProps = {\n /** The specific configuration object for this Smart Cart App instance. */\n componentConfig: Extract<SmartCartComponentConfig, { type: 'smart_cart_app' }>;\n};\n\n/**\n * Renders a container for a specific Smart Cart App, fetching its content\n * and executing its scripts via the useSmartCartApps hook.\n *\n * ! WARNING: This component uses `dangerouslySetInnerHTML` and a script execution\n * ! helper to run code fetched from an API. This approach avoids `eval()` to comply\n * ! with Content Security Policies (CSP) but still carries risks (e.g., XSS).\n * ! Use with caution.\n */\nexport const SmartCartApp = React.memo(({ componentConfig }: SmartCartAppProps) => {\n const containerRef = useRef<HTMLDivElement>(null);\n const executedScriptRef = useRef<string | null>(null);\n\n const { enrichedApps, error: appsHookError, isLoading: appsLoading } = useSmartCartApps();\n\n const componentId = componentConfig.component_id;\n const appId = useMemo(\n () => (componentConfig.settings?.app_id ? Number(componentConfig.settings.app_id) : null),\n [componentConfig.settings?.app_id]\n );\n\n const appData = appId !== null ? enrichedApps.get(appId) : null;\n const enabledAppData = appData?.enabled ? (appData as EnabledSmartCartApp) : null;\n const scriptContent = enabledAppData?.script ?? null;\n\n useEffect(() => {\n const container = containerRef.current;\n\n if (container && scriptContent && executedScriptRef.current !== scriptContent) {\n // Use setTimeout to defer execution until after the current render cycle.\n // This gives the browser time to ensure all DOM elements, including the\n // body tag with the nonce, are available to be queried.\n const timerId = setTimeout(() => {\n executeScriptsInContainer(\n container,\n DebugKey.SC_PARTNER_APPS,\n `Smart Cart App (ID: ${componentId}, App ID: ${appId})`\n );\n // Mark as executed AFTER the script has run (fixed React Strict Mode issues)\n executedScriptRef.current = scriptContent;\n }, 0);\n\n // Cleanup the timer if the component unmounts before it fires.\n return () => {\n clearTimeout(timerId);\n };\n } else if (!scriptContent && executedScriptRef.current !== null) {\n executedScriptRef.current = null;\n }\n }, [scriptContent, appId, componentId]);\n // --- Conditional Rendering Logic (After Hooks) ---\n\n // 1. Handle Loading state from the hook\n if (appsLoading) {\n return <div data-rebuy-component-id={componentId}>Loading App ({appId ?? 'N/A'})...</div>;\n }\n\n // 2. Handle Error state from the hook (fatal error during fetch/processing)\n if (appsHookError) {\n console.error(`[SmartCartApp - ${componentId}] Hook error prevented app rendering: ${appsHookError}`);\n\n return <div data-rebuy-component-id={componentId}>Error loading app data.</div>;\n }\n\n // 3. Handle Missing Config/ID\n if (appId === null) {\n console.warn(`[SmartCartApp - ${componentId}] Missing App ID (settings.app_id) in configuration.`);\n\n return null;\n }\n\n // 4. Handle App Not Available / Disabled / No Content\n if (!enabledAppData || !scriptContent) {\n rebuyDebugLog.log(\n DebugKey.SC_PARTNER_APPS,\n `[SmartCartApp - ${componentId}] App ID ${appId} is not available, disabled, or has no script content.`\n );\n\n return null;\n }\n\n return (\n <div\n dangerouslySetInnerHTML={{ __html: scriptContent }}\n data-rebuy-app-id={appId}\n data-rebuy-component=\"smart_cart_app\"\n data-rebuy-component-id={componentId}\n ref={containerRef}\n />\n );\n});\n\nSmartCartApp.displayName = 'SmartCartApp';\n", "// src/onsite/js/modules/SmartCartReact/hooks/useSmartCartApps.ts\nimport { useEffect, useState } from 'react';\nimport { DebugKey } from '~/constants/debug';\n\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport {\n type DisabledSmartCartApp,\n type EnabledSmartCartApp,\n type EnrichedSmartCartApp,\n type SmartCartAppFromCachedEndpoint,\n type SmartCartAppMerchantConfig,\n smartCartAppFromCachedEndpointSchema,\n} from '~/smart-cart/types/smart-cart-app';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport { safeJsonParse } from '~/smart-cart/utils/safeJsonParse';\n\ntype UseSmartCartAppsResult = {\n enrichedApps: Map<number, EnrichedSmartCartApp>;\n error: string | null;\n isLoading: boolean;\n};\n\n/**\n * Represents the merchant configuration after initial processing within the hook.\n */\ntype ProcessedConfigApp = {\n // Corresponds to partner_app_id from the merchant config data\n enabled: boolean;\n id: number;\n user_inputs?: Record<string, string> | null;\n};\n\n/**\n * Hook to fetch, enrich, and manage Smart Cart App data.\n * Fetches data from the Rebuy `/smart_cart/apps` endpoint based on the\n * configured apps in the Smart Cart settings. Handles variable substitution.\n * Uses Zod to validate individual app data structures from the API.\n *\n * @returns {UseSmartCartAppsResult} Object containing enriched apps, loading state, and any fatal errors\n */\nexport const useSmartCartApps = (): UseSmartCartAppsResult => {\n const { apiKey, cacheKey, config, shopifyDomain } = useSmartCart();\n const [enrichedApps, setEnrichedApps] = useState<Map<number, EnrichedSmartCartApp>>(new Map());\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [error, setError] = useState<string | null>(null);\n\n const initialAppsConfig: SmartCartAppMerchantConfig[] | undefined = config?.apps;\n\n useEffect(() => {\n let isMounted = true;\n\n const fetchAndEnrichApps = async () => {\n // --- 0. Early exit if no apps configured ---\n if (!initialAppsConfig || initialAppsConfig.length === 0) {\n if (isMounted) {\n setEnrichedApps(new Map());\n setIsLoading(false);\n setError(null);\n }\n\n return;\n }\n\n setIsLoading(true);\n setError(null);\n\n // --- 1. Normalize initial config ---\n const processedAppsConfig: ProcessedConfigApp[] = structuredClone(initialAppsConfig).map(\n (app: SmartCartAppMerchantConfig): ProcessedConfigApp => ({\n enabled: app.enabled,\n id: app.partner_app_id,\n user_inputs: app.user_inputs,\n })\n );\n\n const enabledAppIds = processedAppsConfig.filter((app) => app.enabled).map((app) => app.id);\n\n // --- 2. Early exit if no apps are enabled ---\n if (enabledAppIds.length === 0) {\n rebuyDebugLog.log(DebugKey.SC_PARTNER_APPS, '[useSmartCartApps] No enabled apps found in config.');\n\n const disabledAppsMap = new Map<number, EnrichedSmartCartApp>();\n processedAppsConfig.forEach((configApp) => {\n const disabledApp: DisabledSmartCartApp = {\n enabled: false,\n id: configApp.id,\n user_inputs: configApp.user_inputs,\n };\n disabledAppsMap.set(configApp.id, disabledApp);\n });\n\n if (isMounted) {\n setEnrichedApps(disabledAppsMap);\n setIsLoading(false);\n }\n\n return;\n }\n\n // --- 3. Fetch from API ---\n try {\n rebuyDebugLog.log(\n DebugKey.SC_PARTNER_APPS,\n '[useSmartCartApps] Fetching app data for enabled app IDs:',\n enabledAppIds\n );\n\n if (!shopifyDomain || !apiKey || !cacheKey) {\n throw new Error(\n 'Missing required Rebuy configuration (shop domain, API key, or cache key) in SmartCartContext'\n );\n }\n\n const appsUrl = `https://cached.rebuyengine.com/api/v1/smart_cart/apps?shop=${encodeURIComponent(\n shopifyDomain\n )}&key=${encodeURIComponent(apiKey)}&cache_key=${encodeURIComponent(cacheKey)}`;\n\n const response = await fetch(appsUrl);\n\n if (!response.ok) {\n throw new Error(\n `Smart Cart apps API request failed with status ${response.status} for URL: ${appsUrl}`\n );\n }\n\n const rawJson = await response.json();\n\n // --- 4. Validate API Response Structure (Array Check) ---\n if (!Array.isArray(rawJson)) {\n throw new Error('Smart Cart apps API response was not an array.');\n }\n\n // --- 5. Parse & Validate Individual Items with Zod ---\n const validApiAppData: SmartCartAppFromCachedEndpoint[] = [];\n rawJson.forEach((item: unknown, index: number) => {\n const parseResult = smartCartAppFromCachedEndpointSchema.safeParse(item);\n\n if (parseResult.success) {\n validApiAppData.push(parseResult.data);\n } else {\n console.error(\n `[useSmartCartApps] Failed to parse API response item at index ${index}:`,\n parseResult.error.errors,\n 'Raw item:',\n item\n );\n }\n });\n\n if (!isMounted) return;\n\n rebuyDebugLog.groupCollapsed(\n DebugKey.SC_PARTNER_APPS,\n '[useSmartCartApps] API Response Items Passing Validation'\n );\n rebuyDebugLog.log(DebugKey.SC_PARTNER_APPS, validApiAppData);\n rebuyDebugLog.groupEnd();\n\n // --- 6. Enrich and Process (using only validated data) ---\n const newEnrichedApps = new Map<number, EnrichedSmartCartApp>();\n\n processedAppsConfig.forEach((configApp: ProcessedConfigApp) => {\n const apiData = validApiAppData.find((apiApp) => apiApp.id === configApp.id);\n\n if (configApp.enabled && apiData) {\n let scriptWithVars = apiData.script;\n let missingVariables = false;\n\n if (scriptWithVars && apiData.script_variable_json) {\n const variableObject = safeJsonParse<Record<string, string> | null>(\n apiData.script_variable_json\n );\n const userInputs = configApp.user_inputs ?? {};\n\n if (variableObject) {\n Object.keys(variableObject).forEach((variableName) => {\n const inputKey = Object.keys(userInputs).find(\n (key) => key.toLowerCase() === variableName.toLowerCase()\n );\n const variableValue = inputKey ? userInputs[inputKey] : undefined;\n\n if (variableValue !== undefined && variableValue !== null && variableValue !== '') {\n const regex = new RegExp(`\\\\{\\\\{${variableName}\\\\}\\\\}`, 'g');\n scriptWithVars = scriptWithVars!.replace(regex, variableValue);\n } else {\n console.warn(\n `[useSmartCartApps] Missing or empty required variable \"${variableName}\" for App ID ${configApp.id}. Variable definition: ${variableObject[variableName]}`\n );\n missingVariables = true;\n }\n });\n }\n }\n\n if (missingVariables) {\n console.warn(\n `[useSmartCartApps] Disabling App ID ${configApp.id} due to missing variables.`\n );\n\n const disabledApp: DisabledSmartCartApp = {\n enabled: false,\n id: configApp.id,\n user_inputs: configApp.user_inputs,\n };\n newEnrichedApps.set(configApp.id, disabledApp);\n } else {\n const enabledApp: EnabledSmartCartApp = {\n ...apiData,\n enabled: true,\n id: configApp.id,\n script: scriptWithVars,\n user_inputs: configApp.user_inputs,\n };\n newEnrichedApps.set(configApp.id, enabledApp);\n rebuyDebugLog.log(\n DebugKey.SC_PARTNER_APPS,\n `[useSmartCartApps] Successfully processed App ID ${configApp.id}. Enabled: true`\n );\n }\n } else if (configApp.enabled && !apiData) {\n console.warn(\n `[useSmartCartApps] App ID ${configApp.id} enabled in config but not found in validated API response (or failed validation). Disabling.`\n );\n\n const disabledApp: DisabledSmartCartApp = {\n enabled: false,\n id: configApp.id,\n user_inputs: configApp.user_inputs,\n };\n newEnrichedApps.set(configApp.id, disabledApp);\n } else {\n const disabledApp: DisabledSmartCartApp = {\n enabled: false,\n id: configApp.id,\n user_inputs: configApp.user_inputs,\n };\n newEnrichedApps.set(configApp.id, disabledApp);\n }\n });\n\n if (isMounted) {\n setEnrichedApps(newEnrichedApps);\n }\n } catch (err) {\n const message =\n err instanceof Error\n ? err.message\n : 'An unknown error occurred while fetching or processing smart cart apps.';\n console.error('[useSmartCartApps] Fatal Error:', message, err);\n\n if (isMounted) {\n setError(message);\n setEnrichedApps(new Map());\n }\n } finally {\n if (isMounted) {\n setIsLoading(false);\n }\n }\n };\n\n fetchAndEnrichApps();\n\n return () => {\n isMounted = false;\n };\n }, [initialAppsConfig, shopifyDomain, apiKey, cacheKey]);\n\n return { enrichedApps, error, isLoading };\n};\n", "import { z } from 'zod';\n\n/**\n * Smart Cart App shape from the {cached.rebuyengine.com}/api/v1/smart_cart/apps endpoint.\n * Used to enrich the Smart Cart App data for customers on the storefront\n *\n * @see https://bitbucket.org/abovemarket/rebuyengine.com/src/main/application/libraries/Cache/SmartCartApps.php#application/libraries/Cache/SmartCartApps.php-88\n */\nexport const smartCartAppFromCachedEndpointSchema = z.object({\n id: z.number(),\n name: z.string(),\n script: z.string(),\n script_variable_json: z.string().nullable(),\n});\n\n/**\n * Array of Smart Cart Apps fetched from the {cached.rebuyengine.com}/api/v1/smart_cart/apps endpoint.\n */\nexport const smartCartAppsFromCachedEndpointSchema = z.array(smartCartAppFromCachedEndpointSchema);\n\n/**\n * Smart Cart App Merchant Config Schema (stored in the Smart Cart's settings.apps array)\n * Data sampling from the smart_cart_apps DB table.\n *\n * @see https://bitbucket.org/abovemarket/rebuy-core-ci4/src/main/src/Models/SmartCart/SmartCartV2s.php#src/Models/SmartCart/SmartCartV2s.php-111\n */\nexport const smartCartAppMerchantConfigSchema = z.object({\n enabled: z.boolean(),\n partner_app_id: z.number(),\n /** @deprecated - not used for anything in V2 */\n show_in_empty_cart: z.boolean().nullish(),\n user_inputs: z.record(z.string(), z.string()).nullable(),\n});\n\n// Base type for normalized configuration\nexport type NormalizedAppConfig = {\n enabled: boolean;\n id: number;\n user_inputs?: Record<string, string> | null;\n};\n\n// Define the discriminated union for app states\n\n/**\n * Base properties common to all app entries.\n */\nexport type BaseSmartCartApp = {\n id: number;\n user_inputs?: Record<string, string> | null;\n};\n\n/**\n * Type for enabled apps that includes all required API data.\n */\nexport type EnabledSmartCartApp = BaseSmartCartApp &\n z.infer<typeof smartCartAppFromCachedEndpointSchema> & { enabled: true };\n\n/**\n * Type for disabled apps that doesn't require API data.\n */\nexport type DisabledSmartCartApp = BaseSmartCartApp & { enabled: false };\n\n/**\n * Union type for all possible app states.\n * Can be used with type guards: if (app.enabled) { ... }\n */\nexport type EnrichedSmartCartApp = EnabledSmartCartApp | DisabledSmartCartApp;\n\n/**\n * Smart Cart App From Cached Endpoint (cached.rebuyengine.com/api/v1/smart_cart/apps)\n */\nexport type SmartCartAppFromCachedEndpoint = z.infer<typeof smartCartAppFromCachedEndpointSchema>;\n\n/**\n * Smart Cart App Merchant-defined configuration (stored in the Smart Cart's settings.apps array)\n */\nexport type SmartCartAppMerchantConfig = z.infer<typeof smartCartAppMerchantConfigSchema>;\n", "// ~/smart-cart/components/TieredProgressBar/TieredProgressBar.tsx\nimport type { CartLineInput as HRCartLineInput } from '@shopify/hydrogen-react/storefront-api-types';\nimport clsx from 'clsx';\nimport React, { useCallback, useEffect, useMemo, useState } from 'react';\nimport { useFetcher } from 'react-router';\nimport { useShallow } from 'zustand/shallow';\n\nimport { DebugKey } from '~/constants/debug';\nimport {\n calculateVisualProgressBarPercentage,\n checkIsTierReached,\n getGiftAreaTitle,\n getTierFeedbackText,\n getTierIconComponent,\n getTierLabel,\n getTierMinimum,\n shouldRenderGiftArea,\n shouldRenderGiftAreaTitle,\n type TierIconImage,\n} from '~/smart-cart/components/TieredProgressBar/progressBarUtils';\nimport { TieredProgressBarGiftItem as GiftItem } from '~/smart-cart/components/TieredProgressBar/TPBGiftItem';\nimport {\n TieredProgressBarGiftStatus as GiftStatus,\n TieredProgressBarTierType,\n type TieredProgressBarQualifiedGiftState,\n type TieredProgressBarTier,\n} from '~/smart-cart/components/TieredProgressBar/types';\nimport { useSmartCart } from '~/smart-cart/context/SmartCartContext';\nimport {\n useTieredProgressBarStore,\n type SelectedTieredProgressBarStore,\n type TieredProgressBarStoreState,\n} from '~/smart-cart/store/tieredProgressBarStore'; // eslint-disable-line import/order\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport * as debugStyles from '~/smart-cart/utils/debugStyles';\nimport { formatMoney } from '~/smart-cart/utils/moneyUtils';\n\n// eslint-disable-next-line no-restricted-imports\nimport type { JsonValue } from '~/types/common';\nimport styles from './TieredProgressBar.module.css';\n\n/**\n * TieredProgressBar component.\n * Displays progress towards different reward tiers (e.g., free shipping, discounts, free products)\n * based on the cart subtotal. It interacts with the `tieredProgressBarStore` for its state\n * and logic, and with `useSmartCart` for cart actions.\n * This component does not take direct props as its configuration is managed via the store,\n * initialized from settings provided in `SmartCartContext`.\n */\nexport const TieredProgressBar: React.FC = React.memo(() => {\n const { hydrogenReactCartActions, isCartBusy, isHydrogenReact } = useSmartCart();\n const tpbUserActionFetcher = useFetcher();\n const [showDebugPanel, setShowDebugPanel] = useState(false);\n const {\n _lastFetchedBarId,\n activeBarConfig,\n cartSyncError,\n currentSubtotal,\n declinedGiftMap,\n fetchedProductMap,\n giftStates,\n hasFreeShippingOnSubscription,\n isCartReady,\n isManuallyDisabled,\n productFetchError,\n productFetchStatus,\n userActionError,\n } = useTieredProgressBarStore(\n useShallow(\n (state: TieredProgressBarStoreState): SelectedTieredProgressBarStore => ({\n _lastFetchedBarId: state._lastFetchedBarId,\n activeBarConfig: state.activeBarConfig,\n cartSyncError: state.cartSyncError,\n cartSyncStatus: state.cartSyncStatus,\n currentSubtotal: state.currentSubtotal,\n declinedGiftMap: state.declinedGiftMap,\n fetchedProductMap: state.fetchedProductMap,\n giftStates: state.giftStates,\n hasFreeShippingOnSubscription: state.hasFreeShippingOnSubscription,\n initializationStatus: state.initializationStatus,\n isCartReady: state.isCartReady,\n isManuallyDisabled: state.isManuallyDisabled,\n productFetchError: state.productFetchError,\n productFetchStatus: state.productFetchStatus,\n userActionError: state.userActionError,\n userActionStatus: state.userActionStatus,\n })\n )\n );\n\n const handleSelectVariantStore = useTieredProgressBarStore((state) => state.handleSelectVariant);\n const handleAddOrReAddGiftStore = useTieredProgressBarStore((state) => state.handleAddOrReAddGift);\n const handleRemoveGiftStore = useTieredProgressBarStore((state) => state.handleRemoveGift);\n const clearUserActionError = useTieredProgressBarStore((state) => state.clearUserActionError);\n const setSubmitFunctions = useTieredProgressBarStore((state) => state.setSubmitFunctions);\n\n const shouldDisableGiftActions = useMemo(() => {\n // Disable if cart is globally busy (covers H-React, TPB gift sync/user actions)\n // OR if TPB is still fetching its own product data.\n return isCartBusy || productFetchStatus === 'loading';\n }, [isCartBusy, productFetchStatus]);\n\n useEffect(() => {\n if (isHydrogenReact) {\n const hReactLinesAdd = hydrogenReactCartActions?.linesAdd;\n const hReactLinesRemove = hydrogenReactCartActions?.linesRemove;\n\n if (hReactLinesAdd && hReactLinesRemove) {\n setSubmitFunctions(hReactLinesAdd, hReactLinesRemove);\n rebuyDebugLog.log(DebugKey.SC_TPB, 'Set H-React submit functions for TPB.');\n } else {\n rebuyDebugLog.warn(\n DebugKey.SC_TPB,\n '[TPB] Hydrogen React cart actions not available. TPB gift actions might fail.'\n );\n // Set dummy functions that log errors to prevent crashes if called\n setSubmitFunctions(\n (items: HRCartLineInput[]) =>\n console.error('[TPB] H-React linesAdd not configured for TPB.', items),\n (ids: string[]) => console.error('[TPB] H-React linesRemove not configured for TPB.', ids)\n );\n }\n } else {\n // Vanilla Hydrogen/Remix path\n const addItemsRemix = (items: HRCartLineInput[]) => {\n const plainItems = items.map((item) => ({\n attributes: item.attributes?.map((attr) => ({ key: attr.key, value: attr.value })),\n merchandiseId: item.merchandiseId,\n quantity: item.quantity,\n }));\n tpbUserActionFetcher.submit({ action: 'cartLinesAdd', data: { lines: plainItems } } as JsonValue, {\n action: '/cart',\n encType: 'application/json',\n method: 'POST',\n });\n };\n const removeItemsRemix = (lineIds: string[]) => {\n tpbUserActionFetcher.submit({ action: 'cartLinesRemove', data: { lineIds } } as JsonValue, {\n action: '/cart',\n encType: 'application/json',\n method: 'POST',\n });\n };\n setSubmitFunctions(addItemsRemix, removeItemsRemix);\n rebuyDebugLog.log(DebugKey.SC_TPB, 'Set Remix fetcher submit functions for TPB.');\n }\n }, [isHydrogenReact, hydrogenReactCartActions, tpbUserActionFetcher, setSubmitFunctions]);\n\n useEffect(() => {\n if (userActionError) {\n const timer = setTimeout(() => clearUserActionError(), 5_000);\n\n return () => clearTimeout(timer);\n }\n }, [userActionError, clearUserActionError]);\n\n const { amountToNextTier, currentTier, lastReachedTier, realPercentageComplete, visualPercentageComplete } =\n useMemo(() => {\n let calculatedAmountToNextTier = 0,\n calculatedCurrentTier: TieredProgressBarTier | null = null,\n calculatedLastReachedTier: TieredProgressBarTier | null = null,\n calculatedRealPercentageComplete = 0;\n\n if (activeBarConfig && activeBarConfig.tiers.length > 0 && isCartReady) {\n const allTiers = activeBarConfig.tiers;\n const reachedTiers = allTiers.filter((t) =>\n checkIsTierReached(t, currentSubtotal, hasFreeShippingOnSubscription)\n );\n calculatedLastReachedTier = reachedTiers[reachedTiers.length - 1] ?? null;\n calculatedCurrentTier =\n allTiers.find((t) => !checkIsTierReached(t, currentSubtotal, hasFreeShippingOnSubscription)) ??\n null;\n calculatedAmountToNextTier = calculatedCurrentTier\n ? Math.max(0, getTierMinimum(calculatedCurrentTier) - currentSubtotal)\n : 0;\n\n // \"Real\" Percentage calculation (for ARIA and internal data)\n const numericTiers = allTiers.filter((t) => t.type !== TieredProgressBarTierType.DECORATIVE);\n const highestMinimum = Math.max(0, ...numericTiers.map(getTierMinimum));\n calculatedRealPercentageComplete =\n highestMinimum <= 0\n ? currentSubtotal > 0\n ? 100\n : 0\n : currentSubtotal >= highestMinimum\n ? 100\n : currentSubtotal <= 0\n ? 0\n : (currentSubtotal / highestMinimum) * 100;\n calculatedRealPercentageComplete = Math.max(0, Math.min(100, calculatedRealPercentageComplete));\n }\n\n // \"Visual\" Percentage calculation (for UI display)\n const calculatedVisualPercentageComplete = calculateVisualProgressBarPercentage(\n activeBarConfig,\n currentSubtotal,\n hasFreeShippingOnSubscription\n );\n\n return {\n amountToNextTier: calculatedAmountToNextTier,\n currentTier: calculatedCurrentTier,\n lastReachedTier: calculatedLastReachedTier,\n realPercentageComplete: calculatedRealPercentageComplete,\n visualPercentageComplete: calculatedVisualPercentageComplete,\n };\n }, [activeBarConfig, currentSubtotal, hasFreeShippingOnSubscription, isCartReady]);\n\n const giftsForDisplay = useMemo(() => Array.from(giftStates.values()), [giftStates]);\n const feedbackText = useMemo(\n () => getTierFeedbackText(activeBarConfig, currentTier, lastReachedTier, amountToNextTier, fetchedProductMap),\n [activeBarConfig, currentTier, lastReachedTier, amountToNextTier, fetchedProductMap]\n );\n\n const handleVariantSelect = useCallback(\n (tierId: string, variantGid: string) => {\n handleSelectVariantStore(tierId, variantGid);\n },\n [handleSelectVariantStore]\n );\n const handleGiftAddOrReAdd = useCallback(\n (tierId: string) => {\n handleAddOrReAddGiftStore(tierId);\n },\n [handleAddOrReAddGiftStore]\n );\n const handleGiftRemove = useCallback(\n (tierId: string) => {\n handleRemoveGiftStore(tierId);\n },\n [handleRemoveGiftStore]\n );\n\n const lineItemMode = activeBarConfig?.use_line_item_mode ?? false;\n\n const productsToRenderInGiftArea = useMemo(\n () =>\n giftsForDisplay.filter((p: TieredProgressBarQualifiedGiftState) => {\n if (!p.isReached) return false;\n\n if (p.displayStatus === GiftStatus.UNAVAILABLE && !p.error && !p.canReAdd) return false;\n\n if (lineItemMode && p.displayStatus === GiftStatus.ADDED) return false;\n\n if (p.displayStatus === GiftStatus.IDLE && !p.error && !p.isDeclined) return false;\n\n return true;\n }),\n [giftsForDisplay, lineItemMode]\n );\n\n const renderGiftArea = useMemo(\n () => shouldRenderGiftArea(activeBarConfig, productsToRenderInGiftArea.length > 0),\n [activeBarConfig, productsToRenderInGiftArea.length]\n );\n const renderGiftAreaTitle = shouldRenderGiftAreaTitle(activeBarConfig);\n const giftAreaTitle = getGiftAreaTitle(activeBarConfig);\n\n // For loading/error UI related to user actions on TPB:\n const userActionFetcherError = !isHydrogenReact && (tpbUserActionFetcher.data as { error?: string })?.error;\n\n if (userActionFetcherError) {\n console.error('User action fetcher error:', userActionFetcherError);\n }\n\n const isContextLoading = useSmartCart().isLoading;\n\n // If no active bar (disabled, no match, no tiers configured, etc.)\n if (!activeBarConfig || activeBarConfig.tiers.length === 0) {\n return null;\n }\n\n const checkTierReachedCallback = (tier: TieredProgressBarTier | null): boolean => {\n if (!tier) return false;\n\n return checkIsTierReached(tier, currentSubtotal, hasFreeShippingOnSubscription);\n };\n\n const progressBarId = `tpb-main-${activeBarConfig.id}`;\n const feedbackId = `tpb-feedback-text-${activeBarConfig.id}`;\n const giftAreaTitleId = `tpb-giftarea-title-${activeBarConfig.id}`;\n\n return (\n <div className={styles['rebuy-tiered-progress-bar']} data-rebuy-component=\"tiered-progress-bar\">\n <div className={styles['rebuy-tiered-progress-bar__main-progress-area']} id={progressBarId}>\n <div className={styles['rebuy-tiered-progress-bar__tier-markers-list']}>\n {activeBarConfig.tiers.map((tier) => {\n const isReached = checkTierReachedCallback(tier);\n const tierLabel = getTierLabel(tier, fetchedProductMap);\n const iconRenderData = getTierIconComponent(tier, isReached, fetchedProductMap);\n let iconContainerStyle: React.CSSProperties = {};\n const configuredIconSize = tier.product_tier_element_size;\n\n if (configuredIconSize)\n iconContainerStyle = {\n height: configuredIconSize,\n width: configuredIconSize,\n };\n\n let iconElement: React.ReactNode;\n\n if (React.isValidElement(iconRenderData)) iconElement = iconRenderData;\n else if (iconRenderData.type === 'image') {\n const imageObject = iconRenderData as TierIconImage;\n iconElement = (\n <img\n alt={imageObject.alt}\n className={styles['rebuy-tiered-progress-bar__tier-icon-image']}\n src={imageObject.src}\n />\n );\n } else iconElement = null;\n\n return (\n <div\n className={clsx(styles['rebuy-tiered-progress-bar__tier-step'], {\n [styles['rebuy-tiered-progress-bar__tier-step--reached']]: isReached,\n })}\n key={tier.id}\n title={`${tierLabel} (${isReached ? 'Reached' : 'Pending'} at ${formatMoney(getTierMinimum(tier))})`}\n >\n <div\n className={styles['rebuy-tiered-progress-bar__tier-icon-wrapper']}\n style={iconContainerStyle}\n >\n {iconElement}\n </div>\n <div className={styles['rebuy-tiered-progress-bar__tier-label']}>{tierLabel}</div>\n </div>\n );\n })}\n </div>\n <div className={styles['rebuy-tiered-progress-bar__track']}>\n <div\n aria-label=\"Reward progress\"\n aria-labelledby={feedbackId}\n aria-valuemax={100}\n aria-valuemin={0}\n aria-valuenow={Math.round(realPercentageComplete)}\n className={styles['rebuy-tiered-progress-bar__fill']}\n role=\"progressbar\"\n style={{ width: `${visualPercentageComplete}%` }}\n />\n </div>\n </div>\n\n <div aria-live=\"polite\" className={styles['rebuy-tiered-progress-bar__feedback-message']} id={feedbackId}>\n {(isContextLoading || productFetchStatus === 'loading') && !feedbackText\n ? 'Loading rewards...'\n : feedbackText}\n {productFetchError && (\n <div className={styles['rebuy-tiered-progress-bar__error-message']}>\n Could not load reward info.\n {rebuyDebugLog.isKeyActive(DebugKey.SC_TPB) && ` Details: ${productFetchError}`}\n </div>\n )}\n {cartSyncError && (\n <div className={styles['rebuy-tiered-progress-bar__error-message']}>\n Could not update rewards.\n {rebuyDebugLog.isKeyActive(DebugKey.SC_TPB) && ` Details: ${cartSyncError}`}\n </div>\n )}\n {userActionError && (\n <div className={styles['rebuy-tiered-progress-bar__error-message']}>\n Error: {userActionError.message}\n </div>\n )}\n </div>\n\n {renderGiftArea && (\n <div className={styles['rebuy-tiered-progress-bar__gift-area']}>\n {renderGiftAreaTitle && (\n <h3 className={styles['rebuy-tiered-progress-bar__gift-area-title']} id={giftAreaTitleId}>\n {giftAreaTitle}\n </h3>\n )}\n {shouldDisableGiftActions && // If actions are disabled (likely loading something)\n productsToRenderInGiftArea.length === 0 &&\n !productFetchError &&\n !cartSyncError &&\n !userActionError && (\n <div\n style={{\n padding: '10px 0',\n textAlign: 'center',\n }}\n >\n Loading gifts...\n </div>\n )}\n {productsToRenderInGiftArea.length > 0 && (\n <div\n aria-labelledby={renderGiftAreaTitle ? giftAreaTitleId : undefined}\n className={styles['rebuy-tiered-progress-bar__gift-items-list']}\n >\n {productsToRenderInGiftArea.map((productState) => (\n <GiftItem\n isGloballySyncing={shouldDisableGiftActions}\n key={productState.tierId}\n onAddOrReAdd={handleGiftAddOrReAdd}\n onRemove={handleGiftRemove}\n onSelectVariant={handleVariantSelect}\n product={productState}\n />\n ))}\n </div>\n )}\n </div>\n )}\n\n {rebuyDebugLog.isKeyActive(DebugKey.SC_TPB) && (\n <button\n onClick={() => setShowDebugPanel(!showDebugPanel)}\n style={{\n ...debugStyles.toggleButton(),\n display: 'block',\n marginTop: '12px',\n }}\n >\n {showDebugPanel ? 'Hide Debug Panel' : 'Show Debug Panel'}\n </button>\n )}\n\n {rebuyDebugLog.isKeyActive(DebugKey.SC_TPB) && showDebugPanel && (\n <div\n style={{\n ...debugStyles.debugPanel,\n margin: '12px 0',\n maxHeight: '300px',\n maxWidth: 'none',\n width: '100%',\n }}\n >\n <div style={debugStyles.infoText}>\n <strong>Progress Bar Debug Info</strong>\n </div>\n <div style={debugStyles.codeBlock}>\n <div>Subtotal: {formatMoney(currentSubtotal)}</div>\n <div>Visual Progress: {visualPercentageComplete.toFixed(0)}%</div>\n <div>Actual Progress: {realPercentageComplete.toFixed(0)}%</div>\n {amountToNextTier > 0 && <div>To Next Tier: {formatMoney(amountToNextTier)}</div>}\n {currentTier && <div>Current Tier: {getTierLabel(currentTier)}</div>}\n {cartSyncError && <div style={{ color: '#f66' }}>Error: {cartSyncError}</div>}\n </div>\n {giftsForDisplay.length > 0 && (\n <div style={{ marginTop: '8px' }}>\n <div style={debugStyles.infoText}>Gift Status:</div>\n <div style={debugStyles.codeBlock}>\n {giftsForDisplay.map((gift, idx) => (\n <div key={idx} style={{ marginBottom: '4px' }}>\n Tier {gift.tierId}: {gift.displayStatus}\n {gift.isInCart && ' \u2713'}\n </div>\n ))}\n </div>\n </div>\n )}\n </div>\n )}\n </div>\n );\n});\n\nTieredProgressBar.displayName = 'TieredProgressBar';\n", "// ~/smart-cart/components/TieredProgressBar/TieredProgressBar.tsx\nimport clsx from 'clsx';\n\nimport type React from 'react';\nimport { getFreeVariantTitle } from '~/smart-cart/components/TieredProgressBar/progressBarUtils';\nimport {\n TieredProgressBarGiftStatus as GiftStatus,\n type TieredProgressBarQualifiedGiftState,\n} from '~/smart-cart/components/TieredProgressBar/types';\n\nimport { formatMoney } from '~/smart-cart/utils/moneyUtils';\n\n// eslint-disable-next-line no-restricted-imports\nimport styles from './TieredProgressBar.module.css';\n\n// --- Sub-component for rendering individual gift items ---\ntype TieredProgressBarGiftItemProps = {\n isGloballySyncing: boolean;\n onAddOrReAdd: (tierId: string) => void;\n onRemove: (tierId: string) => void;\n onSelectVariant: (tierId: string, variantGid: string) => void;\n product: TieredProgressBarQualifiedGiftState;\n};\n\n/**\n * Renders an individual gift item within the Tiered Progress Bar's gift area.\n * It displays product information, variant selection (if applicable),\n * and action buttons (add/remove/re-add).\n *\n * @param {TieredProgressBarGiftItemProps} props The props for the component.\n *\n * @returns {React.ReactElement} The rendered gift item.\n */\nexport const TieredProgressBarGiftItem: React.FC<TieredProgressBarGiftItemProps> = ({\n isGloballySyncing,\n onAddOrReAdd,\n onRemove,\n onSelectVariant,\n product,\n}) => {\n const { availableChoices, canReAdd, displayStatus, error, image, tierId, title, variantInCart } = product;\n const displayVariantTitle = getFreeVariantTitle(variantInCart);\n const handleVariantChange = (event: React.ChangeEvent<HTMLSelectElement>) => {\n if (isGloballySyncing) return;\n\n const selectedVariantGid = event.target.value;\n\n if (selectedVariantGid) onSelectVariant(String(tierId), selectedVariantGid);\n event.target.value = '';\n };\n const handleReAddClick = () => {\n if (!isGloballySyncing) onAddOrReAdd(String(tierId));\n };\n const handleRemoveClick = () => {\n if (!isGloballySyncing) onRemove(String(tierId));\n };\n const imageSrc = image?.src;\n const imageAlt = image?.altText ?? title;\n const isDisabled = isGloballySyncing || !!error;\n const itemLevelError = error;\n\n return (\n <div\n className={clsx(styles['rebuy-tiered-progress-bar__gift-item'], {\n [styles['rebuy-tiered-progress-bar__gift-item--syncing']]: isGloballySyncing,\n })}\n >\n <div className={styles['rebuy-tiered-progress-bar__gift-item-image-wrapper']}>\n {imageSrc ? (\n <img\n alt={imageAlt}\n className={styles['rebuy-tiered-progress-bar__gift-item-image']}\n loading=\"lazy\"\n src={imageSrc}\n />\n ) : (\n <div\n aria-label=\"Gift product image placeholder\"\n className={styles['rebuy-tiered-progress-bar__gift-item-image']}\n ></div>\n )}\n </div>\n <div className={styles['rebuy-tiered-progress-bar__gift-item-details']}>\n <h4 className={styles['rebuy-tiered-progress-bar__gift-item-title']} id={`tpb-gift-${tierId}-title`}>\n {title}\n </h4>\n {displayStatus === GiftStatus.ADDED && displayVariantTitle && (\n <div className={styles['rebuy-tiered-progress-bar__gift-item-variant-title']}>\n {displayVariantTitle}\n </div>\n )}\n <div className={styles['rebuy-tiered-progress-bar__gift-item-actions-wrapper']}>\n {isGloballySyncing && (\n <button className={clsx(styles['rebuy-tiered-progress-bar__gift-item-button'])} disabled>\n Updating...\n </button>\n )}\n {itemLevelError && !isGloballySyncing && (\n <div className={styles['rebuy-tiered-progress-bar__error-message']}>\n Error: {itemLevelError}\n </div>\n )}\n {!isGloballySyncing && !itemLevelError && (\n <>\n {displayStatus === GiftStatus.ADDED && (\n <button\n aria-label={`Remove ${title} gift`}\n className={clsx(\n styles['rebuy-tiered-progress-bar__gift-item-button'],\n styles['rebuy-tiered-progress-bar__gift-item-button--remove']\n )}\n disabled={isDisabled}\n onClick={handleRemoveClick}\n >\n Remove\n </button>\n )}\n {displayStatus === GiftStatus.NEEDS_SELECTION && (\n <select\n aria-label={`Select option for ${title}`}\n className={clsx(styles['rebuy-tiered-progress-bar__gift-item-select'])}\n disabled={isDisabled}\n onChange={handleVariantChange}\n value=\"\"\n >\n <option disabled value=\"\">\n Select Option\n </option>\n {availableChoices.map((variant) => {\n const variantLabel = getFreeVariantTitle(variant) || variant.title;\n\n return (\n <option key={variant.id} value={variant.id}>\n {variantLabel} ({formatMoney(variant.price.amount)})\n </option>\n );\n })}\n </select>\n )}\n {canReAdd && displayStatus === GiftStatus.DECLINED && (\n <button\n aria-label={`Re-add ${title} gift`}\n className={clsx(\n styles['rebuy-tiered-progress-bar__gift-item-button'],\n styles['rebuy-tiered-progress-bar__gift-item-button--add']\n )}\n disabled={isDisabled}\n onClick={handleReAddClick}\n >\n Re-Add Gift\n </button>\n )}\n {displayStatus === GiftStatus.UNAVAILABLE && !canReAdd && (\n <div className={styles['rebuy-tiered-progress-bar__gift-item-status-text']}>\n Unavailable\n </div>\n )}\n </>\n )}\n </div>\n </div>\n </div>\n );\n};\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/smart-cart/components/TieredProgressBar/TieredProgressBar.css\";\n const result = {\"rebuy-tiered-progress-bar\":\"TieredProgressBar_rebuy-tiered-progress-bar\",\"rebuy-tiered-progress-bar__main-progress-area\":\"TieredProgressBar_rebuy-tiered-progress-bar__main-progress-area\",\"rebuy-tiered-progress-bar__tier-markers-list\":\"TieredProgressBar_rebuy-tiered-progress-bar__tier-markers-list\",\"rebuy-tiered-progress-bar__track\":\"TieredProgressBar_rebuy-tiered-progress-bar__track\",\"rebuy-tiered-progress-bar__fill\":\"TieredProgressBar_rebuy-tiered-progress-bar__fill\",\"rebuy-tiered-progress-bar__tier-step\":\"TieredProgressBar_rebuy-tiered-progress-bar__tier-step\",\"rebuy-tiered-progress-bar__tier-icon-wrapper\":\"TieredProgressBar_rebuy-tiered-progress-bar__tier-icon-wrapper\",\"rebuy-tiered-progress-bar__tier-step--reached\":\"TieredProgressBar_rebuy-tiered-progress-bar__tier-step--reached\",\"rebuy-tiered-progress-bar__tier-icon-image\":\"TieredProgressBar_rebuy-tiered-progress-bar__tier-icon-image\",\"rebuy-tiered-progress-bar__tier-label\":\"TieredProgressBar_rebuy-tiered-progress-bar__tier-label\",\"rebuy-tiered-progress-bar__feedback-message\":\"TieredProgressBar_rebuy-tiered-progress-bar__feedback-message\",\"rebuy-tiered-progress-bar__gift-area\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-area\",\"rebuy-tiered-progress-bar__gift-area-title\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-area-title\",\"rebuy-tiered-progress-bar__gift-items-list\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-items-list\",\"rebuy-tiered-progress-bar__gift-item\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item\",\"rebuy-tiered-progress-bar__gift-item-image-wrapper\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item-image-wrapper\",\"rebuy-tiered-progress-bar__gift-item-image\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item-image\",\"rebuy-tiered-progress-bar__gift-item-details\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item-details\",\"rebuy-tiered-progress-bar__gift-item-title\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item-title\",\"rebuy-tiered-progress-bar__gift-item-variant-title\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item-variant-title\",\"rebuy-tiered-progress-bar__gift-item-status-text\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item-status-text\",\"rebuy-tiered-progress-bar__gift-item-actions-wrapper\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item-actions-wrapper\",\"rebuy-tiered-progress-bar__gift-item-button\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item-button\",\"rebuy-tiered-progress-bar__gift-item-button--remove\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item-button--remove\",\"rebuy-tiered-progress-bar__gift-item-button--add\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item-button--add\",\"rebuy-tiered-progress-bar__error-message\":\"TieredProgressBar_rebuy-tiered-progress-bar__error-message\",\"rebuy-tiered-progress-bar__gift-item--syncing\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item--syncing\",\"rebuy-tiered-progress-bar__gift-item-select\":\"TieredProgressBar_rebuy-tiered-progress-bar__gift-item-select\"};\n export default result;\n ", "import type { CSSProperties } from 'react';\n\n/**\n * Centralized debug styles for Smart Cart components.\n * These styles are only applied when debug mode is active,\n * ensuring zero overhead for production users.\n */\n\n// Base colors and values\nconst debugColors = {\n background: 'rgba(0, 0, 0, 0.9)',\n border: '#666',\n error: '#f66',\n errorBg: 'rgba(255, 102, 102, 0.1)',\n primary: '#0084ff',\n secondary: '#666',\n success: '#0c6',\n text: '#fff',\n} as const;\n\n// Common style mixins\nconst buttonBase: CSSProperties = {\n border: '1px solid #666',\n borderRadius: '3px',\n cursor: 'pointer',\n fontSize: '13px',\n fontWeight: 'normal',\n padding: '6px 12px',\n};\n\n// Debug panel styles - core visual styles only\nexport const debugPanel: CSSProperties = {\n backgroundColor: debugColors.background,\n border: `1px solid ${debugColors.border}`,\n borderRadius: '3px',\n color: debugColors.text,\n fontSize: '12px',\n overflow: 'auto',\n padding: '12px',\n};\n\n// Toggle button styles - core visual styles only\nexport const toggleButton = (): CSSProperties => ({\n ...buttonBase,\n backgroundColor: debugColors.background,\n color: debugColors.text,\n});\n\n// Action button styles\nexport const actionButton = {\n primary: {\n ...buttonBase,\n backgroundColor: debugColors.primary,\n border: `1px solid ${debugColors.primary}`,\n color: 'white',\n },\n secondary: {\n ...buttonBase,\n backgroundColor: 'transparent',\n border: `1px solid ${debugColors.secondary}`,\n color: debugColors.text,\n },\n};\n\n// Status and message styles\nexport const errorMessage: CSSProperties = {\n backgroundColor: debugColors.errorBg,\n borderRadius: '3px',\n color: debugColors.error,\n fontSize: '12px',\n margin: '0 0 8px 0',\n padding: '6px',\n};\n\nexport const statusMessage: CSSProperties = {\n color: debugColors.success,\n fontSize: '12px',\n marginBottom: '6px',\n};\n\nexport const infoText: CSSProperties = {\n fontSize: '13px',\n marginBottom: '8px',\n};\n\nexport const codeBlock: CSSProperties = {\n backgroundColor: 'rgba(255, 255, 255, 0.1)',\n borderRadius: '3px',\n color: debugColors.text,\n fontFamily: 'monospace',\n fontSize: '11px',\n lineHeight: '1.4',\n padding: '6px',\n whiteSpace: 'pre-wrap',\n wordBreak: 'break-word',\n};\n\nexport const buttonGroup: CSSProperties = {\n display: 'flex',\n flexWrap: 'wrap',\n gap: '6px',\n marginBottom: '8px',\n};\n\n// Helper function to merge styles\nexport const mergeStyles = (...styles: (CSSProperties | undefined)[]): CSSProperties => {\n return Object.assign({}, ...styles.filter(Boolean));\n};\n\n// Type-safe style getter\nexport const getDebugStyle = <K extends keyof typeof debugStyles>(key: K): (typeof debugStyles)[K] => {\n return debugStyles[key];\n};\n\n// Export all styles as a single object for convenience\nexport const debugStyles = {\n actionButton,\n buttonGroup,\n codeBlock,\n colors: debugColors,\n errorMessage,\n infoText,\n panel: debugPanel,\n statusMessage,\n toggleButton,\n} as const;\n", "// ~/smart-cart/components/componentRegistry.ts\n\nimport type React from 'react';\nimport { AnnouncementBar } from '~/smart-cart/components/AnnouncementBar/AnnouncementBar';\nimport { CartItemList } from '~/smart-cart/components/CartItemList/CartItemList';\nimport { CartNoteInput } from '~/smart-cart/components/CartNoteInput/CartNoteInput';\nimport { CartSubtotal } from '~/smart-cart/components/CartSubtotal/CartSubtotal';\nimport { CartTitleBar } from '~/smart-cart/components/CartTitleBar/CartTitleBar';\nimport { CheckoutArea } from '~/smart-cart/components/CheckoutArea/CheckoutArea';\nimport { CrossSell } from '~/smart-cart/components/CrossSell/CrossSell';\nimport { CustomCodeBlock } from '~/smart-cart/components/CustomCode/CustomCodeBlock';\nimport { DiscountCodeInput } from '~/smart-cart/components/DiscountCodeInput/DiscountCodeInput';\nimport { LoginButton } from '~/smart-cart/components/LoginButton/LoginButton';\nimport { SmartCartApp } from '~/smart-cart/components/SmartCartApp/SmartCartApp';\nimport { TieredProgressBar } from '~/smart-cart/components/TieredProgressBar/TieredProgressBar';\nimport type { SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\n\nconst _StubComponent: React.FC<{\n componentConfig: SmartCartComponentConfig;\n}> = ({ componentConfig }) => (\n <div\n data-stub-anchor={componentConfig.anchor}\n data-stub-component-id={componentConfig.component_id}\n data-stub-component-type={componentConfig.type}\n style={{\n border: '1px dashed lightgrey',\n color: 'grey',\n fontSize: '12px',\n margin: '5px 0',\n padding: '10px',\n }}\n >\n Stub Component: <strong>{componentConfig.type}</strong> (ID: {componentConfig.component_id})\n <pre\n style={{\n background: '#f8f8f8',\n fontSize: '10px',\n maxHeight: '50px',\n overflow: 'auto',\n }}\n >\n {JSON.stringify(componentConfig.settings, null, 2)}\n </pre>\n </div>\n);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const componentRegistry: Record<string, React.FC<any>> = {\n // Use 'any' for props initially, refine later\n announcement_bar: AnnouncementBar,\n cart_items: CartItemList,\n cart_subtotal: CartSubtotal,\n checkout: CheckoutArea,\n cross_sell_widget: CrossSell,\n custom_code_block: CustomCodeBlock,\n discount_code: DiscountCodeInput,\n login: LoginButton,\n notes: CartNoteInput,\n smart_cart_app: SmartCartApp,\n tiered_progress_bar: TieredProgressBar,\n title_bar: CartTitleBar,\n // Add any other potential component types as stubs if needed\n};\n", "// ~/smart-cart/components/Layouts/DoubleColumnLayout.tsx\nimport clsx from 'clsx';\n\nimport { useRef } from 'react';\nimport { AnchorSlot } from '~/smart-cart/components/_Layouts/AnchorSlot';\nimport { useIsScrolled } from '~/smart-cart/hooks/useIsScrolled';\nimport type { SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\n\n/* eslint-disable-next-line no-restricted-imports */\nimport styles from './LayoutStyles.module.css';\n\ntype DoubleColumnLayoutProps = {\n components: SmartCartComponentConfig[];\n itemCount: number;\n layout: 'double' | 'double-right';\n};\n\nexport const DoubleColumnLayout: React.FC<DoubleColumnLayoutProps> = ({ components, itemCount, layout }) => {\n const scrollAreaRef = useRef<HTMLDivElement>(null);\n const isScrolled = useIsScrolled(scrollAreaRef);\n\n const layoutClass =\n layout === 'double-right'\n ? styles['rebuy-smart-cart-layout__flyout-inner--double-right']\n : styles['rebuy-smart-cart-layout__flyout-inner--double'];\n\n return (\n <div className={clsx(styles['rebuy-smart-cart-layout__flyout-inner'], layoutClass)}>\n <div className={styles['rebuy-smart-cart-layout__column--primary']}>\n <div className={styles['rebuy-smart-cart-layout__anchor-goal-box']} data-rebuy-cart-anchor=\"goalBox\">\n <AnchorSlot anchor=\"goalBox\" components={components} />\n </div>\n <div\n className={clsx(\n styles['rebuy-smart-cart-layout__scroll-area'],\n isScrolled && styles['rebuy-smart-cart-layout__scroll-area--is-scrolled']\n )}\n data-rebuy-cart-scroll-area\n ref={scrollAreaRef}\n >\n <div className={styles['rebuy-smart-cart-layout__anchor-body']} data-rebuy-cart-anchor=\"body\">\n <AnchorSlot anchor=\"body\" components={components} />\n </div>\n </div>\n <div\n className={clsx(styles['rebuy-smart-cart-layout__anchor-footer'], {\n [styles['rebuy-smart-cart-layout__anchor-footer--hidden']]: itemCount === 0,\n })}\n data-rebuy-cart-anchor=\"footer\"\n >\n <AnchorSlot anchor=\"footer\" components={components} />\n </div>\n </div>\n <div className={styles['rebuy-smart-cart-layout__column--secondary']}>\n <div\n className={styles['rebuy-smart-cart-layout__anchor-cross-sells']}\n data-rebuy-cart-anchor=\"crossSells\"\n >\n <AnchorSlot anchor=\"crossSells\" components={components} />\n </div>\n </div>\n </div>\n );\n};\n", "import { useEffect, useState, type RefObject } from 'react';\n\n/**\n * Custom hook to detect if a scrollable element has been scrolled down\n *\n * @param {RefObject<HTMLElement>} scrollElementRef - Ref to the scrollable element\n * @returns {boolean} - boolean indicating if the element has been scrolled (scrollTop > 0)\n *\n * @example\n * const scrollElementRef = useRef<HTMLDivElement>(null);\n * const isScrolled = useIsScrolled(scrollElementRef);\n *\n * return <div ref={scrollElementRef}>{isScrolled ? 'Scrolled' : 'Not scrolled'}</div>;\n */\nexport const useIsScrolled = (scrollElementRef: React.RefObject<HTMLElement>) => {\n const [isScrolled, setIsScrolled] = useState(false);\n\n useEffect(() => {\n const scrollElement = scrollElementRef.current;\n\n if (!scrollElement) return;\n\n const handleScroll = () => {\n setIsScrolled(scrollElement.scrollTop > 0);\n };\n\n // Initial check\n handleScroll();\n\n // Listen for scroll events on the scroll element\n scrollElement.addEventListener('scroll', handleScroll, { passive: true });\n\n return () => {\n scrollElement.removeEventListener('scroll', handleScroll);\n };\n }, [scrollElementRef]);\n\n return isScrolled;\n};\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/smart-cart/components/_Layouts/LayoutStyles.css\";\n const result = {\"rebuy-smart-cart-layout__anchor-goal-box\":\"LayoutStyles_rebuy-smart-cart-layout__anchor-goal-box\",\"rebuy-smart-cart-layout__scroll-area\":\"LayoutStyles_rebuy-smart-cart-layout__scroll-area\",\"rebuy-smart-cart-layout__scroll-area--is-scrolled\":\"LayoutStyles_rebuy-smart-cart-layout__scroll-area--is-scrolled\",\"rebuy-smart-cart-layout__anchor-body\":\"LayoutStyles_rebuy-smart-cart-layout__anchor-body\",\"rebuy-smart-cart-layout__anchor-footer\":\"LayoutStyles_rebuy-smart-cart-layout__anchor-footer\",\"rebuy-smart-cart-layout__anchor-footer--hidden\":\"LayoutStyles_rebuy-smart-cart-layout__anchor-footer--hidden\",\"rebuy-smart-cart-layout__anchor-cross-sells\":\"LayoutStyles_rebuy-smart-cart-layout__anchor-cross-sells\",\"rebuy-smart-cart-layout__flyout-inner\":\"LayoutStyles_rebuy-smart-cart-layout__flyout-inner\",\"rebuy-smart-cart-layout__flyout-inner--double\":\"LayoutStyles_rebuy-smart-cart-layout__flyout-inner--double\",\"rebuy-smart-cart-layout__flyout-inner--double-right\":\"LayoutStyles_rebuy-smart-cart-layout__flyout-inner--double-right\",\"rebuy-smart-cart-layout__column--primary\":\"LayoutStyles_rebuy-smart-cart-layout__column--primary\",\"rebuy-smart-cart-layout__column--secondary\":\"LayoutStyles_rebuy-smart-cart-layout__column--secondary\"};\n export default result;\n ", "// ~/smart-cart/components/Layouts/SingleColumnLayout.tsx\nimport clsx from 'clsx';\nimport { useRef } from 'react';\nimport { AnchorSlot } from '~/smart-cart/components/_Layouts/AnchorSlot';\nimport { useIsScrolled } from '~/smart-cart/hooks/useIsScrolled';\nimport type { SmartCartComponentConfig } from '~/smart-cart/types/smart-cart-component';\n\n/* eslint-disable-next-line no-restricted-imports */\nimport styles from './LayoutStyles.module.css';\n\ntype SingleColumnLayoutProps = {\n components: SmartCartComponentConfig[];\n itemCount: number;\n};\n\nexport const SingleColumnLayout: React.FC<SingleColumnLayoutProps> = ({ components, itemCount }) => {\n const scrollAreaRef = useRef<HTMLDivElement>(null);\n const isScrolled = useIsScrolled(scrollAreaRef);\n\n return (\n <>\n <div className={styles['rebuy-smart-cart-layout__anchor-goal-box']} data-rebuy-cart-anchor=\"goalBox\">\n <AnchorSlot anchor=\"goalBox\" components={components} />\n </div>\n <div\n className={clsx(\n styles['rebuy-smart-cart-layout__scroll-area'],\n isScrolled && styles['rebuy-smart-cart-layout__scroll-area--is-scrolled']\n )}\n data-rebuy-cart-scroll-area\n ref={scrollAreaRef}\n >\n <div className={styles['rebuy-smart-cart-layout__anchor-body']} data-rebuy-cart-anchor=\"body\">\n <AnchorSlot anchor=\"body\" components={components} />\n </div>\n </div>\n <div\n className={clsx(styles['rebuy-smart-cart-layout__anchor-footer'], {\n [styles['rebuy-smart-cart-layout__anchor-footer--hidden']]: itemCount === 0,\n })}\n data-rebuy-cart-anchor=\"footer\"\n >\n <AnchorSlot anchor=\"footer\" components={components} />\n </div>\n </>\n );\n};\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/smart-cart/components/SmartCartContainer/SmartCartContainer.css\";\n const result = {\"rebuy-smart-cart\":\"SmartCartContainer_rebuy-smart-cart\",\"rebuy-smart-cart__overlay-background\":\"SmartCartContainer_rebuy-smart-cart__overlay-background\",\"rebuy-smart-cart__overlay-background--visible\":\"SmartCartContainer_rebuy-smart-cart__overlay-background--visible\",\"rebuy-smart-cart--visible\":\"SmartCartContainer_rebuy-smart-cart--visible\",\"rebuy-smart-cart--layout-double\":\"SmartCartContainer_rebuy-smart-cart--layout-double\",\"rebuy-smart-cart__header\":\"SmartCartContainer_rebuy-smart-cart__header\",\"rebuy-smart-cart__header-top-bar\":\"SmartCartContainer_rebuy-smart-cart__header-top-bar\",\"rebuy-smart-cart__header-content\":\"SmartCartContainer_rebuy-smart-cart__header-content\",\"rebuy-smart-cart__close-button\":\"SmartCartContainer_rebuy-smart-cart__close-button\"};\n export default result;\n ", "import type React from 'react';\nimport { SmartCartContainer } from '~/smart-cart/components/SmartCartContainer/SmartCartContainer';\n\n/**\n * RebuySmartCart component\n *\n * This component renders the Smart Cart UI.\n * It assumes that SmartCartProvider is already rendered higher up in the component tree\n * by RebuyHydrogenReactContextProvider.\n */\nexport const RebuySmartCart: React.FC = () => {\n // TODO: Update this to use an optional component that can be added to pre-existing <Aside> components (ie. no backdrop overlay, etc.)\n return <SmartCartContainer />;\n};\n", "import { RebuyClient } from '@rebuy/rebuy';\nimport * as Utilities from '@rebuy/rebuy/utilities';\nimport { flattenConnection } from '@shopify/hydrogen';\nimport { type ComponentType, useContext, useEffect, useMemo, useState } from 'react';\n\nimport { useRebuyConfig } from '~/context/RebuyConfigContext';\nimport { RebuyContext } from '~/context/RebuyContext';\nimport { RebuyWidgetProvider } from '~/context/RebuyWidgetContext';\nimport type {\n RebuyProduct,\n RebuyProductVariant,\n RebuyWidgetContainerProps,\n RebuyWidgetMetadata,\n} from '~/types/rebuyCustom';\nimport type { HydrogenProduct } from '~/types/shopify';\nimport { filterContextForWidgetEndpoints } from '~/utils/filterContextUtils';\n\ntype RebuyWidgetContainerComponent = {\n (props: RebuyWidgetContainerProps): JSX.Element;\n} & ComponentType<RebuyWidgetContainerProps>;\n\nconst RebuyWidgetContainerBase = ({ children, ...props }: RebuyWidgetContainerProps) => {\n const { collection, collectionId, dataSource, limit, options, product, productId, variant, variantId } = props;\n\n const { apiKey, loadingStatus: configLoadingStatus, rebuyConfig } = useRebuyConfig();\n const rebuyContext = useContext(RebuyContext);\n\n const [rebuyApiClient, setRebuyApiClient] = useState<RebuyClient | null>(null);\n const [initialized, setInitialized] = useState(false);\n const shopifyProductId = product?.id ?? productId ?? null;\n const shopifyVariantId = variant?.id ?? variantId ?? null;\n const shopifyCollectionId = collection?.id ?? collectionId ?? null;\n const [products, setProducts] = useState<RebuyProduct[]>([]);\n const [metadata, setMetadata] = useState<RebuyWidgetMetadata>();\n\n // Initialize Rebuy API client\n useEffect(() => {\n if (!rebuyApiClient && apiKey && configLoadingStatus === 'success') {\n const client = new RebuyClient(apiKey);\n const currentEndpoint = dataSource || '/api/v1/products/recommended';\n\n if (rebuyContext?.contextParameters) {\n const filteredParams = filterContextForWidgetEndpoints(rebuyContext.contextParameters, currentEndpoint);\n client.setContextParameters(filteredParams as Record<string, unknown>);\n }\n\n if (options) {\n client.setDefaultParameters(options as Record<string, unknown>);\n }\n\n setRebuyApiClient(client);\n setInitialized(true);\n }\n }, [apiKey, rebuyApiClient, configLoadingStatus, options, rebuyContext, dataSource]);\n\n // Update context parameters if they change\n useEffect(() => {\n if (rebuyApiClient && rebuyContext?.contextParameters) {\n const currentEndpoint = dataSource || '/api/v1/products/recommended';\n const filteredParams = filterContextForWidgetEndpoints(rebuyContext.contextParameters, currentEndpoint);\n rebuyApiClient.setContextParameters(filteredParams as Record<string, unknown>);\n }\n }, [rebuyApiClient, rebuyContext, dataSource]);\n\n // Memoize request object on prop changes (e.g. product)\n const request = useMemo(() => {\n const req = {\n endpoint: dataSource || '/api/v1/products/recommended',\n params: {} as Record<string, string | number>, // Keeping this object generic to allow for custom endpoints\n };\n\n if (shopifyProductId) {\n req.params.shopify_product_ids = Utilities.getIdFromGraphUrl(shopifyProductId, 'Product') ?? '';\n }\n\n if (shopifyVariantId) {\n req.params.shopify_variant_ids = Utilities.getIdFromGraphUrl(shopifyVariantId, 'ProductVariant') ?? '';\n }\n\n if (shopifyCollectionId) {\n req.params.shopify_collection_ids = Utilities.getIdFromGraphUrl(shopifyCollectionId, 'Collection') ?? '';\n }\n\n if (limit) {\n req.params.limit = limit;\n }\n\n return req;\n }, [dataSource, shopifyProductId, shopifyVariantId, shopifyCollectionId, limit]);\n\n // Update product recommendations on cart or request change\n useEffect(() => {\n let isMounted = true;\n\n if (!rebuyApiClient || !initialized || configLoadingStatus !== 'success') return;\n\n const fetchData = async () => {\n try {\n const { data, metadata } = (await rebuyApiClient.getStorefrontData(\n request.endpoint,\n request.params\n )) as {\n data: RebuyProduct[];\n metadata: RebuyWidgetMetadata;\n };\n\n if (isMounted) {\n setProducts(\n Array.isArray(data)\n ? data.map((p) => ({\n ...p,\n variants: {\n nodes: p.variants ? flattenConnection(p.variants) : [],\n },\n }))\n : []\n );\n setMetadata(metadata);\n }\n } catch (error) {\n console.error('[RebuyWidgetContainer] Error fetching widget data:', error);\n\n if (isMounted) {\n setProducts([]);\n setMetadata(undefined);\n }\n }\n };\n\n fetchData();\n\n return () => {\n isMounted = false;\n };\n }, [rebuyApiClient, initialized, request, configLoadingStatus]);\n\n if (configLoadingStatus !== 'success' || !rebuyApiClient) {\n return null;\n }\n\n return (\n <RebuyWidgetProvider\n value={{\n apiKey: apiKey ?? undefined,\n cacheKey: rebuyConfig?.shop?.cache_key,\n dataSource: dataSource || '/api/v1/products/recommended',\n isHydrogenReact: rebuyContext?.contextParameters?.isHydrogenReact || false,\n key: product?.id || '',\n limit: limit || 0,\n metadata: metadata || ({} as RebuyWidgetMetadata),\n options: (options || {}) as Record<string, unknown>,\n product: product as HydrogenProduct | undefined,\n productId,\n products,\n variant: variant as RebuyProductVariant | undefined,\n variantId,\n }}\n >\n {children}\n </RebuyWidgetProvider>\n );\n};\n\nexport const RebuyWidgetContainer = RebuyWidgetContainerBase as RebuyWidgetContainerComponent;\n", "import { createContext, useContext } from 'react';\nimport type { RebuyWidgetMetadata } from '~/types/rebuyCustom';\nimport type { RebuyWidgetContextType } from '~/types/widgets';\n\nconst RebuyWidgetContext = createContext<RebuyWidgetContextType>({\n dataSource: '',\n isHydrogenReact: false,\n key: '',\n limit: 0,\n metadata: {} as RebuyWidgetMetadata,\n options: {},\n products: [],\n variant: undefined,\n variantId: undefined,\n});\n\nexport const useRebuyWidget = () => useContext(RebuyWidgetContext);\n\nexport const RebuyWidgetProvider: React.FC<{\n children: React.ReactNode;\n value: RebuyWidgetContextType;\n}> = ({ children, value }) => {\n return <RebuyWidgetContext.Provider value={value}>{children}</RebuyWidgetContext.Provider>;\n};\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/widgets/RebuyCompleteTheLook/RebuyCompleteTheLook.css\";\n const result = {\"container\":\"RebuyCompleteTheLook_container\",\"productGrid\":\"RebuyCompleteTheLook_productGrid\",\"productItem\":\"RebuyCompleteTheLook_productItem\"};\n export default result;\n ", "import { ProductCard } from '~/components/ProductCard';\nimport { Title } from '~/components/Title';\nimport { DebugKey } from '~/constants/debug';\nimport { useRebuyWidget } from '~/context/RebuyWidgetContext';\nimport { getTitleLevel } from '~/hooks/titleLevel';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport type { RebuyCompleteTheLookProps } from './types';\n\nimport styles from './RebuyCompleteTheLook.module.css';\n\n// Component implementation\nexport const RebuyCompleteTheLook = (props: RebuyCompleteTheLookProps) => {\n const {\n addToCartBtnText = 'Add to cart',\n addToCartCallback,\n customTitle = `These pair with {product_title}`,\n customTitleLevel = 'h2',\n customTitleStyle,\n } = props;\n\n const { isHydrogenReact, product, products } = useRebuyWidget();\n\n const productTitle = customTitle.replace('{product_title}', product?.title ?? '');\n\n if (products.length === 0) {\n rebuyDebugLog.log(DebugKey.WIDGET_COMPLETE_THE_LOOK, 'RebuyCompleteTheLook: No products found');\n\n return null;\n }\n\n return (\n <section className={styles.container}>\n <Title level={getTitleLevel(customTitleLevel)} style={customTitleStyle} text={productTitle} />\n <ul className={styles.productGrid}>\n {products.map((product) => (\n <li className={styles.productItem} key={product.id}>\n <ProductCard\n addToCartBtnText={addToCartBtnText}\n addToCartCallback={addToCartCallback}\n isHydrogenReact={isHydrogenReact}\n product={product}\n productCardTitleLevel={getTitleLevel(customTitleLevel, true)}\n />\n </li>\n ))}\n </ul>\n </section>\n );\n};\n", "import { useCallback, useEffect, useState } from 'react';\n\nimport { AddToCartBtn } from '~/components/AddToCartBtn';\nimport { Title } from '~/components/Title';\nimport { DebugKey } from '~/constants/debug';\nimport { useRebuyWidget } from '~/context/RebuyWidgetContext';\nimport { getTitleLevel } from '~/hooks/titleLevel';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport { convertToRebuyProduct } from '~/utils/convertToRebuyProduct';\nimport type { BundleProduct, RebuyDynamicBundleProductsProps } from '~/widgets/RebuyDynamicBundleProducts/types';\nimport { BundleImages } from './BundleImages';\nimport { BundlePrice } from './BundlePrice';\nimport { BundleSelection } from './BundleSelection';\nimport styles from './RebuyDynamicBundleProducts.module.css';\n\nexport const RebuyDynamicBundleProducts = (props: RebuyDynamicBundleProductsProps) => {\n const {\n addToCartBtnText = 'Add to cart',\n addToCartCallback,\n customTitle = `These pair with {product_title}`,\n customTitleLevel = 'h2',\n customTitleStyle,\n } = props;\n\n const { isHydrogenReact, product, products } = useRebuyWidget();\n\n const productTitle = customTitle.replace('{product_title}', product?.title ?? '');\n\n const [bundleProducts, setBundleProducts] = useState<BundleProduct[]>([]);\n\n // Initializiation\n useEffect(() => {\n const mainProduct: BundleProduct = convertToRebuyProduct(isHydrogenReact || false, product);\n\n const formattedProducts = products.map((product) => {\n return {\n ...product,\n selected: true,\n selectedVariant: product.variants.nodes[0],\n };\n });\n\n setBundleProducts([mainProduct, ...formattedProducts]);\n }, [product, products, isHydrogenReact]);\n\n const onToggleBundleItem = useCallback(\n (product: BundleProduct) => {\n product.selected = !product.selected;\n\n setBundleProducts([...bundleProducts]);\n },\n [bundleProducts]\n );\n\n const onSelectVariant = useCallback(\n (product: BundleProduct, variant_id: string) => {\n const variant = product.variants.nodes.find(({ id }) => id === variant_id);\n\n if (variant) {\n product.selectedVariant = variant;\n product.selected = variant.availableForSale || false;\n\n setBundleProducts([...bundleProducts]);\n }\n },\n [bundleProducts]\n );\n\n if (products.length === 0) {\n rebuyDebugLog.log(DebugKey.WIDGET_DYNAMIC_BUNDLE_PRODUCTS, 'RebuyDynamicBundleProducts: No products found');\n\n return null;\n }\n\n return (\n <section className={styles.container}>\n <Title level={getTitleLevel(customTitleLevel)} style={customTitleStyle} text={productTitle} />\n <div className={styles.bundleContainer}>\n <BundleImages products={bundleProducts} />\n <BundlePrice products={bundleProducts} />\n\n <div className={styles.addCartBtnContainer}>\n <AddToCartBtn\n addToCartBtnText={addToCartBtnText}\n addToCartCallback={addToCartCallback}\n disabled={bundleProducts.filter((product) => product.selected).length === 0}\n isHydrogenReact={isHydrogenReact}\n selectedVariants={bundleProducts\n .filter((product) => product.selected)\n .map((product) => {\n return product.selectedVariant;\n })}\n />\n </div>\n\n <BundleSelection\n onSelectVariant={onSelectVariant}\n onToggleBundleItem={onToggleBundleItem}\n products={bundleProducts}\n />\n </div>\n </section>\n );\n};\n", "import type { RebuyProductVariant } from '~/types/rebuyCustom';\nimport type { HydrogenProduct } from '~/types/shopify';\n\nexport const convertToRebuyProduct = (isHydrogenReact: boolean, product?: HydrogenProduct) => {\n const mainProductVariants: RebuyProductVariant[] = isHydrogenReact\n ? product?.variants?.nodes?.map((variant) => ({\n availableForSale: variant.availableForSale,\n compareAtPriceV2: {\n amount: variant.compareAtPrice?.amount || '',\n currencyCode: variant.compareAtPrice?.currencyCode || 'USD',\n },\n id: variant.id,\n image: variant.image\n ? {\n altText: variant.image.altText || null,\n height: variant.image.height || 100,\n id: variant.image.id || '',\n url: variant.image.url || '',\n width: variant.image.width || 100,\n }\n : undefined,\n priceV2: {\n amount: variant.price.amount,\n currencyCode: variant.price.currencyCode,\n },\n product: {\n handle: product.handle,\n id: product.id,\n title: product.title,\n vendor: product.vendor,\n },\n selectedOptions: variant.selectedOptions,\n sku: variant.sku || '',\n title: variant.title,\n })) || []\n : product?.adjacentVariants.map((variant) => {\n return {\n availableForSale: variant.availableForSale,\n compareAtPriceV2: {\n amount: variant.compareAtPrice?.amount || '',\n currencyCode: variant.compareAtPrice?.currencyCode || 'USD',\n },\n id: variant.id,\n image: {\n altText: variant.image?.altText || '',\n height: variant.image?.height || 100,\n id: variant.image?.id || '',\n url: variant.image?.url || '',\n width: variant.image?.width || 100,\n },\n priceV2: {\n amount: variant.price.amount || '',\n currencyCode: variant.price.currencyCode || 'USD',\n },\n product: {\n handle: product.handle,\n id: product.id,\n title: product.title,\n vendor: product.vendor,\n },\n selectedOptions: variant.selectedOptions,\n sku: variant.sku || '',\n title: variant.title || '',\n };\n }) || [];\n\n return isHydrogenReact\n ? {\n collections: {\n nodes:\n product?.collections.nodes.map((collection) => {\n return {\n handle: collection.handle,\n };\n }) || [],\n },\n compareAtPriceRange: {\n maxVariantCompareAtPrice: null,\n minVariantCompareAtPrice: null,\n },\n description: product?.description || '',\n descriptionHtml: product?.descriptionHtml || '',\n featuredImage: {\n altText: product?.featuredImage?.altText || '',\n height: product?.featuredImage?.height || 100,\n id: product?.featuredImage?.id || '',\n url: product?.featuredImage?.url || '',\n width: product?.featuredImage?.width || 100,\n },\n handle: product?.handle || '',\n id: product?.id || '',\n images: [{ altText: '', height: 100, id: '', url: '', width: 100 }],\n media: [],\n metafields: [],\n options: [],\n priceRange: product?.priceRange || {\n maxVariantPrice: { amount: '0', currencyCode: 'USD' },\n minVariantPrice: { amount: '0', currencyCode: 'USD' },\n },\n selected: true,\n selectedOptions:\n product?.selectedVariant?.selectedOptions?.reduce((acc, option) => {\n return { ...acc, [option.name]: option.value };\n }, {}) ||\n product?.variants?.nodes[0]?.selectedOptions?.reduce((acc, option) => {\n return { ...acc, [option.name]: option.value };\n }, {}) ||\n {},\n selectedSellingPlan: {},\n selectedSellingPlanAllocation: {},\n selectedVariant: {\n availableForSale:\n product?.selectedVariant?.availableForSale ||\n product?.variants?.nodes[0]?.availableForSale ||\n false,\n compareAtPriceV2: {\n amount:\n product?.selectedVariant?.compareAtPrice?.amount ||\n product?.variants?.nodes[0]?.compareAtPrice?.amount ||\n '',\n currencyCode:\n product?.selectedVariant?.compareAtPrice?.currencyCode ||\n product?.variants?.nodes[0]?.compareAtPrice?.currencyCode ||\n 'USD',\n },\n id: product?.selectedVariant?.id || '',\n image: {\n altText:\n product?.selectedVariant?.image?.altText || product?.variants?.nodes[0]?.image?.altText || '',\n height:\n product?.selectedVariant?.image?.height || product?.variants?.nodes[0]?.image?.height || 100,\n id: product?.selectedVariant?.image?.id || product?.variants?.nodes[0]?.image?.id || '',\n url: product?.selectedVariant?.image?.url || product?.variants?.nodes[0]?.image?.url || '',\n width: product?.selectedVariant?.image?.width || product?.variants?.nodes[0]?.image?.width || 100,\n },\n priceV2: {\n amount: product?.selectedVariant?.price.amount || product?.variants?.nodes[0]?.price.amount || '',\n currencyCode:\n product?.selectedVariant?.price.currencyCode ||\n product?.variants?.nodes[0]?.price.currencyCode ||\n 'USD',\n },\n product: {\n handle: product?.handle || '',\n id: product?.id || '',\n title: product?.title || '',\n vendor: product?.vendor || '',\n },\n selectedOptions:\n product?.selectedVariant?.selectedOptions || product?.variants?.nodes[0]?.selectedOptions || [],\n sku: product?.selectedVariant?.sku || product?.variants?.nodes[0]?.sku || '',\n title: product?.selectedVariant?.title || product?.variants?.nodes[0]?.title || '',\n },\n sellingPlanGroups: [],\n seo: {\n description: product?.seo?.description || '',\n title: product?.seo?.title || '',\n },\n title: product?.title || '',\n variants: {\n nodes: mainProductVariants,\n },\n vendor: product?.vendor || '',\n }\n : {\n collections: {\n nodes: [],\n },\n compareAtPriceRange: {\n maxVariantCompareAtPrice: null,\n minVariantCompareAtPrice: null,\n },\n description: product?.description || '',\n descriptionHtml: product?.descriptionHtml || '',\n featuredImage: {\n altText: product?.selectedOrFirstAvailableVariant?.image?.altText || '',\n height: product?.selectedOrFirstAvailableVariant?.image?.height || 100,\n id: product?.selectedOrFirstAvailableVariant?.image?.id || '',\n url: product?.selectedOrFirstAvailableVariant?.image?.url || '',\n width: product?.selectedOrFirstAvailableVariant?.image?.width || 100,\n },\n handle: product?.handle || '',\n id: product?.id || '',\n images: [\n {\n altText: product?.selectedOrFirstAvailableVariant?.image?.altText || '',\n height: product?.selectedOrFirstAvailableVariant?.image?.height || 100,\n id: product?.selectedOrFirstAvailableVariant?.image?.id || '',\n url: product?.selectedOrFirstAvailableVariant?.image?.url || '',\n width: product?.selectedOrFirstAvailableVariant?.image?.width || 100,\n },\n ],\n media: [],\n metafields: [],\n options: [],\n priceRange: product?.priceRange || {\n maxVariantPrice: { amount: '0', currencyCode: 'USD' },\n minVariantPrice: { amount: '0', currencyCode: 'USD' },\n },\n selected: true,\n selectedOptions:\n product?.selectedOrFirstAvailableVariant?.selectedOptions?.reduce((acc, option) => {\n return { ...acc, [option.name]: option.value };\n }, {}) || {},\n selectedSellingPlan: {},\n selectedSellingPlanAllocation: {},\n selectedVariant: {\n availableForSale: product?.selectedOrFirstAvailableVariant?.availableForSale || false,\n compareAtPriceV2: {\n amount: product?.selectedOrFirstAvailableVariant?.compareAtPrice?.amount || '',\n currencyCode: product?.selectedOrFirstAvailableVariant?.compareAtPrice?.currencyCode || 'USD',\n },\n id: product?.selectedOrFirstAvailableVariant?.id || '',\n image: {\n altText: product?.selectedOrFirstAvailableVariant?.image?.altText || '',\n height: product?.selectedOrFirstAvailableVariant?.image?.height || 100,\n id: product?.selectedOrFirstAvailableVariant?.image?.id || '',\n url: product?.selectedOrFirstAvailableVariant?.image?.url || '',\n width: product?.selectedOrFirstAvailableVariant?.image?.width || 100,\n },\n priceV2: {\n amount: product?.selectedOrFirstAvailableVariant?.price.amount || '',\n currencyCode: product?.selectedOrFirstAvailableVariant?.price.currencyCode || 'USD',\n },\n product: {\n handle: product?.handle || '',\n id: product?.id || '',\n title: product?.title || '',\n vendor: product?.vendor || '',\n },\n selectedOptions: product?.selectedOrFirstAvailableVariant?.selectedOptions || [],\n sku: product?.selectedOrFirstAvailableVariant?.sku || '',\n title: product?.selectedOrFirstAvailableVariant?.title || '',\n },\n sellingPlanGroups: [],\n seo: {\n description: null,\n title: null,\n },\n title: product?.title || '',\n variants: {\n nodes: [\n {\n availableForSale: product?.selectedOrFirstAvailableVariant?.availableForSale || false,\n compareAtPriceV2: {\n amount: product?.selectedOrFirstAvailableVariant?.compareAtPrice?.amount || '',\n currencyCode:\n product?.selectedOrFirstAvailableVariant?.compareAtPrice?.currencyCode || 'USD',\n },\n id: product?.selectedOrFirstAvailableVariant?.id || '',\n image: {\n altText: product?.selectedOrFirstAvailableVariant?.image?.altText || '',\n height: product?.selectedOrFirstAvailableVariant?.image?.height || 100,\n id: product?.selectedOrFirstAvailableVariant?.image?.id || '',\n url: product?.selectedOrFirstAvailableVariant?.image?.url || '',\n width: product?.selectedOrFirstAvailableVariant?.image?.width || 100,\n },\n priceV2: {\n amount: product?.selectedOrFirstAvailableVariant?.price.amount || '',\n currencyCode: product?.selectedOrFirstAvailableVariant?.price.currencyCode || 'USD',\n },\n product: {\n handle: product?.handle || '',\n id: product?.id || '',\n title: product?.title || '',\n vendor: product?.vendor || '',\n },\n selectedOptions: product?.selectedOrFirstAvailableVariant?.selectedOptions || [],\n sku: product?.selectedOrFirstAvailableVariant?.sku || '',\n title: product?.selectedOrFirstAvailableVariant?.title || '',\n },\n ...mainProductVariants,\n ],\n },\n vendor: product?.vendor || '',\n };\n};\n", "import { Image } from '@shopify/hydrogen';\nimport { Fragment } from 'react';\nimport { RebuyLink } from '~/components/RebuyLink';\n\nimport type { BundleProduct } from '~/widgets/RebuyDynamicBundleProducts/types';\n\nimport styles from './RebuyDynamicBundleProducts.module.css';\n\nexport const BundleImages = ({ products }: { products: BundleProduct[] }) => {\n const selected = products.filter((product) => product.selected);\n\n return (\n <ul className={styles.bundleImages}>\n {products.map((product, index) => {\n const image = product.selectedVariant?.image;\n const productImage = image ? (\n <Image\n alt={image.altText || `Picture of ${product.title}`}\n className={styles.bundleImage}\n data={image}\n height={80}\n title={product.title}\n width={80}\n />\n ) : (\n // No image defined\n product.title\n );\n // Hide delimiter for first selected item\n const showDelimiter = selected[0]?.id !== product.id;\n\n return (\n <Fragment key={product.id + '-BundleImages-' + index}>\n {product.selected && (\n <>\n {showDelimiter && (\n <li className={styles.bundleImageDelimiter}>\n <span>+</span>\n </li>\n )}\n <li className=\"flex items-center\">\n {product.default ? (\n // Already on product page\n productImage\n ) : (\n // Link to product\n <RebuyLink\n ariaLabel={`View ${product.title}`}\n handle={`/products/${product.handle}`}\n >\n {productImage}\n </RebuyLink>\n )}\n </li>\n </>\n )}\n </Fragment>\n );\n })}\n </ul>\n );\n};\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/widgets/RebuyDynamicBundleProducts/RebuyDynamicBundleProducts.css\";\n const result = {\"container\":\"RebuyDynamicBundleProducts_container\",\"addCartBtnContainer\":\"RebuyDynamicBundleProducts_addCartBtnContainer\",\"bundleContainer\":\"RebuyDynamicBundleProducts_bundleContainer\",\"select\":\"RebuyDynamicBundleProducts_select\",\"bundleItemRowContainer\":\"RebuyDynamicBundleProducts_bundleItemRowContainer\",\"unselected\":\"RebuyDynamicBundleProducts_unselected\",\"bundleItemRow\":\"RebuyDynamicBundleProducts_bundleItemRow\",\"bundleItemInput\":\"RebuyDynamicBundleProducts_bundleItemInput\",\"bundleItemLabel\":\"RebuyDynamicBundleProducts_bundleItemLabel\",\"bundleImages\":\"RebuyDynamicBundleProducts_bundleImages\",\"bundleImage\":\"RebuyDynamicBundleProducts_bundleImage\",\"bundleImageDelimiter\":\"RebuyDynamicBundleProducts_bundleImageDelimiter\",\"compareAtPrice\":\"RebuyDynamicBundleProducts_compareAtPrice\"};\n export default result;\n ", "import { Money } from '@shopify/hydrogen';\n\nimport type { CurrencyCode, MoneyV2 } from '@shopify/hydrogen-react/storefront-api-types';\nimport type { BundleProduct } from '~/widgets/RebuyDynamicBundleProducts/types';\nimport styles from './RebuyDynamicBundleProducts.module.css';\n\nexport const BundlePrice = ({ products }: { products: BundleProduct[] }) => {\n const isDisabled = products.filter((product) => product.selected).length < 1;\n\n const totalBundlePrice = () => {\n let total = 0;\n let currencyCode = 'USD' as CurrencyCode;\n\n for (const product of products) {\n if (product.selected && product.selectedVariant) {\n const { priceV2: price } = product.selectedVariant;\n\n total += Number(price?.amount);\n currencyCode = (price?.currencyCode || 'USD') as CurrencyCode;\n }\n }\n\n return {\n amount: String(total),\n currencyCode,\n };\n };\n\n const totalBundleCompareAtPrice = () => {\n let compareAtTotal = 0;\n let currencyCode = 'USD' as CurrencyCode;\n\n for (const product of products) {\n if (product.selected && product.selectedVariant) {\n const { compareAtPriceV2: compareAtPrice, priceV2: price } = product.selectedVariant;\n\n currencyCode = (price?.currencyCode || 'USD') as CurrencyCode;\n compareAtTotal += Number((compareAtPrice || price)?.amount);\n }\n }\n\n return {\n amount: String(compareAtTotal),\n currencyCode,\n };\n };\n const isDiscounted = (\n price: { amount: string; currencyCode: string } | null,\n compareAtPrice: { amount: string; currencyCode: string } | null\n ) => Number(compareAtPrice?.amount) > Number(price?.amount);\n\n const price = totalBundlePrice();\n const compareAtPrice = totalBundleCompareAtPrice();\n\n const CompareAtPrice = ({ data: compareAtPrice }: { data: MoneyV2 | null }) => {\n return (\n compareAtPrice && (\n <Money as=\"span\" className={styles.compareAtPrice} data={compareAtPrice} withoutTrailingZeros />\n )\n );\n };\n\n return (\n products.length > 0 && (\n <div className=\"flex items-center flex-col\">\n {!isDisabled && (\n <p className=\"flex items-center gap-2 mb-2\">\n <span>Total Price:</span>\n <Money as=\"span\" data={price} withoutTrailingZeros />\n {isDiscounted(price, compareAtPrice) && <CompareAtPrice data={compareAtPrice} />}\n </p>\n )}\n </div>\n )\n );\n};\n", "import clsx from 'clsx';\nimport { RebuyProductPrice } from '~/components/ProductPrice';\nimport { Select } from '~/widgets/RebuyDynamicBundleProducts/Select';\nimport type { BundleSelectionProps } from '~/widgets/RebuyDynamicBundleProducts/types';\n\nimport styles from './RebuyDynamicBundleProducts.module.css';\n\nexport const BundleSelection = ({ onSelectVariant, onToggleBundleItem, products }: BundleSelectionProps) => {\n return (\n <ul>\n {products.map((product, index) => {\n const { availableForSale } = product.selectedVariant;\n const isOutOfStock = !availableForSale;\n\n return (\n <li\n className={clsx(styles.bundleItemRowContainer, !product.selected && styles.unselected)}\n key={product.id + '-BundleSelection' + index}\n >\n <div className={styles.bundleItemRow}>\n <input\n checked={product.selected && availableForSale}\n className=\"mt-1 rounded-sm accent-black cursor-pointer\"\n disabled={isOutOfStock}\n id={`${product.id}-toggle`}\n onChange={() => onToggleBundleItem(product)}\n type=\"checkbox\"\n value={product.id}\n />\n <div className={styles.bundleItemInput}>\n <label className={styles.bundleItemLabel} htmlFor={`${product.id}-toggle`}>\n {isOutOfStock && <b>SOLD OUT</b>}\n {product.default && <b>This item:</b>}\n {product.title}\n\n <RebuyProductPrice selectedVariant={product.selectedVariant} />\n </label>\n\n {product.variants.nodes.length > 1 && (\n <Select onSelectVariant={onSelectVariant} product={product} />\n )}\n </div>\n </div>\n </li>\n );\n })}\n </ul>\n );\n};\n", "import type { BundleProduct, BundleSelectProps } from '~/widgets/RebuyDynamicBundleProducts/types';\n\nimport styles from './RebuyDynamicBundleProducts.module.css';\n\nexport const Select = ({ onSelectVariant, product }: BundleSelectProps) => {\n const getOptionsLabel = (product: BundleProduct) => {\n const options = product.variants.nodes[0].selectedOptions;\n const optionsFromKeys = options ? Object.keys(options[0]) : [];\n const optionsFromValues = options ? options.map((option) => option.name) : [];\n const useValues = optionsFromKeys.every((key) => ['name', 'value'].includes(key));\n\n // Return delimited label for available option(s) e.g. Color / Size, Scent, etc\n return (useValues ? optionsFromValues : optionsFromKeys).join(' / ');\n };\n\n return (\n product && (\n <select\n aria-label=\"select variant\"\n className={styles.select}\n onChange={(e) => onSelectVariant(product, e.target.value)}\n value={product.selectedVariant.id}\n >\n <optgroup label={getOptionsLabel(product)}>\n {product.variants.nodes.map(({ id, title }) => (\n <option key={id + '-BundleVariant'} value={id}>\n {title}\n </option>\n ))}\n </optgroup>\n </select>\n )\n );\n};\n", "import { Money } from '@shopify/hydrogen-react';\nimport type { CurrencyCode, MoneyV2 } from '@shopify/hydrogen-react/storefront-api-types';\nimport { useCallback, useEffect, useState } from 'react';\n\nimport { AddToCartBtn } from '~/components/AddToCartBtn';\nimport { Title } from '~/components/Title';\nimport { DebugKey } from '~/constants/debug';\nimport { useRebuyWidget } from '~/context/RebuyWidgetContext';\nimport { getTitleLevel } from '~/hooks/titleLevel';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport type { RebuyProduct } from '~/types/rebuyCustom';\nimport { convertToRebuyProduct } from '~/utils/convertToRebuyProduct';\nimport type { RebuyProductAddOnProps } from '~/widgets/RebuyProductAddOns/types';\nimport { RebuyProductAddOnCard } from './RebuyProductAddOnCard';\nimport styles from './RebuyProductAddOns.module.css';\n\nexport const RebuyProductAddOns = (props: RebuyProductAddOnProps) => {\n const {\n addToCartBtnText = 'Add to cart',\n addToCartCallback,\n customTitle = `These pair with {product_title}`,\n customTitleLevel = 'h2',\n customTitleStyle,\n includeMainProduct = false,\n learnMoreText = 'Learn more',\n outOfStockText = 'Out of stock',\n subtotalText = 'Add-ons Subtotal: ',\n withProductText = `With {product_title}: `,\n } = props;\n\n const { isHydrogenReact, product, products } = useRebuyWidget();\n\n const productTitleClean = customTitle.replace('{product_title}', product?.title ?? '');\n const withProductTextClean = withProductText.replace('{product_title}', product?.title ?? '');\n\n const [addedItems, setAddedItems] = useState<RebuyProduct[]>(products);\n\n const [subtotalWithProduct, setSubtotalWithProduct] = useState<MoneyV2>();\n const [subtotalWithOutProduct, setSubtotalWithOutProduct] = useState<MoneyV2>();\n\n const convertedProduct = convertToRebuyProduct(isHydrogenReact || false, product);\n\n useEffect(() => {\n let initialTotal = 0;\n let currencyCode = 'USD' as CurrencyCode;\n\n products.map((product) => {\n product.selectedVariant = product.variants.nodes[0];\n product.selected = true;\n\n if (product.selectedVariant?.priceV2) {\n initialTotal += Number(product.selectedVariant.priceV2.amount);\n currencyCode = (product.selectedVariant.priceV2.currencyCode || 'USD') as CurrencyCode;\n }\n });\n\n setSubtotalWithProduct({\n amount: String(initialTotal),\n currencyCode,\n });\n\n setSubtotalWithOutProduct({\n amount: String(\n initialTotal -\n Number(\n isHydrogenReact\n ? convertedProduct?.selectedVariant?.priceV2?.amount\n : product?.selectedOrFirstAvailableVariant?.price.amount\n )\n ),\n currencyCode,\n });\n setAddedItems(products);\n\n if (includeMainProduct) {\n setAddedItems([convertedProduct, ...products]);\n } else {\n setAddedItems(products);\n }\n }, [products, product, isHydrogenReact, includeMainProduct]);\n\n const handleChange = useCallback(\n (event: React.ChangeEvent<HTMLInputElement>, product: RebuyProduct) => {\n const newProducts = [...products];\n const productIndex = newProducts.findIndex((p) => p.id === product.id);\n\n if (productIndex !== -1) {\n newProducts[productIndex] = {\n ...newProducts[productIndex],\n selected: event.target.checked,\n };\n\n product.selected = event.target.checked;\n\n if (event.target.checked) {\n setAddedItems((prev) => [...prev, product]);\n } else {\n setAddedItems((prev) => prev.filter((item) => item.id !== product.id));\n }\n }\n },\n [products]\n );\n\n useEffect(() => {\n let total = 0;\n let currencyCode = 'USD' as CurrencyCode;\n\n addedItems.forEach((item) => {\n if (item.selected && item.selectedVariant?.priceV2) {\n total += Number(item.selectedVariant.priceV2.amount);\n currencyCode = (item.selectedVariant.priceV2.currencyCode || 'USD') as CurrencyCode;\n }\n });\n\n setSubtotalWithProduct({\n amount: String(total),\n currencyCode,\n });\n\n setSubtotalWithOutProduct({\n amount: String(\n total -\n Number(\n isHydrogenReact\n ? convertedProduct?.selectedVariant?.priceV2?.amount\n : product?.selectedOrFirstAvailableVariant?.price.amount\n )\n ),\n currencyCode,\n });\n }, [addedItems, product, isHydrogenReact]);\n\n if (products.length === 0) {\n rebuyDebugLog.log(DebugKey.WIDGET_PRODUCT_ADD_ONS, 'RebuyProductAddOns: No products found');\n\n return null;\n }\n\n return (\n <div className={styles.container}>\n <Title level={getTitleLevel(customTitleLevel)} style={customTitleStyle} text={productTitleClean} />\n <ul className={styles.productAddOnsList}>\n {products.map((product) => (\n <li key={product.id}>\n <RebuyProductAddOnCard\n handleChange={handleChange}\n learnMoreText={learnMoreText}\n outOfStockText={outOfStockText}\n product={product}\n titleLevel={getTitleLevel(customTitleLevel, true)}\n />\n </li>\n ))}\n </ul>\n <div className={styles.productAddOnsFooter}>\n <div className={styles.moneyContainer}>\n {subtotalText}\n {subtotalWithOutProduct && <Money data={subtotalWithOutProduct} withoutTrailingZeros />}\n </div>\n {includeMainProduct && (\n <div className={styles.moneyContainer}>\n {withProductTextClean}\n {subtotalWithProduct && <Money data={subtotalWithProduct} withoutTrailingZeros />}\n </div>\n )}\n <div className={styles.addCartBtnContainer}>\n {includeMainProduct ? (\n <AddToCartBtn\n addToCartBtnText={addToCartBtnText}\n addToCartCallback={addToCartCallback}\n disabled={addedItems.length === 0}\n isHydrogenReact={isHydrogenReact}\n moneyData={subtotalWithProduct}\n selectedVariants={addedItems.map((item) => item.selectedVariant)}\n />\n ) : (\n <AddToCartBtn\n addToCartBtnText={addToCartBtnText}\n addToCartCallback={addToCartCallback}\n disabled={addedItems.length === 0}\n isHydrogenReact={isHydrogenReact}\n moneyData={subtotalWithOutProduct}\n selectedVariants={addedItems.map((item) => item.selectedVariant)}\n />\n )}\n </div>\n </div>\n </div>\n );\n};\n", "import { Image } from '@shopify/hydrogen';\n\nimport { RebuyProductPrice } from '~/components/ProductPrice';\nimport { RebuyLink } from '~/components/RebuyLink';\nimport { Title } from '~/components/Title';\nimport type { RebuyProductAddOnCardProps } from './types';\nimport styles from './RebuyProductAddOns.module.css';\n\nexport const RebuyProductAddOnCard = ({\n handleChange,\n learnMoreText,\n outOfStockText,\n product,\n titleLevel,\n}: RebuyProductAddOnCardProps) => {\n const { availableForSale, image } = product.selectedVariant || {};\n\n return (\n <label className={styles.addOnCard} htmlFor={product.id}>\n <div className={styles.addOnCardContent}>\n <input\n checked={Boolean(product.selected)}\n className={styles.addOnCardInput}\n disabled={!product.variants.nodes[0].availableForSale}\n id={product.id}\n name={product.title}\n onChange={(event) => handleChange(event, product)}\n type=\"checkbox\"\n value=\"\"\n />\n <div className={styles.addOnCardContentImage}>\n {image && (\n <Image\n alt={image.altText || `Picture of ${product.title}`}\n data={image}\n height={150}\n width={300}\n />\n )}\n </div>\n\n <div className={styles.addOnCardTextContent}>\n {!availableForSale && <p className={styles.addOnCardOutOfStock}>{outOfStockText}</p>}\n\n <Title level={titleLevel} text={product.title} />\n\n <RebuyProductPrice selectedVariant={product.selectedVariant} />\n <RebuyLink\n ariaLabel={`View ${product.title}`}\n className={styles.addOnCardLearnMore}\n handle={`/products/${product.handle}`}\n >\n {learnMoreText}\n </RebuyLink>\n </div>\n </div>\n </label>\n );\n};\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/widgets/RebuyProductAddOns/RebuyProductAddOns.css\";\n const result = {\"container\":\"RebuyProductAddOns_container\",\"productAddOnsList\":\"RebuyProductAddOns_productAddOnsList\",\"addOnCard\":\"RebuyProductAddOns_addOnCard\",\"addOnCardContent\":\"RebuyProductAddOns_addOnCardContent\",\"addOnCardInput\":\"RebuyProductAddOns_addOnCardInput\",\"addOnCardContentImage\":\"RebuyProductAddOns_addOnCardContentImage\",\"addOnCardOutOfStock\":\"RebuyProductAddOns_addOnCardOutOfStock\",\"addOnCardTextContent\":\"RebuyProductAddOns_addOnCardTextContent\",\"addOnCardLearnMore\":\"RebuyProductAddOns_addOnCardLearnMore\",\"addCartBtnContainer\":\"RebuyProductAddOns_addCartBtnContainer\",\"productAddOnsFooter\":\"RebuyProductAddOns_productAddOnsFooter\",\"moneyContainer\":\"RebuyProductAddOns_moneyContainer\"};\n export default result;\n ", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/widgets/RebuyProductRecommendations/RebuyProductRecommendations.css\";\n const result = {\"container\":\"RebuyProductRecommendations_container\",\"productGrid\":\"RebuyProductRecommendations_productGrid\"};\n export default result;\n ", "import { ProductCard } from '~/components/ProductCard';\nimport { Title } from '~/components/Title';\nimport { DebugKey } from '~/constants/debug';\nimport { useRebuyWidget } from '~/context/RebuyWidgetContext';\nimport { getTitleLevel } from '~/hooks/titleLevel';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport type { RebuyProductRecommendationsProps } from './types';\n\nimport styles from './RebuyProductRecommendations.module.css';\n\nexport const RebuyProductRecommendations = (props: RebuyProductRecommendationsProps) => {\n const {\n addToCartBtnText = 'Add to cart',\n addToCartCallback,\n customTitle = `These pair with {product_title}`,\n customTitleLevel = 'h2',\n customTitleStyle,\n } = props;\n\n const { isHydrogenReact, product, products } = useRebuyWidget();\n\n const productTitle = customTitle.replace('{product_title}', product?.title ?? '');\n\n if (products.length === 0) {\n rebuyDebugLog.log(DebugKey.WIDGET_PRODUCT_RECOMMENDATIONS, 'RebuyProductRecommendations: No products found');\n\n return null;\n }\n\n return (\n <section className={styles.container}>\n <Title level={getTitleLevel(customTitleLevel)} style={customTitleStyle} text={productTitle} />\n <ul className={styles.productGrid}>\n {products.map((product) => (\n <li key={product.id}>\n <ProductCard\n addToCartBtnText={addToCartBtnText}\n addToCartCallback={addToCartCallback}\n isHydrogenReact={isHydrogenReact}\n product={product}\n productCardTitleLevel={getTitleLevel(customTitleLevel, true)}\n />\n </li>\n ))}\n </ul>\n </section>\n );\n};\n", "import { RebuyClient } from '@rebuy/rebuy';\nimport * as Utilities from '@rebuy/rebuy/utilities';\nimport { useEffect, useMemo, useState } from 'react';\nimport { useRebuyConfig } from '~/context/RebuyConfigContext';\n\nimport type { ProductViewedRequest } from '~/types/common';\nimport type { RebuyProductViewedProps } from '~/widgets/RebuyProductViewed/types';\nimport { useProductViewedStore } from '~/zustandStores/productViewed';\n\nexport const RebuyProductViewed = ({ ...props }: RebuyProductViewedProps) => {\n const { apiKey: apiKeyFromContext } = useRebuyConfig();\n const { customerId, product, productHandle, productId } = props;\n\n // eslint-disable-next-line no-unused-vars\n const [event, setEvent] = useState(null);\n const [Rebuy, setRebuy] = useState<RebuyClient | null>(null);\n const shopifyProductId = product?.id ?? productId ?? null;\n const [initialized, setInitialized] = useState(false);\n const { setCustomerId, setUuid } = useProductViewedStore();\n\n const request = useMemo(() => {\n const request: ProductViewedRequest = {\n parameters: {},\n };\n\n if (shopifyProductId) {\n const productNumericId = Utilities.getIdFromGraphUrl(shopifyProductId, 'Product');\n\n if (productNumericId !== null) {\n request.parameters.shopify_product_id = productNumericId.toString();\n }\n } else if (productHandle) {\n request.parameters.shopify_product_handle = productHandle;\n }\n\n return request;\n }, [productHandle, shopifyProductId]);\n\n useEffect(() => {\n const recordView = async () => {\n if (!Rebuy) {\n return;\n }\n\n try {\n const response = await Rebuy.trackProductViewed(request.parameters);\n setEvent(response.data);\n\n if (response.data === 'Received' && request.parameters.uuid) {\n setUuid(request.parameters.uuid);\n\n if (customerId && customerId !== '') {\n setCustomerId(customerId);\n }\n }\n } catch (error) {\n console.error('Error tracking product view:', error);\n }\n };\n\n if (!initialized && apiKeyFromContext) {\n const client = new RebuyClient(apiKeyFromContext);\n\n setRebuy(client);\n setInitialized(true);\n\n return;\n }\n\n recordView();\n }, [request.parameters, initialized, apiKeyFromContext, Rebuy]);\n\n if (Object.keys(request.parameters).length === 0) {\n console.warn('No parameters!');\n\n return;\n }\n\n return null;\n};\n", "import { create } from 'zustand';\n\ntype ProductViewedStore = {\n customerId: string | null;\n setCustomerId: (customerId: string) => void;\n setUuid: (uuid: string) => void;\n uuid: string | null;\n};\n\nexport const useProductViewedStore = create<ProductViewedStore>((set) => ({\n customerId: null,\n setCustomerId: (customerId) => set({ customerId }),\n setUuid: (uuid) => set({ uuid }),\n uuid: null,\n}));\n", "import { RebuyClient } from '@rebuy/rebuy';\nimport { flattenConnection } from '@shopify/hydrogen';\nimport { useContext, useEffect, useMemo, useState } from 'react';\nimport { ProductCard } from '~/components/ProductCard';\nimport { Title } from '~/components/Title';\nimport { DebugKey } from '~/constants/debug';\nimport { useRebuyConfig } from '~/context/RebuyConfigContext';\nimport { RebuyContext } from '~/context/RebuyContext';\nimport { getTitleLevel } from '~/hooks/titleLevel';\nimport { rebuyDebugLog } from '~/smart-cart/utils/debugLog';\nimport type { RebuyProduct, RebuyWidgetMetadata } from '~/types/rebuyCustom';\nimport { filterContextForWidgetEndpoints } from '~/utils/filterContextUtils';\nimport { useProductViewedStore } from '~/zustandStores/productViewed';\nimport type { RebuyRecentlyViewedProductsProps } from './types';\nimport styles from './RebuyRecentlyViewedProducts.module.css';\n\nexport const RebuyRecentlyViewedProducts = (props: RebuyRecentlyViewedProductsProps) => {\n const {\n addToCartBtnText = 'Add to cart',\n addToCartCallback,\n customTitle = `Your recently viewed products`,\n customTitleLevel = 'h2',\n customTitleStyle,\n limit,\n options,\n productId,\n } = props;\n const { customerId, uuid } = useProductViewedStore();\n\n const { apiKey, loadingStatus: configLoadingStatus, rebuyConfig } = useRebuyConfig();\n const rebuyContext = useContext(RebuyContext);\n\n const [rebuyApiClient, setRebuyApiClient] = useState<RebuyClient | null>(null);\n const [initialized, setInitialized] = useState(false);\n const [products, setProducts] = useState<RebuyProduct[]>([]);\n const [metadata, setMetadata] = useState<RebuyWidgetMetadata>();\n const rebuyConfigKey = rebuyConfig?.shop?.cache_key;\n\n const endpoint =\n customerId && customerId !== ''\n ? `/api/v1/products/viewed?key=${rebuyConfigKey}&customer_id=${customerId}`\n : `/api/v1/products/viewed?key=${rebuyConfigKey}&uuid=${uuid}`;\n\n // const filtered = products?.filter((recent) => recent.id !== product?.id);\n // Initialize Rebuy API client\n useEffect(() => {\n if (!rebuyApiClient && apiKey && configLoadingStatus === 'success') {\n const client = new RebuyClient(apiKey);\n\n if (rebuyContext?.contextParameters) {\n const filteredParams = filterContextForWidgetEndpoints(rebuyContext.contextParameters, endpoint);\n client.setContextParameters(filteredParams as Record<string, unknown>);\n }\n\n if (options) {\n client.setDefaultParameters(options as Record<string, unknown>);\n }\n\n setRebuyApiClient(client);\n setInitialized(true);\n }\n }, [apiKey, rebuyApiClient, configLoadingStatus, options, rebuyContext, uuid, endpoint]);\n\n // Update context parameters if they change\n useEffect(() => {\n if (rebuyApiClient && rebuyContext?.contextParameters) {\n const filteredParams = filterContextForWidgetEndpoints(rebuyContext.contextParameters, endpoint);\n rebuyApiClient.setContextParameters(filteredParams as Record<string, unknown>);\n }\n }, [rebuyApiClient, rebuyContext, uuid, endpoint]);\n\n // Memoize request object on prop changes (e.g. product)\n const request = useMemo(() => {\n const req = {\n endpoint,\n params: {} as Record<string, string | number>, // Keeping this object generic to allow for custom endpoints\n };\n\n if (limit) {\n req.params.limit = limit;\n }\n\n return req;\n }, [limit, uuid, endpoint]);\n\n // Update product recommendations on cart or request change\n useEffect(() => {\n let isMounted = true;\n\n if (!rebuyApiClient || !initialized || configLoadingStatus !== 'success') return;\n\n const fetchData = async () => {\n try {\n const { data, metadata } = (await rebuyApiClient.getStorefrontData(\n request.endpoint,\n request.params\n )) as {\n data: RebuyProduct[];\n metadata: RebuyWidgetMetadata;\n };\n\n if (isMounted) {\n setProducts(\n Array.isArray(data)\n ? data\n .filter((p) => p.id !== productId)\n .map((p) => ({\n ...p,\n variants: {\n nodes: p.variants ? flattenConnection(p.variants) : [],\n },\n }))\n : []\n );\n setMetadata(metadata);\n }\n } catch (error) {\n console.error('[RebuyWidgetContainer] Error fetching widget data:', error);\n\n if (isMounted) {\n setProducts([]);\n setMetadata(undefined);\n }\n }\n };\n\n fetchData();\n\n return () => {\n isMounted = false;\n };\n }, [rebuyApiClient, initialized, request, configLoadingStatus, productId]);\n\n if (products.length === 0) {\n rebuyDebugLog.log(DebugKey.WIDGET_RECENTLY_VIEWED_PRODUCTS, 'RebuyRecentlyViewedProducts: No products found');\n\n return null;\n }\n\n return (\n <div className={styles['rebuy-recently-viewed-products-container']}>\n <Title level={getTitleLevel(customTitleLevel)} style={customTitleStyle} text={customTitle} />\n <ul className={styles['product-grid']}>\n {products?.map((product) => (\n <li key={product.id}>\n <ProductCard\n addToCartBtnText={addToCartBtnText}\n addToCartCallback={addToCartCallback}\n key={product.id}\n product={product}\n productCardTitleLevel={getTitleLevel('h2')}\n />\n </li>\n ))}\n </ul>\n </div>\n );\n};\n", "\n import \"/tmp/tmp-165-PG4yN66KHu8v/opt/atlassian/pipelines/agent/build/src/widgets/RebuyRecentlyViewedProducts/RebuyRecentlyViewedProducts.css\";\n const result = {\"rebuy-recently-viewed-products-container\":\"RebuyRecentlyViewedProducts_rebuy-recently-viewed-products-container\",\"product-grid\":\"RebuyRecentlyViewedProducts_product-grid\"};\n export default result;\n ", "export const REBUY_THEME_STYLES_BASE_URL = 'https://rebuyengine.com/api/v1/theme-styles';\n", "import { REBUY_THEME_STYLES_BASE_URL } from '~/constants/api';\n\n/**\n * Generates a link object for the Rebuy theme stylesheet.\n * Suitable for Remix's static `links` export.\n *\n * Requires API key to be passed directly or available as an environment variable\n * that this function can access (if it were running in a Node.js server environment\n * where process.env is available before React rendering).\n * For Remix, it's best to pass the apiKey explicitly if it's not a universally available env var.\n *\n * @param {object} options - The options for the Rebuy theme stylesheet link.\n * @param {string} options.apiKey - The API key for the Rebuy theme stylesheet.\n * @returns {Array<{ href: string; rel: string }>}\n */\nexport const getRebuyThemeStylesLink = (options: { apiKey: string }): { href: string; rel: string }[] => {\n const { apiKey } = options;\n\n if (!apiKey) {\n // This function is often called in a context where React isn't fully set up (like Remix links)\n // so console.warn might be the best side effect.\n console.warn('[getRebuyThemeStylesLink] API key is missing. Stylesheet link will not be generated.');\n\n return [];\n }\n\n // TODO: use rebuy client to generate domain\n const stylesheetUrl = `${REBUY_THEME_STYLES_BASE_URL}?key=${apiKey}`;\n\n return [{ href: stylesheetUrl, rel: 'stylesheet' }];\n};\n"],
5
+ "mappings": ";AAAA,YAAYA,gBAAe;AAE3B,SAAS,WA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AA,IACJ;AAEA,cAAU;AAEV,WAAO,MAAM;AACT,kBAAY;AAAA,IAChB;AAAA,EACJ,GAAG,CAAC,gBAAgB,aAAa,SAAS,qBAAqB,SAAS,CAAC;AAEzE,MAAI,SAAS,WAAW,GAAG;AACvB,kBAAc,6EAA8C,gDAAgD;AAE5G,WAAO;AAAA,EACX;AAEA,SACI,gBAAAN,OAAC,SAAI,WAAW,oCAAO,0CAA0C,GAC7D;AAAA,oBAAAD,MAAC,SAAM,OAAO,cAAc,gBAAgB,GAAG,OAAO,kBAAkB,MAAM,aAAa;AAAA,IAC3F,gBAAAA,MAAC,QAAG,WAAW,oCAAO,cAAc,GAC/B,oBAAU,IAAI,CAAC,YACZ,gBAAAA,MAAC,QACG,0BAAAA;AAAA,MAAC;AAAA;AAAA,QACG;AAAA,QACA;AAAA,QAEA;AAAA,QACA,uBAAuB,cAAc,IAAI;AAAA;AAAA,MAFpC,QAAQ;AAAA,IAGjB,KAPK,QAAQ,EAQjB,CACH,GACL;AAAA,KACJ;AAER;;;AE7JO,IAAM,8BAA8B;;;ACepC,IAAM,0BAA0B,CAAC,YAAiE;AACrG,QAAM,EAAE,OAAO,IAAI;AAEnB,MAAI,CAAC,QAAQ;AAGT,YAAQ,KAAK,sFAAsF;AAEnG,WAAO,CAAC;AAAA,EACZ;AAGA,QAAM,gBAAgB,GAAG,2BAA2B,QAAQ,MAAM;AAElE,SAAO,CAAC,EAAE,MAAM,eAAe,KAAK,aAAa,CAAC;AACtD;",
6
+ "names": ["Utilities", "useMemo", "useRef", "errorMessage", "createContext", "useEffect", "useState", "isEqual", "createContext", "useContext", "useEffect", "useMemo", "useRef", "useState", "flattenConnection", "jsx", "jsx", "flattenConnection", "jsx", "createContext", "useContext", "useState", "useMemo", "useRef", "isEqual", "useEffect", "jsx", "jsxs", "warningLogged", "useRef", "useMemo", "Utilities", "useEffect", "useMemo", "useRef", "useLocation", "Fragment", "jsx", "jsxs", "warningLogged", "useRef", "useLocation", "useMemo", "useEffect", "clsx", "React", "useCallback", "useEffect", "useMemo", "useRef", "useMemo", "useCallback", "useEffect", "useMemo", "useRef", "useState", "jsx", "jsx", "jsxs", "useState", "useRef", "useMemo", "useCallback", "useEffect", "useCallback", "useEffect", "useMemo", "useState", "jsx", "useCallback", "useMemo", "useState", "useState", "useMemo", "useCallback", "bmsmTiers", "result", "Fragment", "jsx", "jsxs", "useState", "useMemo", "useCallback", "useEffect", "result", "jsx", "result", "jsx", "clsx", "React", "useCallback", "useEffect", "useMemo", "useRef", "useState", "useFetcher", "result", "jsx", "jsxs", "React", "useFetcher", "useRef", "useState", "useMemo", "useEffect", "useCallback", "clsx", "clsx", "React", "useCallback", "useMemo", "useState", "result", "Fragment", "jsx", "jsxs", "useState", "useMemo", "useCallback", "clsx", "React", "DOMPurify", "React", "useMemo", "result", "jsx", "React", "useMemo", "DOMPurify", "React", "useCallback", "useEffect", "useMemo", "useState", "useFetcher", "result", "jsx", "jsxs", "React", "useFetcher", "useState", "useEffect", "useMemo", "useCallback", "RebuyClient", "Utilities", "flattenConnection", "useContext", "useEffect", "useMemo", "useRef", "useState", "jsx", "useEffect", "useState", "useCallback", "useEffect", "elements", "useCallback", "useMemo", "useState", "result", "Fragment", "jsx", "jsxs", "Money", "useCart", "Fragment", "jsx", "jsxs", "useCart", "Money", "jsx", "Money", "clsx", "result", "jsx", "jsxs", "price", "compareAtPrice", "Money", "clsx", "useState", "result", "jsx", "useState", "clsx", "useEffect", "useState", "result", "jsx", "useState", "useEffect", "clsx", "clsx", "result", "jsx", "clsx", "result", "jsx", "jsxs", "useState", "useCallback", "product", "useMemo", "useEffect", "useState", "result", "jsx", "jsxs", "useState", "useEffect", "clsx", "useCallback", "useEffect", "useState", "result", "jsx", "jsxs", "useState", "useCallback", "useEffect", "clsx", "result", "jsx", "jsxs", "Fragment", "jsx", "jsxs", "useState", "useRef", "useContext", "useEffect", "RebuyClient", "useMemo", "flattenConnection", "jsx", "React", "useEffect", "useMemo", "useRef", "jsx", "React", "useRef", "useMemo", "useEffect", "clsx", "React", "useCallback", "useEffect", "useMemo", "useRef", "useState", "useFetcher", "useCallback", "useEffect", "useMemo", "useState", "useState", "useMemo", "useEffect", "useCallback", "result", "jsx", "jsxs", "useFetcher", "useState", "useRef", "useMemo", "useCallback", "useEffect", "clsx", "React", "React", "result", "jsx", "React", "React", "useEffect", "useMemo", "useRef", "useEffect", "useState", "z", "useState", "useEffect", "jsx", "jsxs", "React", "useRef", "useMemo", "useEffect", "clsx", "React", "useCallback", "useEffect", "useMemo", "useState", "useFetcher", "useShallow", "clsx", "result", "Fragment", "jsx", "jsxs", "clsx", "jsx", "jsxs", "React", "useFetcher", "useState", "useShallow", "useMemo", "useEffect", "useCallback", "clsx", "jsx", "jsxs", "Fragment", "jsx", "useMemo", "clsx", "useRef", "useEffect", "useState", "result", "jsx", "jsxs", "useRef", "clsx", "clsx", "useRef", "Fragment", "jsx", "jsxs", "useRef", "clsx", "result", "jsx", "jsxs", "useRef", "useMemo", "useCallback", "useEffect", "clsx", "React", "jsx", "RebuyClient", "Utilities", "flattenConnection", "useContext", "useEffect", "useMemo", "useState", "createContext", "useContext", "jsx", "jsx", "useContext", "useState", "useEffect", "RebuyClient", "useMemo", "metadata", "flattenConnection", "result", "jsx", "jsxs", "product", "useCallback", "useEffect", "useState", "Image", "Fragment", "result", "Fragment", "jsx", "jsxs", "Image", "Money", "jsx", "jsxs", "price", "compareAtPrice", "Money", "clsx", "jsx", "product", "jsx", "jsxs", "clsx", "jsx", "jsxs", "useState", "useEffect", "product", "useCallback", "Money", "useCallback", "useEffect", "useState", "Image", "result", "jsx", "jsxs", "Image", "jsx", "jsxs", "useState", "useEffect", "product", "useCallback", "Money", "result", "jsx", "jsxs", "product", "RebuyClient", "Utilities", "useEffect", "useMemo", "useState", "create", "useState", "useMemo", "request", "useEffect", "RebuyClient", "RebuyClient", "flattenConnection", "useContext", "useEffect", "useMemo", "useState", "result", "jsx", "jsxs", "useContext", "useState", "useEffect", "RebuyClient", "useMemo", "metadata", "flattenConnection"]
7
7
  }