@brainerce/mcp-server 2.0.1 → 2.1.1

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.
package/dist/index.js CHANGED
@@ -747,27 +747,109 @@ const nudges: CartNudge[] = await client.getCartNudges(cartId);
747
747
  Display: banners in header, badges on product cards (strikethrough + discounted price), nudges below cart totals, applied discounts as line items in order summary.`;
748
748
  }
749
749
  function getRecommendationsSection() {
750
- return `## Product Recommendations (Cross-Sells & Upsells)
750
+ return `## Product Recommendations & Upsell Features
751
751
 
752
- Recommendations come **embedded in the product response** \u2014 no extra API call needed for product pages.
752
+ ### Relation Types
753
+ - **Cross-sell**: Complementary products ("Bought a phone? Add a case") \u2014 shown on product page + cart
754
+ - **Upsell**: Premium alternatives ("Upgrade to Pro for $20 more") \u2014 shown on product page + cart upgrade banner
755
+ - **Related**: Similar products ("Other shirts in this collection") \u2014 shown on product page
756
+
757
+ ### Product Page Recommendations
758
+ Recommendations come **embedded in the product response** \u2014 no extra API call needed.
753
759
 
754
760
  \`\`\`typescript
755
- import type { ProductRecommendation, ProductRecommendationsResponse, CartRecommendationsResponse } from 'brainerce';
761
+ import type { ProductRecommendation, ProductRecommendationsResponse } from 'brainerce';
756
762
 
757
- // Product page \u2014 recommendations are embedded in the product response
758
763
  const product = await client.getProductBySlug('some-slug');
759
764
  const recs = (product as any).recommendations as ProductRecommendationsResponse | undefined;
760
- // recs?.upsells \u2014 premium alternatives (show on product page)
761
- // recs?.related \u2014 similar products (show at bottom of product page)
762
- // recs?.crossSells \u2014 complementary products (typically used on cart page)
763
765
 
764
- // Cart page \u2014 cross-sell suggestions for cart items (separate call)
765
- const cartRecs: CartRecommendationsResponse = await client.getCartRecommendations(cartId, 4);
766
+ // recs?.crossSells \u2014 complementary products \u2192 "Frequently Bought Together" section
767
+ // recs?.upsells \u2014 premium alternatives \u2192 "Upgrade Your Choice" section
768
+ // recs?.related \u2014 similar products \u2192 "Similar Products" section
769
+ \`\`\`
770
+
771
+ ### Cart Page Features
772
+
773
+ **Cross-sell recommendations** (existing products the customer might also want):
774
+ \`\`\`typescript
775
+ import type { CartRecommendationsResponse } from 'brainerce';
776
+ const cartRecs = await client.getCartRecommendations(cartId, 4);
766
777
  // cartRecs.recommendations \u2014 deduplicated cross-sells (excludes items already in cart)
767
778
  \`\`\`
768
779
 
769
- ProductRecommendation: \`id\`, \`name\`, \`slug\`, \`basePrice\`, \`salePrice\`, \`images\`, \`type\`, \`inventory\`, \`relationType\`.
770
- Display upsells + related on product pages, cross-sells on cart page.`;
780
+ **Cart upgrade banner** (upsell relations with small price delta \u2014 "Upgrade to X for +$Y"):
781
+ \`\`\`typescript
782
+ import type { CartUpgradesResponse } from 'brainerce';
783
+ const { upgrades } = await client.getCartUpgrades(cartId);
784
+ // upgrades is a Record<sourceProductId, { targetProduct, priceDelta, deltaPercent }>
785
+ // Show inline banner per cart item if upgrade exists
786
+ \`\`\`
787
+
788
+ **Bundle offers** (discounted complementary products configured by the store owner):
789
+ \`\`\`typescript
790
+ import type { CartBundlesResponse } from 'brainerce';
791
+ const { bundles } = await client.getCartBundles(cartId);
792
+ // bundles[].bundleProduct \u2014 the product to offer
793
+ // bundles[].originalPrice / bundles[].discountedPrice \u2014 prices
794
+ // bundles[].discountType ('PERCENTAGE' | 'FIXED_AMOUNT') + discountValue
795
+
796
+ // Add a bundle to cart (applies the discount automatically):
797
+ await client.addBundleToCart(cartId, bundleOfferId);
798
+ // Remove a bundle from cart:
799
+ await client.removeBundleFromCart(cartId, bundleOfferId);
800
+ // Detect already-added bundles: check cart.items for metadata?.isBundleItem === true
801
+ \`\`\`
802
+
803
+ **Free shipping progress bar** (configured threshold in channel settings):
804
+ \`\`\`typescript
805
+ const { storeInfo } = useStoreInfo(); // from store provider
806
+ const threshold = storeInfo?.upsell?.freeShippingThreshold;
807
+ const subtotal = parseFloat(cart.subtotal);
808
+ const remaining = threshold ? threshold - subtotal : 0;
809
+ const qualified = threshold ? subtotal >= threshold : false;
810
+ // Show progress bar: remaining > 0 ? "You're $X away from free shipping!" : "You've got free shipping!"
811
+ \`\`\`
812
+
813
+ ### Checkout Features
814
+
815
+ **Order bumps** (one-click add-ons at checkout):
816
+ \`\`\`typescript
817
+ import type { CheckoutBumpsResponse } from 'brainerce';
818
+ const { bumps } = await client.getCheckoutBumps(checkoutId);
819
+ // bumps[].bumpProduct \u2014 product to offer
820
+ // bumps[].originalPrice / discountedPrice \u2014 with optional discount
821
+ // bumps[].title / description \u2014 display text
822
+
823
+ // Add a bump to cart:
824
+ await client.addOrderBump(cartId, bumpId);
825
+ // Remove a bump:
826
+ await client.removeOrderBump(cartId, bumpId);
827
+ // Detect already-added bumps: check cart.items for metadata?.isOrderBump === true
828
+ \`\`\`
829
+
830
+ ### Feature Flags (per-channel)
831
+ All upsell features are controlled by \`storeInfo.upsell.*\`:
832
+ - \`freeShippingBarEnabled\` \u2014 free shipping progress bar in cart
833
+ - \`frequentlyBoughtTogetherEnabled\` \u2014 cross-sell section on product page
834
+ - \`cartUpgradeBannerEnabled\` \u2014 upgrade banner per cart item
835
+ - \`cartBundleEnabled\` \u2014 bundle offers in cart
836
+ - \`checkoutOrderBumpEnabled\` \u2014 order bumps at checkout
837
+ - \`freeShippingThreshold\` \u2014 threshold amount for free shipping bar
838
+
839
+ Always check the flag before rendering: \`if (storeInfo?.upsell?.featureName !== false)\`
840
+
841
+ ### Components Reference
842
+ | Component | Location | Purpose |
843
+ |-----------|----------|---------|
844
+ | FrequentlyBoughtTogether | products/ | Cross-sells with "Add all to cart" on product page |
845
+ | RecommendationSection | products/ | Grid of upsells or related products on product page |
846
+ | CartRecommendationSection | products/ | Cross-sell grid at bottom of cart page |
847
+ | FreeShippingBar | cart/ | Progress bar toward free shipping threshold |
848
+ | CartUpgradeBanner | cart/ | Inline "Upgrade to X for +$Y" per cart item |
849
+ | CartBundleOfferCard | cart/ | Discounted bundle offer card in cart |
850
+ | OrderBumpCard | checkout/ | Checkbox add-on card in checkout sidebar |
851
+
852
+ ProductRecommendation: \`id\`, \`name\`, \`slug\`, \`basePrice\`, \`salePrice\`, \`images\`, \`type\`, \`inventory\`, \`relationType\`.`;
771
853
  }
