'use client'; import { useState } from 'react'; import { Image as ImageIcon } from 'lucide-react'; import { Link } from '@/core/lib/navigation'; import { CdnImage as Image } from '@/ui/shared/cdn-image'; import type { AutomaticRecommendationItem, Product, ProductRecommendation } from 'brainerce'; import { formatPrice } from 'brainerce'; import { useCart, useStoreInfo } from '@/core/providers/store-provider'; import { useCurrency } from '@/core/lib/use-currency'; import { useTranslations } from '@/core/lib/translations'; import { useRecommendationCard } from '@/core/hooks/use-recommendation-tracking'; import { addToCartErrorMessageKey, toAddToCartError, type AddToCartError, } from '@/core/lib/add-to-cart-error'; import { Button } from '@/components/ui/button'; import { Card } from '@/components/ui/card'; import { Checkbox } from '@/components/ui/checkbox'; import { cn } from '@/core/lib/utils'; /** A manual cross-sell or a card of the automatic `bought_together` group. */ type BundleItem = ProductRecommendation | AutomaticRecommendationItem; interface FrequentlyBoughtTogetherProps { items: BundleItem[]; currentProduct: Product; /** * The heading. It comes from WHERE the items came from, never from this * component: manual cross-sells get a neutral title ("Recommended for you"), * only the automatic `bought_together` group is "Frequently bought together". */ title: string; className?: string; /** * Whether the "Frequently bought together" switch hides this block. True (the default) * for the automatic `bought_together` group, which that switch governs. The merchant's * own manual cross-sells pass `false`: a hand-picked list is not "frequently bought * together" and must not disappear because that automatic feature is off. */ respectSwitch?: boolean; } // ⛔ STORE CURRENCY THROUGHOUT, deliberately. The cross-sells are // `ProductRecommendation`, a trimmed shape with no displayPrice/displayCurrency, // so there is nothing to convert them to. Converting only `currentProduct` // (which is a full Product and does carry FX fields) would add a euro amount to // two dollar amounts and print the result as one total. One currency wins, and // it has to be the one the cart actually charges. function getEffectivePrice(item: { basePrice: string; salePrice?: string | null }): number { const sale = item.salePrice ? parseFloat(item.salePrice) : null; const base = parseFloat(item.basePrice); return sale != null && sale < base ? sale : base; } /** * A VARIABLE product with no pinned variation cannot be added by its product id: * the shopper must pick a size or colour first. It never goes into the total or * the add-all button; it links to its product page instead. */ function needsOptions(item: BundleItem): boolean { return ( Boolean(item.requiresVariantSelection) || (item.type === 'VARIABLE' && !item.targetVariantId) ); } function ProductThumb({ name, imageUrl, price, currency, checked, onToggle, disabled, card, href, }: { name: string; imageUrl: string | null; price: number; currency: string; checked: boolean; onToggle?: () => void; disabled?: boolean; /** The recommendation card, for measurement. Absent for the product being viewed. */ card?: BundleItem; /** The card's product page. Absent for the product being viewed. */ href?: string; }) { const { ref, onClick } = useRecommendationCard({ recToken: card?.recToken }); return ( ); } /** A suggestion the shopper must configure first: a link to its page, not a checkbox. */ function ChooseOptionsCard({ item, currency }: { item: BundleItem; currency: string }) { const t = useTranslations('productDetail'); const { ref, onClick } = useRecommendationCard({ recToken: item.recToken }); const img = item.images?.[0]; const imgUrl = img ? (typeof img === 'string' ? img : img.url) : null; return (
{imgUrl ? ( {item.name} ) : (
)}
{item.name} {formatPrice(getEffectivePrice(item), { currency }) as string} {t('chooseOptions')}
); } export function FrequentlyBoughtTogether({ items, currentProduct, title, className, respectSwitch = true, }: FrequentlyBoughtTogetherProps) { // Hooks must be called unconditionally and in the same order on every // render — keep all of them above any early `return null` branch. const { storeInfo } = useStoreInfo(); const { add, dismissMutationError } = useCart(); const t = useTranslations('productDetail'); const currency = useCurrency(); // ⛔ KITs are dropped, not priced. A recommendation is a `ProductRecommendation` // — an UNRESOLVED list shape, and the recommendations endpoint does not resolve // kits, so `item.basePrice` on a kit is the stored PLACEHOLDER, wrong for every // kit priced SUM / SUM_MINUS_PERCENT. This block sums those numbers into one // "Total" beside a button that adds them all, so a wrong figure here is a // number the shopper commits to. Adding a kit by its own `productId` would in // fact be correct — it is the displayed price that cannot be trusted — so a // kit still sells fine from its own product page, where the API resolves it. // Only show up to 3 cards. const visible = items.filter((item) => item.type !== 'KIT').slice(0, 3); // Cards that can be added as they are (a pinned variation is added WITH its variantId), // and cards that need the shopper to choose options first. const pickable = visible.filter((item) => !needsOptions(item)); const optionCards = visible.filter(needsOptions); const [selected, setSelected] = useState>(() => new Set(pickable.map((i) => i.id))); const [adding, setAdding] = useState(false); const [addError, setAddError] = useState(null); // The "Frequently bought together" switch hides the AUTOMATIC group (the server already // withholds it when off). Manual cross-sells opt out with `respectSwitch={false}`. if (respectSwitch && !storeInfo?.upsell?.frequentlyBoughtTogetherEnabled) return null; if (visible.length === 0) return null; const currentPrice = getEffectivePrice(currentProduct); const currentImage = currentProduct.images?.[0]; const currentImageUrl = currentImage ? typeof currentImage === 'string' ? currentImage : currentImage.url : null; const totalPrice = pickable .filter((item) => selected.has(item.id)) .reduce((sum, item) => sum + getEffectivePrice(item), 0); const toggleItem = (id: string) => { setSelected((prev) => { const next = new Set(prev); if (next.has(id)) { next.delete(id); } else { next.add(id); } return next; }); }; async function handleAddAll() { if (adding || selected.size === 0) return; setAddError(null); try { setAdding(true); const selectedItems = pickable.filter((item) => selected.has(item.id)); // One write per product, each awaited, so the first refusal stops the // loop. The store never throws: a refusal comes back in the result. for (const item of selectedItems) { const result = await add({ productId: item.id, // A pinned variation is added as that variation; never a bare variable product. ...(item.targetVariantId ? { variantId: item.targetVariantId } : {}), quantity: 1, // The card's token, so the purchase is attributed to the recommendation. ...(item.recToken ? { recommendationToken: item.recToken } : {}), }); if (!result.ok) { // The loop is not transactional: if the cart hits its 50-line cap // part-way through, the earlier items ARE in the cart and the rest are // not. Saying so beats a silent stop the shopper reads as a dead button. setAddError(toAddToCartError(result.error)); // This block says it; clear the shared slot so a cart-level alert does // not say it a second time. dismissMutationError(); console.error('Failed to add items to cart:', result.error); return; } } } finally { setAdding(false); } } return (

{title}

{/* Current product: shown for context, no checkbox. The shopper adds it with the main add-to-cart button (it may need a size, colour or custom text), so the total below counts only the checked items. */} {pickable.length > 0 && ( )} {pickable.map((item) => { const img = item.images?.[0]; const imgUrl = img ? (typeof img === 'string' ? img : img.url) : null; return (
+ toggleItem(item.id)} card={item} href={`/products/${item.slug || item.id}`} />
); })} {/* Products that need a size, colour or other option: never added blind. */} {optionCards.map((item) => ( ))}
{/* Total + Add button */} {pickable.length > 0 && (
{t('totalPrice', { price: formatPrice(totalPrice, { currency }) as string })}
)} {/* Why the add was refused. Some items may already be in the cart: the loop above adds one at a time and stops at the first refusal. */} {addError && (

{t(addToCartErrorMessageKey(addError))}

)}
); }