772
854
  function getInventorySection() {
773
855
  return `## Inventory, Stock Display & Reservation Countdown
@@ -2940,13 +3022,21 @@ export default async function ProductDetailPage({ params }: Props) {
2940
3022
 
2941
3023
  import { useEffect, useState } from 'react';
2942
3024
  import Link from 'next/link';
2943
- import type { CartRecommendationsResponse } from 'brainerce';
3025
+ import type {
3026
+ CartRecommendationsResponse,
3027
+ CartUpgradesResponse,
3028
+ CartBundlesResponse,
3029
+ } from 'brainerce';
2944
3030
  import { getClient } from '@/lib/brainerce';
2945
3031
  import { useCart } from '@/providers/store-provider';
3032
+ import { useStoreInfo } from '@/providers/store-provider';
2946
3033
  import { CartItem } from '@/components/cart/cart-item';
3034
+ import { CartUpgradeBanner } from '@/components/cart/cart-upgrade-banner';
3035
+ import { CartBundleOfferCard } from '@/components/cart/cart-bundle-offer';
2947
3036
  import { CartSummary } from '@/components/cart/cart-summary';
2948
3037
  import { CouponInput } from '@/components/cart/coupon-input';
2949
3038
  import { CartNudges } from '@/components/cart/cart-nudges';
3039
+ import { FreeShippingBar } from '@/components/cart/free-shipping-bar';
2950
3040
  import { ReservationCountdown } from '@/components/cart/reservation-countdown';
2951
3041
  import { CartRecommendationSection } from '@/components/products/recommendation-section';
2952
3042
  import { LoadingSpinner } from '@/components/shared/loading-spinner';
@@ -2954,9 +3044,12 @@ import { useTranslations } from '@/lib/translations';
2954
3044
 
2955
3045
  export default function CartPage() {
2956
3046
  const { cart, cartLoading, refreshCart, itemCount } = useCart();
3047
+ const { storeInfo } = useStoreInfo();
2957
3048
  const t = useTranslations('cart');
2958
3049
  const tc = useTranslations('common');
2959
3050
  const [cartRecs, setCartRecs] = useState<CartRecommendationsResponse | null>(null);
3051
+ const [upgrades, setUpgrades] = useState<CartUpgradesResponse | null>(null);
3052
+ const [bundles, setBundles] = useState<CartBundlesResponse | null>(null);
2960
3053
 
2961
3054
  // Load cross-sell recommendations when cart changes
2962
3055
  useEffect(() => {
@@ -2971,6 +3064,36 @@ export default function CartPage() {
2971
3064
  .catch(() => {});
2972
3065
  }, [cart?.id, cart?.items.length]);
2973
3066
 
3067
+ // Load upgrade suggestions when cart changes
3068
+ useEffect(() => {
3069
+ if (
3070
+ !cart?.id ||
3071
+ cart.items.length === 0 ||
3072
+ storeInfo?.upsell?.cartUpgradeBannerEnabled === false
3073
+ ) {
3074
+ setUpgrades(null);
3075
+ return;
3076
+ }
3077
+ const client = getClient();
3078
+ client
3079
+ .getCartUpgrades(cart.id)
3080
+ .then(setUpgrades)
3081
+ .catch(() => {});
3082
+ }, [cart?.id, cart?.items.length, storeInfo?.upsell?.cartUpgradeBannerEnabled]);
3083
+
3084
+ // Load bundle offers when cart changes
3085
+ useEffect(() => {
3086
+ if (!cart?.id || cart.items.length === 0 || storeInfo?.upsell?.cartBundleEnabled === false) {
3087
+ setBundles(null);
3088
+ return;
3089
+ }
3090
+ const client = getClient();
3091
+ client
3092
+ .getCartBundles(cart.id)
3093
+ .then(setBundles)
3094
+ .catch(() => {});
3095
+ }, [cart?.id, cart?.items.length, storeInfo?.upsell?.cartBundleEnabled]);
3096
+
2974
3097
  if (cartLoading) {
2975
3098
  return (
2976
3099
  <div className="flex min-h-[60vh] items-center justify-center">
@@ -3030,10 +3153,30 @@ export default function CartPage() {
3030
3153
  {/* Cart items */}
3031
3154
  <div>
3032
3155
  {cart.items.map((item) => (
3033
- <CartItem key={item.id} item={item} onUpdate={refreshCart} />
3156
+ <div key={item.id}>
3157
+ <CartItem item={item} onUpdate={refreshCart} />
3158
+ {upgrades?.upgrades?.[item.productId] && (
3159
+ <CartUpgradeBanner
3160
+ suggestion={upgrades.upgrades[item.productId]}
3161
+ cartItem={item}
3162
+ onUpgrade={refreshCart}
3163
+ className="mb-2 ms-24"
3164
+ />
3165
+ )}
3166
+ </div>
3034
3167
  ))}
3035
3168
  </div>
3036
3169
 
3170
+ {/* Bundle offers */}
3171
+ {bundles?.bundles && bundles.bundles.length > 0 && (
3172
+ <div className="mt-6 space-y-3">
3173
+ <h3 className="text-foreground text-sm font-semibold">{t('bundleOffers')}</h3>
3174
+ {bundles.bundles.map((offer) => (
3175
+ <CartBundleOfferCard key={offer.id} offer={offer} onAdd={refreshCart} />
3176
+ ))}
3177
+ </div>
3178
+ )}
3179
+
3037
3180
  {/* Coupon input */}
3038
3181
  <div className="border-border mt-6 border-t pt-4">
3039
3182
  <CouponInput cart={cart} onUpdate={refreshCart} />
@@ -3043,6 +3186,7 @@ export default function CartPage() {
3043
3186
  {/* Summary sidebar */}
3044
3187
  <div className="lg:col-span-1">
3045
3188
  <div className="bg-muted/50 border-border sticky top-24 rounded-lg border p-6">
3189
+ <FreeShippingBar className="mb-4" />
3046
3190
  <CartSummary />
3047
3191
 
3048
3192
  <Link
@@ -3086,6 +3230,7 @@ import type {
3086
3230
  SetShippingAddressDto,
3087
3231
  ShippingDestinations,
3088
3232
  PickupLocation,
3233
+ CheckoutBumpsResponse,
3089
3234
  } from 'brainerce';
3090
3235
  import { formatPrice } from 'brainerce';
3091
3236
  import { getClient } from '@/lib/brainerce';
@@ -3096,6 +3241,7 @@ import { PaymentStep } from '@/components/checkout/payment-step';
3096
3241
  import { DeliveryMethodStep } from '@/components/checkout/delivery-method-step';
3097
3242
  import { PickupStep } from '@/components/checkout/pickup-step';
3098
3243
  import { TaxDisplay } from '@/components/checkout/tax-display';
3244
+ import { OrderBumpCard } from '@/components/checkout/order-bump-card';
3099
3245
  import { CouponInput } from '@/components/cart/coupon-input';
3100
3246
  import { ReservationCountdown } from '@/components/cart/reservation-countdown';
3101
3247
  import { LoadingSpinner } from '@/components/shared/loading-spinner';
@@ -3132,6 +3278,9 @@ function CheckoutContent() {
3132
3278
  phone?: string;
3133
3279
  } | null>(null);
3134
3280
  const [hasSavedAddress, setHasSavedAddress] = useState(false);
3281
+ const [orderBumps, setOrderBumps] = useState<CheckoutBumpsResponse | null>(null);
3282
+ const [addedBumpIds, setAddedBumpIds] = useState<Set<string>>(new Set());
3283
+ const [bumpLoading, setBumpLoading] = useState<string | null>(null);
3135
3284
 
3136
3285
  // Check for returning from canceled payment
3137
3286
  const canceled = searchParams.get('canceled') === 'true';
@@ -3234,9 +3383,59 @@ function CheckoutContent() {
3234
3383
  };
3235
3384
 
3236
3385
  initCheckout();
3237
- // eslint-disable-next-line react-hooks/exhaustive-deps
3238
3386
  }, [cart?.id, existingCheckoutId]);
3239
3387
 
3388
+ // Load order bumps when checkout is available
3389
+ useEffect(() => {
3390
+ if (!checkout?.id || storeInfo?.upsell?.checkoutOrderBumpEnabled === false) {
3391
+ setOrderBumps(null);
3392
+ return;
3393
+ }
3394
+ const client = getClient();
3395
+ client
3396
+ .getCheckoutBumps(checkout.id)
3397
+ .then((data) => {
3398
+ setOrderBumps(data);
3399
+ // Detect already-added bumps from cart
3400
+ if (cart?.items) {
3401
+ const existingBumpIds = new Set<string>();
3402
+ for (const item of cart.items) {
3403
+ const meta = item.metadata as Record<string, unknown> | undefined;
3404
+ if (meta?.isOrderBump && meta?.orderBumpId) {
3405
+ existingBumpIds.add(meta.orderBumpId as string);
3406
+ }
3407
+ }
3408
+ setAddedBumpIds(existingBumpIds);
3409
+ }
3410
+ })
3411
+ .catch(() => {});
3412
+ }, [checkout?.id, storeInfo?.upsell?.checkoutOrderBumpEnabled]);
3413
+
3414
+ // Handle bump toggle
3415
+ async function handleBumpToggle(bumpId: string, add: boolean) {
3416
+ if (!cart?.id || bumpLoading) return;
3417
+ try {
3418
+ setBumpLoading(bumpId);
3419
+ const client = getClient();
3420
+ if (add) {
3421
+ await client.addOrderBump(cart.id, bumpId);
3422
+ setAddedBumpIds((prev) => new Set([...prev, bumpId]));
3423
+ } else {
3424
+ await client.removeOrderBump(cart.id, bumpId);
3425
+ setAddedBumpIds((prev) => {
3426
+ const next = new Set(prev);
3427
+ next.delete(bumpId);
3428
+ return next;
3429
+ });
3430
+ }
3431
+ await refreshCart();
3432
+ } catch (err) {
3433
+ console.error('Failed to toggle order bump:', err);
3434
+ } finally {
3435
+ setBumpLoading(null);
3436
+ }
3437
+ }
3438
+
3240
3439
  // Handle shipping address submission
3241
3440
  async function handleAddressSubmit(
3242
3441
  address: SetShippingAddressDto,
@@ -3739,6 +3938,24 @@ function CheckoutContent() {
3739
3938
  )
3740
3939
  )}
3741
3940
 
3941
+ {/* Order bumps */}
3942
+ {orderBumps?.bumps && orderBumps.bumps.length > 0 && (
3943
+ <div className="border-border space-y-2 border-t pt-4">
3944
+ <p className="text-foreground text-xs font-semibold uppercase tracking-wide">
3945
+ {t('addToYourOrder')}
3946
+ </p>
3947
+ {orderBumps.bumps.map((bump) => (
3948
+ <OrderBumpCard
3949
+ key={bump.id}
3950
+ bump={bump}
3951
+ isAdded={addedBumpIds.has(bump.id)}
3952
+ onToggle={handleBumpToggle}
3953
+ loading={bumpLoading === bump.id}
3954
+ />
3955
+ ))}
3956
+ </div>
3957
+ )}
3958
+
3742
3959
  {/* Coupon input \u2014 show from shipping/pickup step onwards (or immediately if digital) */}
3743
3960
  {cart &&
3744
3961
  (isAllDigital || step === 'shipping' || step === 'pickup' || step === 'payment') && (
@@ -9210,6 +9427,719 @@ export function LoadingSpinner({ size = 'md', className }: LoadingSpinnerProps)
9210
9427
  </div>
9211
9428
  );
9212
9429
  }
9430
+ `,
9431
+ "src/components/products/recommendation-section.tsx": `'use client';
9432
+
9433
+ import { useEffect, useState } from 'react';
9434
+ import Link from 'next/link';
9435
+ import Image from 'next/image';
9436
+ import type { ProductRecommendation } from 'brainerce';
9437
+ import { PriceDisplay } from '@/components/shared/price-display';
9438
+ import { cn } from '@/lib/utils';
9439
+
9440
+ interface RecommendationCardProps {
9441
+ item: ProductRecommendation;
9442
+ className?: string;
9443
+ }
9444
+
9445
+ function RecommendationCard({ item, className }: RecommendationCardProps) {
9446
+ const firstImage = item.images?.[0];
9447
+ const imageUrl = typeof firstImage === 'string' ? firstImage : firstImage?.url || null;
9448
+ const slug = item.slug || item.id;
9449
+ const basePrice = parseFloat(item.basePrice);
9450
+ const salePrice = item.salePrice ? parseFloat(item.salePrice) : undefined;
9451
+ const isOnSale = salePrice != null && salePrice < basePrice;
9452
+
9453
+ return (
9454
+ <Link
9455
+ href={\`/products/\${slug}\`}
9456
+ className={cn(
9457
+ 'border-border bg-background group block overflow-hidden rounded-lg border transition-shadow hover:shadow-md',
9458
+ className
9459
+ )}
9460
+ >
9461
+ <div className="bg-muted relative aspect-square overflow-hidden">
9462
+ {imageUrl ? (
9463
+ <Image
9464
+ src={imageUrl}
9465
+ alt={item.name}
9466
+ fill
9467
+ sizes="(max-width: 640px) 50vw, (max-width: 1024px) 33vw, 20vw"
9468
+ className="object-cover transition-transform duration-300 group-hover:scale-105"
9469
+ />
9470
+ ) : (
9471
+ <div className="text-muted-foreground absolute inset-0 flex items-center justify-center">
9472
+ <svg className="h-10 w-10" fill="none" viewBox="0 0 24 24" stroke="currentColor">
9473
+ <path
9474
+ strokeLinecap="round"
9475
+ strokeLinejoin="round"
9476
+ strokeWidth={1.5}
9477
+ d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
9478
+ />
9479
+ </svg>
9480
+ </div>
9481
+ )}
9482
+ </div>
9483
+ <div className="space-y-1.5 p-3">
9484
+ <h3 className="text-foreground group-hover:text-primary line-clamp-2 text-sm font-medium transition-colors">
9485
+ {item.name}
9486
+ </h3>
9487
+ <PriceDisplay price={basePrice} salePrice={isOnSale ? salePrice : undefined} size="sm" />
9488
+ </div>
9489
+ </Link>
9490
+ );
9491
+ }
9492
+
9493
+ interface RecommendationSectionProps {
9494
+ title: string;
9495
+ items: ProductRecommendation[];
9496
+ className?: string;
9497
+ }
9498
+
9499
+ export function RecommendationSection({ title, items, className }: RecommendationSectionProps) {
9500
+ if (items.length === 0) return null;
9501
+
9502
+ return (
9503
+ <div className={cn('', className)}>
9504
+ <h2 className="text-foreground mb-4 text-xl font-semibold">{title}</h2>
9505
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
9506
+ {items.map((item) => (
9507
+ <RecommendationCard key={item.id} item={item} />
9508
+ ))}
9509
+ </div>
9510
+ </div>
9511
+ );
9512
+ }
9513
+
9514
+ interface CartRecommendationSectionProps {
9515
+ title: string;
9516
+ items: ProductRecommendation[];
9517
+ className?: string;
9518
+ }
9519
+
9520
+ export function CartRecommendationSection({
9521
+ title,
9522
+ items,
9523
+ className,
9524
+ }: CartRecommendationSectionProps) {
9525
+ if (items.length === 0) return null;
9526
+
9527
+ return (
9528
+ <div className={cn('', className)}>
9529
+ <h2 className="text-foreground mb-4 text-lg font-semibold">{title}</h2>
9530
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
9531
+ {items.map((item) => (
9532
+ <RecommendationCard key={item.id} item={item} />
9533
+ ))}
9534
+ </div>
9535
+ </div>
9536
+ );
9537
+ }
9538
+ `,
9539
+ "src/components/products/frequently-bought-together.tsx": `'use client';
9540
+
9541
+ import { useState } from 'react';
9542
+ import Image from 'next/image';
9543
+ import type { Product, ProductRecommendation } from 'brainerce';
9544
+ import { formatPrice } from 'brainerce';
9545
+ import { useCart } from '@/providers/store-provider';
9546
+ import { useStoreInfo } from '@/providers/store-provider';
9547
+ import { useTranslations } from '@/lib/translations';
9548
+ import { cn } from '@/lib/utils';
9549
+
9550
+ interface FrequentlyBoughtTogetherProps {
9551
+ items: ProductRecommendation[];
9552
+ currentProduct: Product;
9553
+ className?: string;
9554
+ }
9555
+
9556
+ function getEffectivePrice(item: { basePrice: string; salePrice?: string | null }): number {
9557
+ const sale = item.salePrice ? parseFloat(item.salePrice) : null;
9558
+ const base = parseFloat(item.basePrice);
9559
+ return sale != null && sale < base ? sale : base;
9560
+ }
9561
+
9562
+ function ProductThumb({
9563
+ name,
9564
+ imageUrl,
9565
+ price,
9566
+ currency,
9567
+ checked,
9568
+ onToggle,
9569
+ disabled,
9570
+ }: {
9571
+ name: string;
9572
+ imageUrl: string | null;
9573
+ price: number;
9574
+ currency: string;
9575
+ checked: boolean;
9576
+ onToggle?: () => void;
9577
+ disabled?: boolean;
9578
+ }) {
9579
+ return (
9580
+ <label
9581
+ className={cn(
9582
+ 'border-border bg-background relative flex cursor-pointer flex-col items-center rounded-lg border p-3 transition-all',
9583
+ checked ? 'ring-primary ring-2' : 'opacity-60',
9584
+ disabled && 'pointer-events-none'
9585
+ )}
9586
+ >
9587
+ {onToggle && (
9588
+ <input
9589
+ type="checkbox"
9590
+ checked={checked}
9591
+ onChange={onToggle}
9592
+ className="absolute start-2 top-2 h-4 w-4 rounded"
9593
+ />
9594
+ )}
9595
+ <div className="bg-muted relative mb-2 h-20 w-20 overflow-hidden rounded">
9596
+ {imageUrl ? (
9597
+ <Image src={imageUrl} alt={name} fill sizes="80px" className="object-cover" />
9598
+ ) : (
9599
+ <div className="flex h-full w-full items-center justify-center">
9600
+ <svg
9601
+ className="text-muted-foreground h-8 w-8"
9602
+ fill="none"
9603
+ viewBox="0 0 24 24"
9604
+ stroke="currentColor"
9605
+ >
9606
+ <path
9607
+ strokeLinecap="round"
9608
+ strokeLinejoin="round"
9609
+ strokeWidth={1.5}
9610
+ d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
9611
+ />
9612
+ </svg>
9613
+ </div>
9614
+ )}
9615
+ </div>
9616
+ <span className="text-foreground line-clamp-2 text-center text-xs font-medium">{name}</span>
9617
+ <span className="text-muted-foreground mt-1 text-xs">
9618
+ {formatPrice(price, { currency }) as string}
9619
+ </span>
9620
+ </label>
9621
+ );
9622
+ }
9623
+
9624
+ export function FrequentlyBoughtTogether({
9625
+ items,
9626
+ currentProduct,
9627
+ className,
9628
+ }: FrequentlyBoughtTogetherProps) {
9629
+ const { storeInfo } = useStoreInfo();
9630
+ const { refreshCart } = useCart();
9631
+ const t = useTranslations('productDetail');
9632
+
9633
+ // Only show up to 3 cross-sells
9634
+ const crossSells = items.slice(0, 3);
9635
+
9636
+ const [selected, setSelected] = useState<Set<string>>(() => new Set(crossSells.map((i) => i.id)));
9637
+ const [adding, setAdding] = useState(false);
9638
+
9639
+ if (!storeInfo?.upsell?.frequentlyBoughtTogetherEnabled) return null;
9640
+ if (crossSells.length === 0) return null;
9641
+
9642
+ const currency = storeInfo.currency || 'USD';
9643
+
9644
+ const currentPrice = getEffectivePrice(currentProduct);
9645
+ const currentImage = currentProduct.images?.[0];
9646
+ const currentImageUrl = currentImage
9647
+ ? typeof currentImage === 'string'
9648
+ ? currentImage
9649
+ : currentImage.url
9650
+ : null;
9651
+
9652
+ const totalPrice = crossSells
9653
+ .filter((item) => selected.has(item.id))
9654
+ .reduce((sum, item) => sum + getEffectivePrice(item), currentPrice);
9655
+
9656
+ const toggleItem = (id: string) => {
9657
+ setSelected((prev) => {
9658
+ const next = new Set(prev);
9659
+ if (next.has(id)) {
9660
+ next.delete(id);
9661
+ } else {
9662
+ next.add(id);
9663
+ }
9664
+ return next;
9665
+ });
9666
+ };
9667
+
9668
+ async function handleAddAll() {
9669
+ if (adding || selected.size === 0) return;
9670
+ try {
9671
+ setAdding(true);
9672
+ const { getClient } = await import('@/lib/brainerce');
9673
+ const client = getClient();
9674
+ const selectedItems = crossSells.filter((item) => selected.has(item.id));
9675
+ for (const item of selectedItems) {
9676
+ await client.smartAddToCart({ productId: item.id, quantity: 1 });
9677
+ }
9678
+ await refreshCart();
9679
+ } catch (err) {
9680
+ console.error('Failed to add items to cart:', err);
9681
+ } finally {
9682
+ setAdding(false);
9683
+ }
9684
+ }
9685
+
9686
+ return (
9687
+ <div className={cn('border-border rounded-lg border p-6', className)}>
9688
+ <h2 className="text-foreground mb-4 text-xl font-semibold">
9689
+ {t('frequentlyBoughtTogether')}
9690
+ </h2>
9691
+
9692
+ <div className="flex flex-wrap items-center gap-3">
9693
+ {/* Current product (always included, no checkbox) */}
9694
+ <ProductThumb
9695
+ name={currentProduct.name}
9696
+ imageUrl={currentImageUrl}
9697
+ price={currentPrice}
9698
+ currency={currency}
9699
+ checked={true}
9700
+ disabled
9701
+ />
9702
+
9703
+ {crossSells.map((item) => {
9704
+ const img = item.images?.[0];
9705
+ const imgUrl = img ? (typeof img === 'string' ? img : img.url) : null;
9706
+ return (
9707
+ <div key={item.id} className="flex items-center gap-3">
9708
+ <span className="text-muted-foreground text-lg font-light">+</span>
9709
+ <ProductThumb
9710
+ name={item.name}
9711
+ imageUrl={imgUrl}
9712
+ price={getEffectivePrice(item)}
9713
+ currency={currency}
9714
+ checked={selected.has(item.id)}
9715
+ onToggle={() => toggleItem(item.id)}
9716
+ />
9717
+ </div>
9718
+ );
9719
+ })}
9720
+ </div>
9721
+
9722
+ {/* Total + Add button */}
9723
+ <div className="mt-4 flex flex-wrap items-center gap-4">
9724
+ <span className="text-foreground text-lg font-semibold">
9725
+ {t('totalPrice', { price: formatPrice(totalPrice, { currency }) as string })}
9726
+ </span>
9727
+ <button
9728
+ onClick={handleAddAll}
9729
+ disabled={adding || selected.size === 0}
9730
+ className={cn(
9731
+ 'bg-primary text-primary-foreground rounded px-5 py-2.5 text-sm font-medium transition-opacity hover:opacity-90',
9732
+ 'disabled:cursor-not-allowed disabled:opacity-50'
9733
+ )}
9734
+ >
9735
+ {adding ? t('addingAll') : t('addSelectedToCart')}
9736
+ </button>
9737
+ </div>
9738
+ </div>
9739
+ );
9740
+ }
9741
+ `,
9742
+ "src/components/cart/free-shipping-bar.tsx": `'use client';
9743
+
9744
+ import { formatPrice } from 'brainerce';
9745
+ import { useStoreInfo, useCart } from '@/providers/store-provider';
9746
+ import { useTranslations } from '@/lib/translations';
9747
+ import { cn } from '@/lib/utils';
9748
+
9749
+ interface FreeShippingBarProps {
9750
+ className?: string;
9751
+ }
9752
+
9753
+ export function FreeShippingBar({ className }: FreeShippingBarProps) {
9754
+ const t = useTranslations('cart');
9755
+ const { storeInfo } = useStoreInfo();
9756
+ const { totals } = useCart();
9757
+
9758
+ const upsell = storeInfo?.upsell;
9759
+ const threshold = upsell?.freeShippingThreshold;
9760
+ const enabled = upsell?.freeShippingBarEnabled !== false;
9761
+
9762
+ // Don't render if disabled or no threshold configured
9763
+ if (!enabled || !threshold || threshold <= 0) return null;
9764
+
9765
+ const subtotal = totals.subtotal;
9766
+ const remaining = Math.max(0, threshold - subtotal);
9767
+ const progress = Math.min(100, (subtotal / threshold) * 100);
9768
+ const qualified = remaining <= 0;
9769
+ const currency = storeInfo?.currency || 'USD';
9770
+
9771
+ // Don't show if already qualified
9772
+ if (qualified) {
9773
+ return (
9774
+ <div className={cn('rounded-lg border border-green-200 bg-green-50 p-3', className)}>
9775
+ <div className="flex items-center gap-2 text-sm font-medium text-green-700">
9776
+ <svg className="h-4 w-4 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
9777
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
9778
+ </svg>
9779
+ {t('freeShippingQualified')}
9780
+ </div>
9781
+ </div>
9782
+ );
9783
+ }
9784
+
9785
+ return (
9786
+ <div className={cn('rounded-lg border border-amber-200 bg-amber-50 p-3', className)}>
9787
+ <p className="mb-2 text-sm text-amber-800">
9788
+ {t('freeShippingRemaining', {
9789
+ amount: formatPrice(remaining, { currency }) as string,
9790
+ })}
9791
+ </p>
9792
+ <div className="h-2 w-full overflow-hidden rounded-full bg-amber-200">
9793
+ <div
9794
+ className="h-full rounded-full bg-amber-500 transition-all duration-500 ease-out"
9795
+ style={{ width: \`\${progress}%\` }}
9796
+ />
9797
+ </div>
9798
+ </div>
9799
+ );
9800
+ }
9801
+ `,
9802
+ "src/components/cart/cart-upgrade-banner.tsx": `'use client';
9803
+
9804
+ import { useState, useEffect } from 'react';
9805
+ import Image from 'next/image';
9806
+ import type { CartUpgradeSuggestion, CartItem as CartItemType } from 'brainerce';
9807
+ import { formatPrice } from 'brainerce';
9808
+ import { getClient } from '@/lib/brainerce';
9809
+ import { useStoreInfo } from '@/providers/store-provider';
9810
+ import { useTranslations } from '@/lib/translations';
9811
+ import { cn } from '@/lib/utils';
9812
+
9813
+ interface CartUpgradeBannerProps {
9814
+ suggestion: CartUpgradeSuggestion;
9815
+ cartItem: CartItemType;
9816
+ onUpgrade: () => void;
9817
+ className?: string;
9818
+ }
9819
+
9820
+ export function CartUpgradeBanner({
9821
+ suggestion,
9822
+ cartItem,
9823
+ onUpgrade,
9824
+ className,
9825
+ }: CartUpgradeBannerProps) {
9826
+ const { storeInfo } = useStoreInfo();
9827
+ const t = useTranslations('cart');
9828
+ const currency = storeInfo?.currency || 'USD';
9829
+ const [upgrading, setUpgrading] = useState(false);
9830
+ const [dismissed, setDismissed] = useState(false);
9831
+
9832
+ const storageKey = \`dismissed_upgrade_\${suggestion.sourceProductId}\`;
9833
+
9834
+ useEffect(() => {
9835
+ try {
9836
+ if (sessionStorage.getItem(storageKey)) {
9837
+ setDismissed(true);
9838
+ }
9839
+ } catch {
9840
+ /* ignore */
9841
+ }
9842
+ }, [storageKey]);
9843
+
9844
+ if (dismissed) return null;
9845
+
9846
+ const target = suggestion.targetProduct;
9847
+ const firstImage = target.images?.[0];
9848
+ const imageUrl = firstImage
9849
+ ? typeof firstImage === 'string'
9850
+ ? firstImage
9851
+ : firstImage.url
9852
+ : null;
9853
+ const formattedDelta = formatPrice(parseFloat(suggestion.priceDelta), { currency }) as string;
9854
+
9855
+ function handleDismiss() {
9856
+ try {
9857
+ sessionStorage.setItem(storageKey, '1');
9858
+ } catch {
9859
+ /* ignore */
9860
+ }
9861
+ setDismissed(true);
9862
+ }
9863
+
9864
+ async function handleUpgrade() {
9865
+ if (upgrading) return;
9866
+ try {
9867
+ setUpgrading(true);
9868
+ const client = getClient();
9869
+ await client.smartRemoveFromCart(cartItem.productId, cartItem.variantId || undefined);
9870
+ await client.smartAddToCart({ productId: target.id, quantity: cartItem.quantity });
9871
+ onUpgrade();
9872
+ } catch (err) {
9873
+ console.error('Failed to upgrade cart item:', err);
9874
+ } finally {
9875
+ setUpgrading(false);
9876
+ }
9877
+ }
9878
+
9879
+ return (
9880
+ <div
9881
+ className={cn(
9882
+ 'bg-primary/5 border-primary/20 relative flex items-center gap-3 rounded-lg border px-4 py-3',
9883
+ className
9884
+ )}
9885
+ >
9886
+ {/* Dismiss button */}
9887
+ <button
9888
+ type="button"
9889
+ onClick={handleDismiss}
9890
+ className="text-muted-foreground hover:text-foreground absolute end-2 top-2 text-xs"
9891
+ aria-label={t('dismissUpgrade')}
9892
+ >
9893
+ <svg
9894
+ className="h-4 w-4"
9895
+ fill="none"
9896
+ viewBox="0 0 24 24"
9897
+ stroke="currentColor"
9898
+ strokeWidth={2}
9899
+ >
9900
+ <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
9901
+ </svg>
9902
+ </button>
9903
+
9904
+ {/* Product image */}
9905
+ <div className="bg-muted relative h-12 w-12 flex-shrink-0 overflow-hidden rounded">
9906
+ {imageUrl ? (
9907
+ <Image src={imageUrl} alt={target.name} fill sizes="48px" className="object-cover" />
9908
+ ) : (
9909
+ <div className="text-muted-foreground flex h-full w-full items-center justify-center">
9910
+ <svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
9911
+ <path
9912
+ strokeLinecap="round"
9913
+ strokeLinejoin="round"
9914
+ strokeWidth={1.5}
9915
+ d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
9916
+ />
9917
+ </svg>
9918
+ </div>
9919
+ )}
9920
+ </div>
9921
+
9922
+ {/* Text */}
9923
+ <div className="min-w-0 flex-1">
9924
+ <p className="text-foreground text-sm font-medium">
9925
+ {t('upgradeFor', { name: target.name, amount: formattedDelta })}
9926
+ </p>
9927
+ </div>
9928
+
9929
+ {/* Upgrade button */}
9930
+ <button
9931
+ type="button"
9932
+ onClick={handleUpgrade}
9933
+ disabled={upgrading}
9934
+ className={cn(
9935
+ 'bg-primary text-primary-foreground flex-shrink-0 rounded px-3 py-1.5 text-xs font-medium transition-opacity hover:opacity-90',
9936
+ 'disabled:cursor-not-allowed disabled:opacity-50'
9937
+ )}
9938
+ >
9939
+ {upgrading ? t('upgrading') : t('upgrade')}
9940
+ </button>
9941
+ </div>
9942
+ );
9943
+ }
9944
+ `,
9945
+ "src/components/cart/cart-bundle-offer.tsx": `'use client';
9946
+
9947
+ import { useState } from 'react';
9948
+ import Image from 'next/image';
9949
+ import type { CartBundleOffer as CartBundleOfferType } from 'brainerce';
9950
+ import { formatPrice } from 'brainerce';
9951
+ import { getClient } from '@/lib/brainerce';
9952
+ import { useStoreInfo } from '@/providers/store-provider';
9953
+ import { useTranslations } from '@/lib/translations';
9954
+ import { cn } from '@/lib/utils';
9955
+
9956
+ interface CartBundleOfferCardProps {
9957
+ offer: CartBundleOfferType;
9958
+ onAdd: () => void;
9959
+ className?: string;
9960
+ }
9961
+
9962
+ export function CartBundleOfferCard({ offer, onAdd, className }: CartBundleOfferCardProps) {
9963
+ const { storeInfo } = useStoreInfo();
9964
+ const t = useTranslations('cart');
9965
+ const currency = storeInfo?.currency || 'USD';
9966
+ const [adding, setAdding] = useState(false);
9967
+
9968
+ const product = offer.bundleProduct;
9969
+ const firstImage = product.images?.[0];
9970
+ const imageUrl = firstImage
9971
+ ? typeof firstImage === 'string'
9972
+ ? firstImage
9973
+ : firstImage.url
9974
+ : null;
9975
+ const originalPrice = parseFloat(offer.originalPrice);
9976
+ const discountedPrice = parseFloat(offer.discountedPrice);
9977
+ const discountLabel =
9978
+ offer.discountType === 'PERCENTAGE'
9979
+ ? \`\${offer.discountValue}%\`
9980
+ : (formatPrice(parseFloat(offer.discountValue), { currency }) as string);
9981
+
9982
+ async function handleAdd() {
9983
+ if (adding) return;
9984
+ try {
9985
+ setAdding(true);
9986
+ const client = getClient();
9987
+ await client.smartAddToCart({
9988
+ productId: product.id,
9989
+ variantId: offer.bundleVariantId || undefined,
9990
+ quantity: 1,
9991
+ });
9992
+ onAdd();
9993
+ } catch (err) {
9994
+ console.error('Failed to add bundle item:', err);
9995
+ } finally {
9996
+ setAdding(false);
9997
+ }
9998
+ }
9999
+
10000
+ return (
10001
+ <div
10002
+ className={cn(
10003
+ 'bg-background border-border flex items-center gap-4 rounded-lg border p-4',
10004
+ className
10005
+ )}
10006
+ >
10007
+ {/* Product image */}
10008
+ <div className="bg-muted relative h-16 w-16 flex-shrink-0 overflow-hidden rounded">
10009
+ {imageUrl ? (
10010
+ <Image src={imageUrl} alt={product.name} fill sizes="64px" className="object-cover" />
10011
+ ) : (
10012
+ <div className="text-muted-foreground flex h-full w-full items-center justify-center">
10013
+ <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
10014
+ <path
10015
+ strokeLinecap="round"
10016
+ strokeLinejoin="round"
10017
+ strokeWidth={1.5}
10018
+ d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
10019
+ />
10020
+ </svg>
10021
+ </div>
10022
+ )}
10023
+ </div>
10024
+
10025
+ {/* Details */}
10026
+ <div className="min-w-0 flex-1">
10027
+ <p className="text-foreground text-sm font-medium">{offer.name}</p>
10028
+ {offer.description && (
10029
+ <p className="text-muted-foreground mt-0.5 text-xs">{offer.description}</p>
10030
+ )}
10031
+ <div className="mt-1 flex items-center gap-2">
10032
+ <span className="text-muted-foreground text-sm line-through">
10033
+ {formatPrice(originalPrice, { currency }) as string}
10034
+ </span>
10035
+ <span className="text-foreground text-sm font-semibold">
10036
+ {formatPrice(discountedPrice, { currency }) as string}
10037
+ </span>
10038
+ <span className="bg-destructive/10 text-destructive rounded px-1.5 py-0.5 text-xs font-medium">
10039
+ -{discountLabel}
10040
+ </span>
10041
+ </div>
10042
+ </div>
10043
+
10044
+ {/* Add button */}
10045
+ <button
10046
+ type="button"
10047
+ onClick={handleAdd}
10048
+ disabled={adding}
10049
+ className={cn(
10050
+ 'bg-primary text-primary-foreground flex-shrink-0 rounded px-4 py-2 text-xs font-medium transition-opacity hover:opacity-90',
10051
+ 'disabled:cursor-not-allowed disabled:opacity-50'
10052
+ )}
10053
+ >
10054
+ {adding ? t('addingBundle') : t('addBundleItem')}
10055
+ </button>
10056
+ </div>
10057
+ );
10058
+ }
10059
+ `,
10060
+ "src/components/checkout/order-bump-card.tsx": `'use client';
10061
+
10062
+ import Image from 'next/image';
10063
+ import type { OrderBump } from 'brainerce';
10064
+ import { formatPrice } from 'brainerce';
10065
+ import { useStoreInfo } from '@/providers/store-provider';
10066
+ import { useTranslations } from '@/lib/translations';
10067
+ import { cn } from '@/lib/utils';
10068
+
10069
+ interface OrderBumpCardProps {
10070
+ bump: OrderBump;
10071
+ isAdded: boolean;
10072
+ onToggle: (bumpId: string, add: boolean) => void;
10073
+ loading: boolean;
10074
+ className?: string;
10075
+ }
10076
+
10077
+ export function OrderBumpCard({ bump, isAdded, onToggle, loading, className }: OrderBumpCardProps) {
10078
+ const { storeInfo } = useStoreInfo();
10079
+ const t = useTranslations('checkout');
10080
+ const currency = storeInfo?.currency || 'USD';
10081
+
10082
+ const product = bump.bumpProduct;
10083
+ const firstImage = product.images?.[0];
10084
+ const imageUrl = firstImage
10085
+ ? typeof firstImage === 'string'
10086
+ ? firstImage
10087
+ : firstImage.url
10088
+ : null;
10089
+ const originalPrice = parseFloat(bump.originalPrice);
10090
+ const hasDiscount = bump.discountedPrice != null;
10091
+ const discountedPrice = hasDiscount ? parseFloat(bump.discountedPrice!) : null;
10092
+
10093
+ return (
10094
+ <label
10095
+ className={cn(
10096
+ 'border-border hover:border-primary/50 flex cursor-pointer items-start gap-3 rounded-lg border p-3 transition-colors',
10097
+ isAdded && 'border-primary bg-primary/5',
10098
+ loading && 'pointer-events-none opacity-60',
10099
+ className
10100
+ )}
10101
+ >
10102
+ <input
10103
+ type="checkbox"
10104
+ checked={isAdded}
10105
+ onChange={() => onToggle(bump.id, !isAdded)}
10106
+ disabled={loading}
10107
+ className="mt-1 h-4 w-4 shrink-0 rounded"
10108
+ />
10109
+
10110
+ {/* Image */}
10111
+ {imageUrl && (
10112
+ <div className="bg-muted relative h-10 w-10 shrink-0 overflow-hidden rounded">
10113
+ <Image src={imageUrl} alt={product.name} fill sizes="40px" className="object-cover" />
10114
+ </div>
10115
+ )}
10116
+
10117
+ {/* Content */}
10118
+ <div className="min-w-0 flex-1">
10119
+ <p className="text-foreground text-sm font-medium">{bump.title}</p>
10120
+ {bump.description && (
10121
+ <p className="text-muted-foreground mt-0.5 text-xs">{bump.description}</p>
10122
+ )}
10123
+ <div className="mt-1 flex items-center gap-2">
10124
+ {hasDiscount ? (
10125
+ <>
10126
+ <span className="text-muted-foreground text-xs line-through">
10127
+ {formatPrice(originalPrice, { currency }) as string}
10128
+ </span>
10129
+ <span className="text-foreground text-sm font-semibold">
10130
+ {formatPrice(discountedPrice!, { currency }) as string}
10131
+ </span>
10132
+ </>
10133
+ ) : (
10134
+ <span className="text-foreground text-sm font-semibold">
10135
+ {formatPrice(originalPrice, { currency }) as string}
10136
+ </span>
10137
+ )}
10138
+ </div>
10139
+ </div>
10140
+ </label>
10141
+ );
10142
+ }
9213
10143
  `,
9214
10144
  "src/hooks/use-search.ts": `'use client';
9215
10145