create-brainerce-store 1.43.0 → 1.43.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.
Files changed (24) hide show
  1. package/dist/index.js +1 -1
  2. package/messages/en.json +1 -0
  3. package/messages/he.json +1 -0
  4. package/package.json +1 -1
  5. package/templates/nextjs/base/next.config.ts +68 -69
  6. package/templates/nextjs/base/scripts/fetch-store-info.mjs +91 -93
  7. package/templates/nextjs/base/src/app/checkout/page.tsx +1004 -982
  8. package/templates/nextjs/base/src/app/products/[slug]/page.tsx +118 -118
  9. package/templates/nextjs/base/src/components/account/order-history.tsx +368 -368
  10. package/templates/nextjs/base/src/components/cart/cart-bundle-offer.tsx +111 -111
  11. package/templates/nextjs/base/src/components/cart/cart-item.tsx +152 -152
  12. package/templates/nextjs/base/src/components/cart/cart-summary.tsx +108 -108
  13. package/templates/nextjs/base/src/components/cart/cart-upgrade-banner.tsx +141 -141
  14. package/templates/nextjs/base/src/components/cart/free-shipping-bar.tsx +62 -62
  15. package/templates/nextjs/base/src/components/checkout/order-bump-card.tsx +242 -242
  16. package/templates/nextjs/base/src/components/checkout/pickup-step.tsx +198 -198
  17. package/templates/nextjs/base/src/components/checkout/shipping-step.tsx +109 -109
  18. package/templates/nextjs/base/src/components/checkout/tax-display.tsx +74 -64
  19. package/templates/nextjs/base/src/components/products/frequently-bought-together.tsx +203 -203
  20. package/templates/nextjs/base/src/components/products/variant-selector.tsx +291 -291
  21. package/templates/nextjs/base/src/components/seo/product-json-ld.tsx +125 -129
  22. package/templates/nextjs/base/src/components/shared/price-display.tsx +61 -61
  23. package/templates/nextjs/base/src/lib/resolve-currency.ts +1 -6
  24. package/templates/nextjs/base/src/lib/use-currency.ts +1 -6
@@ -1,982 +1,1004 @@
1
- 'use client';
2
-
3
- import { Suspense, useEffect, useState, useCallback, useRef } from 'react';
4
- import { useSearchParams } from 'next/navigation';
5
- import Image from 'next/image';
6
- import { Link } from '@/lib/navigation';
7
- import type {
8
- Checkout,
9
- ShippingRate,
10
- SetShippingAddressDto,
11
- ShippingDestinations,
12
- PickupLocation,
13
- CheckoutBumpsResponse,
14
- CheckoutCustomFieldDefinition,
15
- } from 'brainerce';
16
- import { formatPrice } from 'brainerce';
17
- import { getClient } from '@/lib/brainerce';
18
- import { useStoreInfo, useCart, useAuth } from '@/providers/store-provider';
19
- import { useCurrency } from '@/lib/use-currency';
20
- import { CheckoutForm } from '@/components/checkout/checkout-form';
21
- import { ShippingStep } from '@/components/checkout/shipping-step';
22
- import { PaymentStep } from '@/components/checkout/payment-step';
23
- import { DeliveryMethodStep } from '@/components/checkout/delivery-method-step';
24
- import { PickupStep } from '@/components/checkout/pickup-step';
25
- import { CustomFieldsStep } from '@/components/checkout/custom-fields-step';
26
- import { TaxDisplay } from '@/components/checkout/tax-display';
27
- import { OrderBumpCard } from '@/components/checkout/order-bump-card';
28
- import { CouponInput } from '@/components/cart/coupon-input';
29
- import { ReservationCountdown } from '@/components/cart/reservation-countdown';
30
- import { LoadingSpinner } from '@/components/shared/loading-spinner';
31
- import { useTranslations } from '@/lib/translations';
32
- import { cn } from '@/lib/utils';
33
- import { isValidCheckoutId } from '@/lib/safe-redirect';
34
-
35
- type CheckoutStep = 'method' | 'address' | 'shipping' | 'pickup' | 'custom-fields' | 'payment';
36
-
37
- function CheckoutContent() {
38
- const searchParams = useSearchParams();
39
- const { storeInfo } = useStoreInfo();
40
- const { cart, refreshCart } = useCart();
41
- const { isLoggedIn } = useAuth();
42
- const currency = useCurrency();
43
- const t = useTranslations('checkout');
44
- const tc = useTranslations('common');
45
-
46
- const [step, setStep] = useState<CheckoutStep>('address');
47
- const [checkout, setCheckout] = useState<Checkout | null>(null);
48
- const [shippingRates, setShippingRates] = useState<ShippingRate[]>([]);
49
- const [selectedRateId, setSelectedRateId] = useState<string | null>(null);
50
- const [loading, setLoading] = useState(false);
51
- const [initializing, setInitializing] = useState(true);
52
- const [error, setError] = useState<string | null>(null);
53
- const [destinations, setDestinations] = useState<ShippingDestinations | null>(null);
54
- const [pickupLocations, setPickupLocations] = useState<PickupLocation[]>([]);
55
- const [deliveryType, setDeliveryType] = useState<'shipping' | 'pickup'>('shipping');
56
- const [isAllDigital, setIsAllDigital] = useState(false);
57
- const [prefillAddress, setPrefillAddress] = useState<SetShippingAddressDto | null>(null);
58
- const [prefillCustomer, setPrefillCustomer] = useState<{
59
- email: string;
60
- firstName?: string;
61
- lastName?: string;
62
- phone?: string;
63
- } | null>(null);
64
- const [hasSavedAddress, setHasSavedAddress] = useState(false);
65
- const [orderBumps, setOrderBumps] = useState<CheckoutBumpsResponse | null>(null);
66
- const [addedBumpIds, setAddedBumpIds] = useState<Set<string>>(new Set());
67
- const [bumpLoading, setBumpLoading] = useState<string | null>(null);
68
- const [customFields, setCustomFields] = useState<CheckoutCustomFieldDefinition[]>([]);
69
- const [customFieldValues, setCustomFieldValues] = useState<Record<string, unknown>>({});
70
- const [customFieldsLoading, setCustomFieldsLoading] = useState(false);
71
-
72
- // Check for returning from canceled payment
73
- const canceled = searchParams.get('canceled') === 'true';
74
- const checkoutIdParam = searchParams.get('checkout_id');
75
- const existingCheckoutId = isValidCheckoutId(checkoutIdParam) ? checkoutIdParam : null;
76
-
77
- // Pre-fill address and customer data from profile when logged in
78
- useEffect(() => {
79
- if (!isLoggedIn) return;
80
- getClient()
81
- .getCheckoutPrefillData()
82
- .then((data) => {
83
- if (data.customer) setPrefillCustomer(data.customer);
84
- if (data.shippingAddress) {
85
- setPrefillAddress(data.shippingAddress);
86
- setHasSavedAddress(true);
87
- }
88
- })
89
- .catch(() => {});
90
- }, [isLoggedIn]);
91
-
92
- // Initialize or resume checkout (only once)
93
- const checkoutInitRef = useRef(false);
94
- const cartIdRef = useRef<string | null>(null);
95
-
96
- useEffect(() => {
97
- // Only init once, or if cart ID actually changed (e.g. cart was replaced)
98
- if (!cart?.id) return;
99
- if (checkoutInitRef.current && cartIdRef.current === cart.id) return;
100
- checkoutInitRef.current = true;
101
- cartIdRef.current = cart.id;
102
-
103
- const initCheckout = async () => {
104
- try {
105
- setInitializing(true);
106
- setError(null);
107
- const client = getClient();
108
-
109
- // Fetch shipping destinations and pickup locations in parallel
110
- client
111
- .getShippingDestinations()
112
- .then(setDestinations)
113
- .catch(() => {});
114
-
115
- const locations = await client.getPickupLocations().catch(() => [] as PickupLocation[]);
116
- setPickupLocations(locations);
117
-
118
- // If returning with existing checkout ID, resume it
119
- if (existingCheckoutId) {
120
- const existing = await client.getCheckout(existingCheckoutId);
121
- setCheckout(existing);
122
-
123
- // Preload custom field definitions and any existing values so the
124
- // step indicator and "change options" affordance work on resume.
125
- client
126
- .getCheckoutCustomFields(existing.id)
127
- .then((fields) => {
128
- setCustomFields(fields);
129
- const existingValues = (
130
- existing as unknown as {
131
- customFieldValues?: Record<string, unknown> | null;
132
- }
133
- ).customFieldValues;
134
- if (existingValues) setCustomFieldValues(existingValues);
135
- })
136
- .catch(() => {
137
- setCustomFields([]);
138
- });
139
-
140
- // Determine step based on checkout state
141
- const allDigital = existing.lineItems.every(
142
- (i) => (i.product as unknown as { isDownloadable?: boolean }).isDownloadable
143
- );
144
- setIsAllDigital(allDigital);
145
- if (allDigital) {
146
- // Digital products: show contact info step if email not set, else payment
147
- setStep(existing.email ? 'payment' : 'address');
148
- } else if (existing.deliveryType === 'pickup' && existing.pickupLocation) {
149
- setDeliveryType('pickup');
150
- setStep('payment');
151
- } else if (existing.shippingAddress && existing.shippingRateId) {
152
- setStep('payment');
153
- } else if (existing.shippingAddress) {
154
- // Fetch shipping rates
155
- const rates = await client.getShippingRates(existing.id);
156
- setShippingRates(rates);
157
- setStep('shipping');
158
- } else if (locations.length > 0) {
159
- setStep('method');
160
- }
161
- return;
162
- }
163
-
164
- // Create new checkout — cart is always server-side now
165
- const newCheckout = await client.createCheckout({ cartId: cart.id });
166
- setCheckout(newCheckout);
167
-
168
- // If all items are downloadable, skip shipping — show contact info step
169
- const allDigital = newCheckout.lineItems.every(
170
- (i) => (i.product as unknown as { isDownloadable?: boolean }).isDownloadable
171
- );
172
- setIsAllDigital(allDigital);
173
- if (allDigital) {
174
- setStep('address');
175
- return;
176
- }
177
-
178
- // If pickup locations exist, start with delivery method selection
179
- if (locations.length > 0) {
180
- setStep('method');
181
- }
182
- } catch (err) {
183
- const message = err instanceof Error ? err.message : t('failedToInitCheckout');
184
- setError(message);
185
- } finally {
186
- setInitializing(false);
187
- }
188
- };
189
-
190
- initCheckout();
191
- }, [cart?.id, existingCheckoutId]);
192
-
193
- // Load order bumps when checkout is available
194
- useEffect(() => {
195
- if (!checkout?.id || storeInfo?.upsell?.checkoutOrderBumpEnabled === false) {
196
- setOrderBumps(null);
197
- return;
198
- }
199
- const client = getClient();
200
- client
201
- .getCheckoutBumps(checkout.id)
202
- .then((data) => {
203
- setOrderBumps(data);
204
- // Detect already-added bumps from cart
205
- if (cart?.items) {
206
- const existingBumpIds = new Set<string>();
207
- for (const item of cart.items) {
208
- const meta = item.metadata as Record<string, unknown> | undefined;
209
- if (meta?.isOrderBump && meta?.orderBumpId) {
210
- existingBumpIds.add(meta.orderBumpId as string);
211
- }
212
- }
213
- setAddedBumpIds(existingBumpIds);
214
- }
215
- })
216
- .catch(() => {});
217
- }, [checkout?.id, storeInfo?.upsell?.checkoutOrderBumpEnabled]);
218
-
219
- // Handle bump toggle
220
- async function handleBumpToggle(bumpId: string, add: boolean, variantId?: string) {
221
- if (!cart?.id || bumpLoading) return;
222
- try {
223
- setBumpLoading(bumpId);
224
- const client = getClient();
225
- if (add) {
226
- await client.addOrderBump(cart.id, bumpId, variantId);
227
- setAddedBumpIds((prev) => new Set([...prev, bumpId]));
228
- } else {
229
- await client.removeOrderBump(cart.id, bumpId);
230
- setAddedBumpIds((prev) => {
231
- const next = new Set(prev);
232
- next.delete(bumpId);
233
- return next;
234
- });
235
- }
236
- await refreshCart();
237
- } catch (err) {
238
- console.error('Failed to toggle order bump:', err);
239
- } finally {
240
- setBumpLoading(null);
241
- }
242
- }
243
-
244
- // Handle shipping address submission
245
- async function handleAddressSubmit(
246
- address: SetShippingAddressDto,
247
- consent: { acceptsMarketing: boolean; saveDetails: boolean }
248
- ) {
249
- if (!checkout) return;
250
-
251
- try {
252
- setLoading(true);
253
- setError(null);
254
- const client = getClient();
255
-
256
- if (isAllDigital) {
257
- // Digital products: set customer info only, skip shipping
258
- const updated = await client.setCheckoutCustomer(checkout.id, {
259
- email: address.email,
260
- firstName: address.firstName,
261
- lastName: address.lastName,
262
- phone: address.phone,
263
- acceptsMarketing: consent.acceptsMarketing,
264
- });
265
- setCheckout(updated);
266
- setStep('payment');
267
- } else {
268
- const response = await client.setShippingAddress(checkout.id, address);
269
- setCheckout(response.checkout);
270
- setShippingRates(response.rates);
271
- setStep('shipping');
272
- }
273
-
274
- // Update marketing preference for logged-in users
275
- if (isLoggedIn) {
276
- try {
277
- await client.updateMyProfile({ acceptsMarketing: consent.acceptsMarketing });
278
- } catch {
279
- // non-critical
280
- }
281
- }
282
-
283
- // Save address to profile if checkbox was checked and no existing saved address
284
- if (isLoggedIn && consent.saveDetails && !hasSavedAddress && !isAllDigital) {
285
- try {
286
- await client.addMyAddress({
287
- firstName: address.firstName,
288
- lastName: address.lastName,
289
- line1: address.line1,
290
- line2: address.line2,
291
- city: address.city,
292
- region: address.region,
293
- postalCode: address.postalCode,
294
- country: address.country,
295
- phone: address.phone,
296
- isDefault: true,
297
- });
298
- } catch {
299
- // non-critical
300
- }
301
- }
302
- } catch (err) {
303
- const message = err instanceof Error ? err.message : t('failedToSaveAddress');
304
- setError(message);
305
- } finally {
306
- setLoading(false);
307
- }
308
- }
309
-
310
- // After shipping/pickup is set, decide whether to show the custom-fields step
311
- // or jump straight to payment. Returns the next step.
312
- async function loadCustomFieldsOrSkip(checkoutId: string): Promise<CheckoutStep> {
313
- try {
314
- const fields = await getClient().getCheckoutCustomFields(checkoutId);
315
- setCustomFields(fields);
316
- return fields.length > 0 ? 'custom-fields' : 'payment';
317
- } catch {
318
- // If the endpoint isn't available or fails, fall through to payment
319
- // rather than blocking the customer.
320
- setCustomFields([]);
321
- return 'payment';
322
- }
323
- }
324
-
325
- // Handle shipping method selection
326
- async function handleShippingSelect(rateId: string) {
327
- if (!checkout) return;
328
-
329
- try {
330
- setLoading(true);
331
- setError(null);
332
- setSelectedRateId(rateId);
333
- const client = getClient();
334
-
335
- const updated = await client.selectShippingMethod(checkout.id, rateId);
336
- setCheckout(updated);
337
- setStep(await loadCustomFieldsOrSkip(updated.id));
338
- } catch (err) {
339
- const message = err instanceof Error ? err.message : t('failedToSelectShipping');
340
- setError(message);
341
- } finally {
342
- setLoading(false);
343
- }
344
- }
345
-
346
- // Submit custom fields
347
- async function handleCustomFieldsApply() {
348
- if (!checkout) return;
349
- try {
350
- setCustomFieldsLoading(true);
351
- setError(null);
352
- const updated = await getClient().setCheckoutCustomFields(checkout.id, customFieldValues);
353
- setCheckout(updated);
354
- setStep('payment');
355
- } catch (err) {
356
- const message = err instanceof Error ? err.message : t('customFieldsFailed');
357
- setError(message);
358
- } finally {
359
- setCustomFieldsLoading(false);
360
- }
361
- }
362
-
363
- // Handle delivery method selection
364
- async function handleDeliveryTypeSelect(method: 'shipping' | 'pickup') {
365
- if (!checkout) return;
366
-
367
- try {
368
- setLoading(true);
369
- setError(null);
370
- setDeliveryType(method);
371
- const client = getClient();
372
-
373
- await client.setDeliveryType(checkout.id, method);
374
-
375
- if (method === 'shipping') {
376
- setStep('address');
377
- } else {
378
- setStep('pickup');
379
- }
380
- } catch (err) {
381
- const message = err instanceof Error ? err.message : t('failedToSetDeliveryMethod');
382
- setError(message);
383
- } finally {
384
- setLoading(false);
385
- }
386
- }
387
-
388
- // Handle pickup location selection
389
- async function handlePickupSelect(
390
- locationId: string,
391
- customerInfo: { email: string; firstName?: string; lastName?: string; phone?: string }
392
- ) {
393
- if (!checkout) return;
394
-
395
- try {
396
- setLoading(true);
397
- setError(null);
398
- const client = getClient();
399
-
400
- const updated = await client.selectPickupLocation(checkout.id, {
401
- pickupRateId: locationId,
402
- email: customerInfo.email,
403
- firstName: customerInfo.firstName,
404
- lastName: customerInfo.lastName,
405
- phone: customerInfo.phone,
406
- });
407
- setCheckout(updated);
408
- setStep(await loadCustomFieldsOrSkip(updated.id));
409
- } catch (err) {
410
- const message = err instanceof Error ? err.message : t('failedToSelectPickup');
411
- setError(message);
412
- } finally {
413
- setLoading(false);
414
- }
415
- }
416
-
417
- // Refresh cart after coupon apply/remove.
418
- // The checkout totals are updated server-side by applyCheckoutCoupon/removeCheckoutCoupon,
419
- // so we re-fetch the checkout to get the updated discountAmount and total.
420
- const handleCouponUpdate = useCallback(async () => {
421
- await refreshCart();
422
- if (checkout) {
423
- try {
424
- const client = getClient();
425
- const updated = await client.getCheckout(checkout.id);
426
- setCheckout(updated);
427
- } catch (err) {
428
- console.error('Failed to refresh checkout after coupon update:', err);
429
- }
430
- }
431
- }, [checkout, refreshCart]);
432
-
433
- if (initializing) {
434
- return (
435
- <div className="flex min-h-[60vh] items-center justify-center">
436
- <LoadingSpinner size="lg" />
437
- </div>
438
- );
439
- }
440
-
441
- // Empty cart
442
- if (!cart || cart.items.length === 0) {
443
- return (
444
- <div className="mx-auto max-w-7xl px-4 py-16 text-center sm:px-6 lg:px-8">
445
- <h1 className="text-foreground text-2xl font-bold">{t('emptyCart')}</h1>
446
- <p className="text-muted-foreground mt-2">{t('emptyCartSubtitle')}</p>
447
- <Link
448
- href="/products"
449
- className="bg-primary text-primary-foreground mt-6 inline-flex items-center rounded px-6 py-3 font-medium transition-opacity hover:opacity-90"
450
- >
451
- {tc('shopNow')}
452
- </Link>
453
- </div>
454
- );
455
- }
456
-
457
- if (error && !checkout) {
458
- return (
459
- <div className="mx-auto max-w-7xl px-4 py-16 text-center sm:px-6 lg:px-8">
460
- <h1 className="text-foreground text-2xl font-bold">{t('errorTitle')}</h1>
461
- <p className="text-destructive mt-2">{error}</p>
462
- <Link
463
- href="/cart"
464
- className="bg-primary text-primary-foreground mt-6 inline-flex items-center rounded px-6 py-3 font-medium transition-opacity hover:opacity-90"
465
- >
466
- {t('returnToCart')}
467
- </Link>
468
- </div>
469
- );
470
- }
471
-
472
- const customFieldsStep =
473
- customFields.length > 0
474
- ? [{ key: 'custom-fields' as CheckoutStep, label: t('stepCustomFields') }]
475
- : [];
476
-
477
- const steps: { key: CheckoutStep; label: string }[] = isAllDigital
478
- ? [
479
- { key: 'address', label: t('stepContactInfo') },
480
- ...customFieldsStep,
481
- { key: 'payment', label: t('stepPayment') },
482
- ]
483
- : pickupLocations.length > 0
484
- ? deliveryType === 'pickup'
485
- ? [
486
- { key: 'method', label: t('stepMethod') },
487
- { key: 'pickup', label: t('stepPickup') },
488
- ...customFieldsStep,
489
- { key: 'payment', label: t('stepPayment') },
490
- ]
491
- : [
492
- { key: 'method', label: t('stepMethod') },
493
- { key: 'address', label: t('stepAddress') },
494
- { key: 'shipping', label: t('stepShipping') },
495
- ...customFieldsStep,
496
- { key: 'payment', label: t('stepPayment') },
497
- ]
498
- : [
499
- { key: 'address', label: t('stepAddress') },
500
- { key: 'shipping', label: t('stepShipping') },
501
- ...customFieldsStep,
502
- { key: 'payment', label: t('stepPayment') },
503
- ];
504
-
505
- const currentStepIndex = steps.findIndex((s) => s.key === step);
506
-
507
- return (
508
- <div className="mx-auto max-w-7xl px-4 py-8 sm:px-6 lg:px-8">
509
- <h1 className="text-foreground mb-6 text-2xl font-bold">{t('title')}</h1>
510
-
511
- {/* Canceled payment banner */}
512
- {canceled && (
513
- <div className="mb-6 rounded-lg border border-orange-200 bg-orange-50 px-4 py-3 text-sm text-orange-800 dark:border-orange-800 dark:bg-orange-950/30 dark:text-orange-300">
514
- {t('paymentCanceledBanner')}
515
- </div>
516
- )}
517
-
518
- {/* Reservation countdown */}
519
- {checkout?.reservation?.hasReservation && (
520
- <ReservationCountdown reservation={checkout.reservation} className="mb-6" />
521
- )}
522
-
523
- {/* Step indicator */}
524
- <div className="mb-8 flex items-center gap-2">
525
- {steps.map((s, index) => (
526
- <div key={s.key} className="flex items-center">
527
- {index > 0 && (
528
- <div
529
- className={cn(
530
- 'mx-2 h-px w-8 sm:w-12',
531
- index <= currentStepIndex ? 'bg-primary' : 'bg-border'
532
- )}
533
- />
534
- )}
535
- <div className="flex items-center gap-2">
536
- <div
537
- className={cn(
538
- 'flex h-7 w-7 items-center justify-center rounded-full text-xs font-medium',
539
- index < currentStepIndex
540
- ? 'bg-primary text-primary-foreground'
541
- : index === currentStepIndex
542
- ? 'bg-primary text-primary-foreground'
543
- : 'bg-muted text-muted-foreground'
544
- )}
545
- >
546
- {index < currentStepIndex ? (
547
- <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
548
- <path
549
- strokeLinecap="round"
550
- strokeLinejoin="round"
551
- strokeWidth={2}
552
- d="M5 13l4 4L19 7"
553
- />
554
- </svg>
555
- ) : (
556
- index + 1
557
- )}
558
- </div>
559
- <span
560
- className={cn(
561
- 'hidden text-sm sm:block',
562
- index <= currentStepIndex
563
- ? 'text-foreground font-medium'
564
- : 'text-muted-foreground'
565
- )}
566
- >
567
- {s.label}
568
- </span>
569
- </div>
570
- </div>
571
- ))}
572
- </div>
573
-
574
- {/* Error banner */}
575
- {error && checkout && (
576
- <div className="bg-destructive/10 border-destructive/20 text-destructive mb-6 rounded-lg border px-4 py-3 text-sm">
577
- {error}
578
- </div>
579
- )}
580
-
581
- <div className="grid grid-cols-1 gap-8 lg:grid-cols-3">
582
- {/* Main content */}
583
- <div className="lg:col-span-2">
584
- {/* Delivery Method */}
585
- {step === 'method' && (
586
- <div>
587
- <h2 className="text-foreground mb-4 text-lg font-semibold">{t('deliveryMethod')}</h2>
588
- <DeliveryMethodStep onSelect={handleDeliveryTypeSelect} />
589
- </div>
590
- )}
591
-
592
- {/* Address */}
593
- {step === 'address' && (
594
- <div>
595
- <div className="mb-4 flex items-center justify-between">
596
- <h2 className="text-foreground text-lg font-semibold">
597
- {isAllDigital ? t('contactInfo') : t('shippingAddress')}
598
- </h2>
599
- {!isAllDigital && pickupLocations.length > 0 && (
600
- <button
601
- type="button"
602
- onClick={() => setStep('method')}
603
- className="text-primary text-sm hover:underline"
604
- >
605
- {t('changeMethod')}
606
- </button>
607
- )}
608
- </div>
609
- <CheckoutForm
610
- onSubmit={handleAddressSubmit}
611
- loading={loading}
612
- destinations={isAllDigital ? null : destinations}
613
- showSaveDetails={isLoggedIn && !hasSavedAddress && !isAllDigital}
614
- emailOnly={isAllDigital}
615
- initialValues={
616
- checkout?.shippingAddress
617
- ? {
618
- email: checkout.email || '',
619
- firstName: checkout.shippingAddress.firstName,
620
- lastName: checkout.shippingAddress.lastName,
621
- line1: checkout.shippingAddress.line1,
622
- line2: checkout.shippingAddress.line2 || '',
623
- city: checkout.shippingAddress.city,
624
- region: checkout.shippingAddress.region || '',
625
- postalCode: checkout.shippingAddress.postalCode,
626
- country: checkout.shippingAddress.country,
627
- phone: checkout.shippingAddress.phone || '',
628
- }
629
- : prefillAddress
630
- ? {
631
- email: prefillAddress.email,
632
- firstName: prefillAddress.firstName,
633
- lastName: prefillAddress.lastName,
634
- line1: prefillAddress.line1,
635
- line2: prefillAddress.line2 || '',
636
- city: prefillAddress.city,
637
- region: prefillAddress.region || '',
638
- postalCode: prefillAddress.postalCode,
639
- country: prefillAddress.country,
640
- phone: prefillAddress.phone || '',
641
- }
642
- : prefillCustomer
643
- ? {
644
- email: prefillCustomer.email,
645
- firstName: prefillCustomer.firstName || '',
646
- lastName: prefillCustomer.lastName || '',
647
- phone: prefillCustomer.phone || '',
648
- }
649
- : undefined
650
- }
651
- />
652
- </div>
653
- )}
654
-
655
- {/* Step 2: Shipping */}
656
- {step === 'shipping' && (
657
- <div>
658
- <div className="mb-4 flex items-center justify-between">
659
- <h2 className="text-foreground text-lg font-semibold">{t('shippingMethod')}</h2>
660
- <button
661
- type="button"
662
- onClick={() => setStep('address')}
663
- className="text-primary text-sm hover:underline"
664
- >
665
- {t('editAddress')}
666
- </button>
667
- </div>
668
-
669
- <ShippingStep
670
- rates={shippingRates}
671
- selectedRateId={selectedRateId}
672
- onSelect={handleShippingSelect}
673
- loading={loading}
674
- />
675
- </div>
676
- )}
677
-
678
- {/* Pickup */}
679
- {step === 'pickup' && (
680
- <div>
681
- <div className="mb-4 flex items-center justify-between">
682
- <h2 className="text-foreground text-lg font-semibold">{t('pickupLocation')}</h2>
683
- <button
684
- type="button"
685
- onClick={() => setStep('method')}
686
- className="text-primary text-sm hover:underline"
687
- >
688
- {t('changeMethod')}
689
- </button>
690
- </div>
691
- <PickupStep
692
- locations={pickupLocations}
693
- onSelect={handlePickupSelect}
694
- loading={loading}
695
- initialEmail={checkout?.email || ''}
696
- />
697
- </div>
698
- )}
699
-
700
- {/* Custom Fields (optional, between shipping/pickup and payment) */}
701
- {step === 'custom-fields' && checkout && (
702
- <div>
703
- <div className="mb-4 flex items-center justify-between">
704
- <h2 className="text-foreground text-lg font-semibold">{t('customFieldsTitle')}</h2>
705
- <button
706
- type="button"
707
- onClick={() => setStep(deliveryType === 'pickup' ? 'pickup' : 'shipping')}
708
- className="text-primary text-sm hover:underline"
709
- >
710
- {deliveryType === 'pickup' ? t('changePickup') : t('changeShipping')}
711
- </button>
712
- </div>
713
- <CustomFieldsStep
714
- fields={customFields}
715
- values={customFieldValues}
716
- onChange={(key, value) =>
717
- setCustomFieldValues((prev) => ({ ...prev, [key]: value }))
718
- }
719
- onApply={handleCustomFieldsApply}
720
- onUploadFile={(file) => getClient().uploadCustomizationFile(file)}
721
- loading={customFieldsLoading}
722
- />
723
- </div>
724
- )}
725
-
726
- {/* Payment */}
727
- {step === 'payment' && checkout && (
728
- <div>
729
- <div className="mb-4 flex items-center justify-between">
730
- <h2 className="text-foreground text-lg font-semibold">{t('payment')}</h2>
731
- {customFields.length > 0 ? (
732
- <button
733
- type="button"
734
- onClick={() => setStep('custom-fields')}
735
- className="text-primary text-sm hover:underline"
736
- >
737
- {t('changeOptions')}
738
- </button>
739
- ) : (
740
- !isAllDigital && (
741
- <button
742
- type="button"
743
- onClick={() => setStep(deliveryType === 'pickup' ? 'pickup' : 'shipping')}
744
- className="text-primary text-sm hover:underline"
745
- >
746
- {deliveryType === 'pickup' ? t('changePickup') : t('changeShipping')}
747
- </button>
748
- )
749
- )}
750
- </div>
751
-
752
- <PaymentStep checkoutId={checkout.id} />
753
- </div>
754
- )}
755
- </div>
756
-
757
- {/* Order summary sidebar */}
758
- <div className="lg:col-span-1">
759
- <div className="bg-muted/50 border-border sticky top-24 rounded-lg border p-6">
760
- <h3 className="text-foreground mb-4 text-lg font-semibold">{t('orderSummary')}</h3>
761
-
762
- {/* Line items */}
763
- {checkout?.lineItems && checkout.lineItems.length > 0 ? (
764
- <div className="mb-4 space-y-3">
765
- {checkout.lineItems.map((item) => {
766
- const imageUrl = item.product.images?.[0]?.url || null;
767
- const name = item.variant?.name || item.product.name;
768
- const lineTotal = parseFloat(item.unitPrice) * item.quantity;
769
-
770
- return (
771
- <div key={item.id} className="flex gap-3">
772
- <div className="bg-muted relative h-12 w-12 flex-shrink-0 overflow-hidden rounded">
773
- {imageUrl ? (
774
- <Image
775
- src={imageUrl}
776
- alt={name}
777
- fill
778
- sizes="48px"
779
- className="object-cover"
780
- />
781
- ) : (
782
- <div className="text-muted-foreground absolute inset-0 flex items-center justify-center">
783
- <svg
784
- className="h-5 w-5"
785
- fill="none"
786
- viewBox="0 0 24 24"
787
- stroke="currentColor"
788
- >
789
- <path
790
- strokeLinecap="round"
791
- strokeLinejoin="round"
792
- strokeWidth={1.5}
793
- 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"
794
- />
795
- </svg>
796
- </div>
797
- )}
798
- </div>
799
-
800
- <div className="min-w-0 flex-1">
801
- <p className="text-foreground truncate text-sm">{name}</p>
802
- <p className="text-muted-foreground text-xs">
803
- {tc('qty')} {item.quantity}
804
- </p>
805
- </div>
806
-
807
- <span className="text-foreground flex-shrink-0 text-sm font-medium">
808
- {formatPrice(lineTotal, { currency }) as string}
809
- </span>
810
- </div>
811
- );
812
- })}
813
- </div>
814
- ) : (
815
- // Fallback to cart items if checkout line items aren't loaded yet
816
- cart && (
817
- <div className="mb-4 space-y-2">
818
- <p className="text-muted-foreground text-sm">
819
- {cart.items.length} {cart.items.length === 1 ? tc('item') : tc('items')}
820
- </p>
821
- </div>
822
- )
823
- )}
824
-
825
- {/* Order bumps */}
826
- {orderBumps?.bumps && orderBumps.bumps.length > 0 && (
827
- <div className="border-border space-y-2 border-t pt-4">
828
- <p className="text-foreground text-xs font-semibold uppercase tracking-wide">
829
- {t('addToYourOrder')}
830
- </p>
831
- {orderBumps.bumps.map((bump) => (
832
- <OrderBumpCard
833
- key={bump.id}
834
- bump={bump}
835
- isAdded={addedBumpIds.has(bump.id)}
836
- onToggle={handleBumpToggle}
837
- loading={bumpLoading === bump.id}
838
- />
839
- ))}
840
- </div>
841
- )}
842
-
843
- {/* Coupon input — show from shipping/pickup step onwards (or immediately if digital) */}
844
- {cart &&
845
- (isAllDigital || step === 'shipping' || step === 'pickup' || step === 'payment') && (
846
- <div className="border-border border-t pt-4">
847
- <CouponInput
848
- cart={cart}
849
- checkoutId={checkout?.id}
850
- onUpdate={handleCouponUpdate}
851
- />
852
- </div>
853
- )}
854
-
855
- {/* Totals */}
856
- {checkout && (
857
- <div className="border-border space-y-2 border-t pt-4 text-sm">
858
- <div className="flex items-center justify-between">
859
- <span className="text-muted-foreground">{tc('subtotal')}</span>
860
- <span className="text-foreground">
861
- {formatPrice(parseFloat(checkout.subtotal), { currency }) as string}
862
- </span>
863
- </div>
864
-
865
- {(() => {
866
- const totalDiscount = parseFloat(checkout.discountAmount);
867
- const ruleAmt = parseFloat(checkout.ruleDiscountAmount || '0');
868
- const couponAmt = totalDiscount - ruleAmt;
869
- const rules = cart?.appliedDiscounts;
870
- if (totalDiscount <= 0) return null;
871
- return (
872
- <>
873
- {rules && rules.length > 0
874
- ? rules.map((rule) => (
875
- <div key={rule.ruleId} className="flex items-center justify-between">
876
- <span className="text-muted-foreground">{rule.ruleName}</span>
877
- <span className="text-destructive">
878
- -
879
- {
880
- formatPrice(parseFloat(rule.discountAmount), {
881
- currency,
882
- }) as string
883
- }
884
- </span>
885
- </div>
886
- ))
887
- : ruleAmt > 0 && (
888
- <div className="flex items-center justify-between">
889
- <span className="text-muted-foreground">{tc('generalDiscount')}</span>
890
- <span className="text-destructive">
891
- -{formatPrice(ruleAmt, { currency }) as string}
892
- </span>
893
- </div>
894
- )}
895
- {checkout.couponCode && couponAmt > 0 && (
896
- <div className="flex items-center justify-between">
897
- <span className="text-muted-foreground">
898
- {tc('couponDiscount')} ({checkout.couponCode})
899
- </span>
900
- <span className="text-destructive">
901
- -{formatPrice(couponAmt, { currency }) as string}
902
- </span>
903
- </div>
904
- )}
905
- {!checkout.couponCode && ruleAmt <= 0 && (!rules || rules.length === 0) && (
906
- <div className="flex items-center justify-between">
907
- <span className="text-muted-foreground">{tc('discount')}</span>
908
- <span className="text-destructive">
909
- -{formatPrice(totalDiscount, { currency }) as string}
910
- </span>
911
- </div>
912
- )}
913
- </>
914
- );
915
- })()}
916
-
917
- {(parseFloat(checkout.shippingAmount) > 0 ||
918
- checkout.deliveryType === 'pickup') && (
919
- <div className="flex items-center justify-between">
920
- <span className="text-muted-foreground">
921
- {checkout.deliveryType === 'pickup' ? tc('pickup') : tc('shipping')}
922
- </span>
923
- <span className="text-foreground">
924
- {parseFloat(checkout.shippingAmount) === 0
925
- ? tc('free')
926
- : (formatPrice(parseFloat(checkout.shippingAmount), {
927
- currency,
928
- }) as string)}
929
- </span>
930
- </div>
931
- )}
932
-
933
- <TaxDisplay
934
- addressSet={!!checkout.shippingAddress}
935
- taxAmount={checkout.taxAmount}
936
- taxBreakdown={checkout.taxBreakdown}
937
- />
938
-
939
- {/* Custom field surcharges (one line per applied surcharge) */}
940
- {checkout.appliedSurcharges && checkout.appliedSurcharges.length > 0 && (
941
- <>
942
- {checkout.appliedSurcharges.map((s) => (
943
- <div key={s.key} className="flex items-center justify-between">
944
- <span className="text-muted-foreground">{s.name}</span>
945
- <span className="text-foreground">
946
- {formatPrice(Number(s.amount), { currency }) as string}
947
- </span>
948
- </div>
949
- ))}
950
- </>
951
- )}
952
-
953
- <div className="border-border mt-2 border-t pt-2">
954
- <div className="flex items-center justify-between">
955
- <span className="text-foreground font-semibold">{tc('total')}</span>
956
- <span className="text-foreground text-base font-semibold">
957
- {formatPrice(parseFloat(checkout.total), { currency }) as string}
958
- </span>
959
- </div>
960
- </div>
961
- </div>
962
- )}
963
- </div>
964
- </div>
965
- </div>
966
- </div>
967
- );
968
- }
969
-
970
- export default function CheckoutPage() {
971
- return (
972
- <Suspense
973
- fallback={
974
- <div className="flex min-h-[60vh] items-center justify-center">
975
- <LoadingSpinner size="lg" />
976
- </div>
977
- }
978
- >
979
- <CheckoutContent />
980
- </Suspense>
981
- );
982
- }
1
+ 'use client';
2
+
3
+ import { Suspense, useEffect, useState, useCallback, useRef } from 'react';
4
+ import { useSearchParams } from 'next/navigation';
5
+ import Image from 'next/image';
6
+ import { Link } from '@/lib/navigation';
7
+ import type {
8
+ Checkout,
9
+ ShippingRate,
10
+ SetShippingAddressDto,
11
+ ShippingDestinations,
12
+ PickupLocation,
13
+ CheckoutBumpsResponse,
14
+ CheckoutCustomFieldDefinition,
15
+ } from 'brainerce';
16
+ import { formatPrice } from 'brainerce';
17
+ import { getClient } from '@/lib/brainerce';
18
+ import { useStoreInfo, useCart, useAuth } from '@/providers/store-provider';
19
+ import { useCurrency } from '@/lib/use-currency';
20
+ import { CheckoutForm } from '@/components/checkout/checkout-form';
21
+ import { ShippingStep } from '@/components/checkout/shipping-step';
22
+ import { PaymentStep } from '@/components/checkout/payment-step';
23
+ import { DeliveryMethodStep } from '@/components/checkout/delivery-method-step';
24
+ import { PickupStep } from '@/components/checkout/pickup-step';
25
+ import { CustomFieldsStep } from '@/components/checkout/custom-fields-step';
26
+ import { TaxDisplay } from '@/components/checkout/tax-display';
27
+ import { OrderBumpCard } from '@/components/checkout/order-bump-card';
28
+ import { CouponInput } from '@/components/cart/coupon-input';
29
+ import { ReservationCountdown } from '@/components/cart/reservation-countdown';
30
+ import { LoadingSpinner } from '@/components/shared/loading-spinner';
31
+ import { useTranslations } from '@/lib/translations';
32
+ import { cn } from '@/lib/utils';
33
+ import { isValidCheckoutId } from '@/lib/safe-redirect';
34
+
35
+ type CheckoutStep = 'method' | 'address' | 'shipping' | 'pickup' | 'custom-fields' | 'payment';
36
+
37
+ function CheckoutContent() {
38
+ const searchParams = useSearchParams();
39
+ const { storeInfo } = useStoreInfo();
40
+ const { cart, refreshCart } = useCart();
41
+ const { isLoggedIn } = useAuth();
42
+ const currency = useCurrency();
43
+ const t = useTranslations('checkout');
44
+ const tc = useTranslations('common');
45
+
46
+ const [step, setStep] = useState<CheckoutStep>('address');
47
+ const [checkout, setCheckout] = useState<Checkout | null>(null);
48
+ const [shippingRates, setShippingRates] = useState<ShippingRate[]>([]);
49
+ const [selectedRateId, setSelectedRateId] = useState<string | null>(null);
50
+ const [loading, setLoading] = useState(false);
51
+ const [initializing, setInitializing] = useState(true);
52
+ const [error, setError] = useState<string | null>(null);
53
+ const [destinations, setDestinations] = useState<ShippingDestinations | null>(null);
54
+ const [pickupLocations, setPickupLocations] = useState<PickupLocation[]>([]);
55
+ const [deliveryType, setDeliveryType] = useState<'shipping' | 'pickup'>('shipping');
56
+ const [isAllDigital, setIsAllDigital] = useState(false);
57
+ const [prefillAddress, setPrefillAddress] = useState<SetShippingAddressDto | null>(null);
58
+ const [prefillCustomer, setPrefillCustomer] = useState<{
59
+ email: string;
60
+ firstName?: string;
61
+ lastName?: string;
62
+ phone?: string;
63
+ } | null>(null);
64
+ const [hasSavedAddress, setHasSavedAddress] = useState(false);
65
+ const [orderBumps, setOrderBumps] = useState<CheckoutBumpsResponse | null>(null);
66
+ const [addedBumpIds, setAddedBumpIds] = useState<Set<string>>(new Set());
67
+ const [bumpLoading, setBumpLoading] = useState<string | null>(null);
68
+ const [customFields, setCustomFields] = useState<CheckoutCustomFieldDefinition[]>([]);
69
+ const [customFieldValues, setCustomFieldValues] = useState<Record<string, unknown>>({});
70
+ const [customFieldsLoading, setCustomFieldsLoading] = useState(false);
71
+
72
+ // Check for returning from canceled payment
73
+ const canceled = searchParams.get('canceled') === 'true';
74
+ const checkoutIdParam = searchParams.get('checkout_id');
75
+ const existingCheckoutId = isValidCheckoutId(checkoutIdParam) ? checkoutIdParam : null;
76
+
77
+ // Pre-fill address and customer data from profile when logged in
78
+ useEffect(() => {
79
+ if (!isLoggedIn) return;
80
+ getClient()
81
+ .getCheckoutPrefillData()
82
+ .then((data) => {
83
+ if (data.customer) setPrefillCustomer(data.customer);
84
+ if (data.shippingAddress) {
85
+ setPrefillAddress(data.shippingAddress);
86
+ setHasSavedAddress(true);
87
+ }
88
+ })
89
+ .catch(() => {});
90
+ }, [isLoggedIn]);
91
+
92
+ // Initialize or resume checkout (only once)
93
+ const checkoutInitRef = useRef(false);
94
+ const cartIdRef = useRef<string | null>(null);
95
+
96
+ useEffect(() => {
97
+ // Only init once, or if cart ID actually changed (e.g. cart was replaced)
98
+ if (!cart?.id) return;
99
+ if (checkoutInitRef.current && cartIdRef.current === cart.id) return;
100
+ checkoutInitRef.current = true;
101
+ cartIdRef.current = cart.id;
102
+
103
+ const initCheckout = async () => {
104
+ try {
105
+ setInitializing(true);
106
+ setError(null);
107
+ const client = getClient();
108
+
109
+ // Fetch shipping destinations and pickup locations in parallel
110
+ client
111
+ .getShippingDestinations()
112
+ .then(setDestinations)
113
+ .catch(() => {});
114
+
115
+ const locations = await client.getPickupLocations().catch(() => [] as PickupLocation[]);
116
+ setPickupLocations(locations);
117
+
118
+ // If returning with existing checkout ID, resume it
119
+ if (existingCheckoutId) {
120
+ const existing = await client.getCheckout(existingCheckoutId);
121
+ setCheckout(existing);
122
+
123
+ // Preload custom field definitions and any existing values so the
124
+ // step indicator and "change options" affordance work on resume.
125
+ client
126
+ .getCheckoutCustomFields(existing.id)
127
+ .then((fields) => {
128
+ setCustomFields(fields);
129
+ const existingValues = (
130
+ existing as unknown as {
131
+ customFieldValues?: Record<string, unknown> | null;
132
+ }
133
+ ).customFieldValues;
134
+ if (existingValues) setCustomFieldValues(existingValues);
135
+ })
136
+ .catch(() => {
137
+ setCustomFields([]);
138
+ });
139
+
140
+ // Determine step based on checkout state
141
+ const allDigital = existing.lineItems.every(
142
+ (i) => (i.product as unknown as { isDownloadable?: boolean }).isDownloadable
143
+ );
144
+ setIsAllDigital(allDigital);
145
+ if (allDigital) {
146
+ // Digital products: show contact info step if email not set, else payment
147
+ setStep(existing.email ? 'payment' : 'address');
148
+ } else if (existing.deliveryType === 'pickup' && existing.pickupLocation) {
149
+ setDeliveryType('pickup');
150
+ setStep('payment');
151
+ } else if (existing.shippingAddress && existing.shippingRateId) {
152
+ setStep('payment');
153
+ } else if (existing.shippingAddress) {
154
+ // Fetch shipping rates
155
+ const rates = await client.getShippingRates(existing.id);
156
+ setShippingRates(rates);
157
+ setStep('shipping');
158
+ } else if (locations.length > 0) {
159
+ setStep('method');
160
+ }
161
+ return;
162
+ }
163
+
164
+ // Create new checkout — cart is always server-side now
165
+ const newCheckout = await client.createCheckout({ cartId: cart.id });
166
+ setCheckout(newCheckout);
167
+
168
+ // If all items are downloadable, skip shipping — show contact info step
169
+ const allDigital = newCheckout.lineItems.every(
170
+ (i) => (i.product as unknown as { isDownloadable?: boolean }).isDownloadable
171
+ );
172
+ setIsAllDigital(allDigital);
173
+ if (allDigital) {
174
+ setStep('address');
175
+ return;
176
+ }
177
+
178
+ // If pickup locations exist, start with delivery method selection
179
+ if (locations.length > 0) {
180
+ setStep('method');
181
+ }
182
+ } catch (err) {
183
+ const message = err instanceof Error ? err.message : t('failedToInitCheckout');
184
+ setError(message);
185
+ } finally {
186
+ setInitializing(false);
187
+ }
188
+ };
189
+
190
+ initCheckout();
191
+ }, [cart?.id, existingCheckoutId]);
192
+
193
+ // Load order bumps when checkout is available
194
+ useEffect(() => {
195
+ if (!checkout?.id || storeInfo?.upsell?.checkoutOrderBumpEnabled === false) {
196
+ setOrderBumps(null);
197
+ return;
198
+ }
199
+ const client = getClient();
200
+ client
201
+ .getCheckoutBumps(checkout.id)
202
+ .then((data) => {
203
+ setOrderBumps(data);
204
+ // Detect already-added bumps from cart
205
+ if (cart?.items) {
206
+ const existingBumpIds = new Set<string>();
207
+ for (const item of cart.items) {
208
+ const meta = item.metadata as Record<string, unknown> | undefined;
209
+ if (meta?.isOrderBump && meta?.orderBumpId) {
210
+ existingBumpIds.add(meta.orderBumpId as string);
211
+ }
212
+ }
213
+ setAddedBumpIds(existingBumpIds);
214
+ }
215
+ })
216
+ .catch(() => {});
217
+ }, [checkout?.id, storeInfo?.upsell?.checkoutOrderBumpEnabled]);
218
+
219
+ // Handle bump toggle
220
+ async function handleBumpToggle(bumpId: string, add: boolean, variantId?: string) {
221
+ if (!cart?.id || bumpLoading) return;
222
+ try {
223
+ setBumpLoading(bumpId);
224
+ const client = getClient();
225
+ if (add) {
226
+ await client.addOrderBump(cart.id, bumpId, variantId);
227
+ setAddedBumpIds((prev) => new Set([...prev, bumpId]));
228
+ } else {
229
+ await client.removeOrderBump(cart.id, bumpId);
230
+ setAddedBumpIds((prev) => {
231
+ const next = new Set(prev);
232
+ next.delete(bumpId);
233
+ return next;
234
+ });
235
+ }
236
+ await refreshCart();
237
+ } catch (err) {
238
+ console.error('Failed to toggle order bump:', err);
239
+ } finally {
240
+ setBumpLoading(null);
241
+ }
242
+ }
243
+
244
+ // Handle shipping address submission
245
+ async function handleAddressSubmit(
246
+ address: SetShippingAddressDto,
247
+ consent: { acceptsMarketing: boolean; saveDetails: boolean }
248
+ ) {
249
+ if (!checkout) return;
250
+
251
+ try {
252
+ setLoading(true);
253
+ setError(null);
254
+ const client = getClient();
255
+
256
+ if (isAllDigital) {
257
+ // Digital products: set customer info only, skip shipping
258
+ const updated = await client.setCheckoutCustomer(checkout.id, {
259
+ email: address.email,
260
+ firstName: address.firstName,
261
+ lastName: address.lastName,
262
+ phone: address.phone,
263
+ acceptsMarketing: consent.acceptsMarketing,
264
+ });
265
+ setCheckout(updated);
266
+ setStep('payment');
267
+ } else {
268
+ const response = await client.setShippingAddress(checkout.id, address);
269
+ setCheckout(response.checkout);
270
+ setShippingRates(response.rates);
271
+ setStep('shipping');
272
+ }
273
+
274
+ // Update marketing preference for logged-in users
275
+ if (isLoggedIn) {
276
+ try {
277
+ await client.updateMyProfile({ acceptsMarketing: consent.acceptsMarketing });
278
+ } catch {
279
+ // non-critical
280
+ }
281
+ }
282
+
283
+ // Save address to profile if checkbox was checked and no existing saved address
284
+ if (isLoggedIn && consent.saveDetails && !hasSavedAddress && !isAllDigital) {
285
+ try {
286
+ await client.addMyAddress({
287
+ firstName: address.firstName,
288
+ lastName: address.lastName,
289
+ line1: address.line1,
290
+ line2: address.line2,
291
+ city: address.city,
292
+ region: address.region,
293
+ postalCode: address.postalCode,
294
+ country: address.country,
295
+ phone: address.phone,
296
+ isDefault: true,
297
+ });
298
+ } catch {
299
+ // non-critical
300
+ }
301
+ }
302
+ } catch (err) {
303
+ const message = err instanceof Error ? err.message : t('failedToSaveAddress');
304
+ setError(message);
305
+ } finally {
306
+ setLoading(false);
307
+ }
308
+ }
309
+
310
+ // After shipping/pickup is set, decide whether to show the custom-fields step
311
+ // or jump straight to payment. Returns the next step.
312
+ async function loadCustomFieldsOrSkip(checkoutId: string): Promise<CheckoutStep> {
313
+ try {
314
+ const fields = await getClient().getCheckoutCustomFields(checkoutId);
315
+ setCustomFields(fields);
316
+ return fields.length > 0 ? 'custom-fields' : 'payment';
317
+ } catch {
318
+ // If the endpoint isn't available or fails, fall through to payment
319
+ // rather than blocking the customer.
320
+ setCustomFields([]);
321
+ return 'payment';
322
+ }
323
+ }
324
+
325
+ // Handle shipping method selection
326
+ async function handleShippingSelect(rateId: string) {
327
+ if (!checkout) return;
328
+
329
+ try {
330
+ setLoading(true);
331
+ setError(null);
332
+ setSelectedRateId(rateId);
333
+ const client = getClient();
334
+
335
+ const updated = await client.selectShippingMethod(checkout.id, rateId);
336
+ setCheckout(updated);
337
+ setStep(await loadCustomFieldsOrSkip(updated.id));
338
+ } catch (err) {
339
+ const message = err instanceof Error ? err.message : t('failedToSelectShipping');
340
+ setError(message);
341
+ } finally {
342
+ setLoading(false);
343
+ }
344
+ }
345
+
346
+ // Submit custom fields
347
+ async function handleCustomFieldsApply() {
348
+ if (!checkout) return;
349
+ try {
350
+ setCustomFieldsLoading(true);
351
+ setError(null);
352
+ const updated = await getClient().setCheckoutCustomFields(checkout.id, customFieldValues);
353
+ setCheckout(updated);
354
+ setStep('payment');
355
+ } catch (err) {
356
+ const message = err instanceof Error ? err.message : t('customFieldsFailed');
357
+ setError(message);
358
+ } finally {
359
+ setCustomFieldsLoading(false);
360
+ }
361
+ }
362
+
363
+ // Handle delivery method selection
364
+ async function handleDeliveryTypeSelect(method: 'shipping' | 'pickup') {
365
+ if (!checkout) return;
366
+
367
+ try {
368
+ setLoading(true);
369
+ setError(null);
370
+ setDeliveryType(method);
371
+ const client = getClient();
372
+
373
+ await client.setDeliveryType(checkout.id, method);
374
+
375
+ if (method === 'shipping') {
376
+ setStep('address');
377
+ } else {
378
+ setStep('pickup');
379
+ }
380
+ } catch (err) {
381
+ const message = err instanceof Error ? err.message : t('failedToSetDeliveryMethod');
382
+ setError(message);
383
+ } finally {
384
+ setLoading(false);
385
+ }
386
+ }
387
+
388
+ // Handle pickup location selection
389
+ async function handlePickupSelect(
390
+ locationId: string,
391
+ customerInfo: { email: string; firstName?: string; lastName?: string; phone?: string }
392
+ ) {
393
+ if (!checkout) return;
394
+
395
+ try {
396
+ setLoading(true);
397
+ setError(null);
398
+ const client = getClient();
399
+
400
+ const updated = await client.selectPickupLocation(checkout.id, {
401
+ pickupRateId: locationId,
402
+ email: customerInfo.email,
403
+ firstName: customerInfo.firstName,
404
+ lastName: customerInfo.lastName,
405
+ phone: customerInfo.phone,
406
+ });
407
+ setCheckout(updated);
408
+ setStep(await loadCustomFieldsOrSkip(updated.id));
409
+ } catch (err) {
410
+ const message = err instanceof Error ? err.message : t('failedToSelectPickup');
411
+ setError(message);
412
+ } finally {
413
+ setLoading(false);
414
+ }
415
+ }
416
+
417
+ // Refresh cart after coupon apply/remove.
418
+ // The checkout totals are updated server-side by applyCheckoutCoupon/removeCheckoutCoupon,
419
+ // so we re-fetch the checkout to get the updated discountAmount and total.
420
+ const handleCouponUpdate = useCallback(async () => {
421
+ await refreshCart();
422
+ if (checkout) {
423
+ try {
424
+ const client = getClient();
425
+ const updated = await client.getCheckout(checkout.id);
426
+ setCheckout(updated);
427
+ } catch (err) {
428
+ console.error('Failed to refresh checkout after coupon update:', err);
429
+ }
430
+ }
431
+ }, [checkout, refreshCart]);
432
+
433
+ if (initializing) {
434
+ return (
435
+ <div className="flex min-h-[60vh] items-center justify-center">
436
+ <LoadingSpinner size="lg" />
437
+ </div>
438
+ );
439
+ }
440
+
441
+ // Empty cart
442
+ if (!cart || cart.items.length === 0) {
443
+ return (
444
+ <div className="mx-auto max-w-7xl px-4 py-16 text-center sm:px-6 lg:px-8">
445
+ <h1 className="text-foreground text-2xl font-bold">{t('emptyCart')}</h1>
446
+ <p className="text-muted-foreground mt-2">{t('emptyCartSubtitle')}</p>
447
+ <Link
448
+ href="/products"
449
+ className="bg-primary text-primary-foreground mt-6 inline-flex items-center rounded px-6 py-3 font-medium transition-opacity hover:opacity-90"
450
+ >
451
+ {tc('shopNow')}
452
+ </Link>
453
+ </div>
454
+ );
455
+ }
456
+
457
+ if (error && !checkout) {
458
+ return (
459
+ <div className="mx-auto max-w-7xl px-4 py-16 text-center sm:px-6 lg:px-8">
460
+ <h1 className="text-foreground text-2xl font-bold">{t('errorTitle')}</h1>
461
+ <p className="text-destructive mt-2">{error}</p>
462
+ <Link
463
+ href="/cart"
464
+ className="bg-primary text-primary-foreground mt-6 inline-flex items-center rounded px-6 py-3 font-medium transition-opacity hover:opacity-90"
465
+ >
466
+ {t('returnToCart')}
467
+ </Link>
468
+ </div>
469
+ );
470
+ }
471
+
472
+ const customFieldsStep =
473
+ customFields.length > 0
474
+ ? [{ key: 'custom-fields' as CheckoutStep, label: t('stepCustomFields') }]
475
+ : [];
476
+
477
+ const steps: { key: CheckoutStep; label: string }[] = isAllDigital
478
+ ? [
479
+ { key: 'address', label: t('stepContactInfo') },
480
+ ...customFieldsStep,
481
+ { key: 'payment', label: t('stepPayment') },
482
+ ]
483
+ : pickupLocations.length > 0
484
+ ? deliveryType === 'pickup'
485
+ ? [
486
+ { key: 'method', label: t('stepMethod') },
487
+ { key: 'pickup', label: t('stepPickup') },
488
+ ...customFieldsStep,
489
+ { key: 'payment', label: t('stepPayment') },
490
+ ]
491
+ : [
492
+ { key: 'method', label: t('stepMethod') },
493
+ { key: 'address', label: t('stepAddress') },
494
+ { key: 'shipping', label: t('stepShipping') },
495
+ ...customFieldsStep,
496
+ { key: 'payment', label: t('stepPayment') },
497
+ ]
498
+ : [
499
+ { key: 'address', label: t('stepAddress') },
500
+ { key: 'shipping', label: t('stepShipping') },
501
+ ...customFieldsStep,
502
+ { key: 'payment', label: t('stepPayment') },
503
+ ];
504
+
505
+ const currentStepIndex = steps.findIndex((s) => s.key === step);
506
+
507
+ return (
508
+ <div className="mx-auto max-w-7xl px-4 py-8 sm:px-6 lg:px-8">
509
+ <h1 className="text-foreground mb-6 text-2xl font-bold">{t('title')}</h1>
510
+
511
+ {/* Canceled payment banner */}
512
+ {canceled && (
513
+ <div className="mb-6 rounded-lg border border-orange-200 bg-orange-50 px-4 py-3 text-sm text-orange-800 dark:border-orange-800 dark:bg-orange-950/30 dark:text-orange-300">
514
+ {t('paymentCanceledBanner')}
515
+ </div>
516
+ )}
517
+
518
+ {/* Reservation countdown */}
519
+ {checkout?.reservation?.hasReservation && (
520
+ <ReservationCountdown reservation={checkout.reservation} className="mb-6" />
521
+ )}
522
+
523
+ {/* Step indicator */}
524
+ <div className="mb-8 flex items-center gap-2">
525
+ {steps.map((s, index) => (
526
+ <div key={s.key} className="flex items-center">
527
+ {index > 0 && (
528
+ <div
529
+ className={cn(
530
+ 'mx-2 h-px w-8 sm:w-12',
531
+ index <= currentStepIndex ? 'bg-primary' : 'bg-border'
532
+ )}
533
+ />
534
+ )}
535
+ <div className="flex items-center gap-2">
536
+ <div
537
+ className={cn(
538
+ 'flex h-7 w-7 items-center justify-center rounded-full text-xs font-medium',
539
+ index < currentStepIndex
540
+ ? 'bg-primary text-primary-foreground'
541
+ : index === currentStepIndex
542
+ ? 'bg-primary text-primary-foreground'
543
+ : 'bg-muted text-muted-foreground'
544
+ )}
545
+ >
546
+ {index < currentStepIndex ? (
547
+ <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
548
+ <path
549
+ strokeLinecap="round"
550
+ strokeLinejoin="round"
551
+ strokeWidth={2}
552
+ d="M5 13l4 4L19 7"
553
+ />
554
+ </svg>
555
+ ) : (
556
+ index + 1
557
+ )}
558
+ </div>
559
+ <span
560
+ className={cn(
561
+ 'hidden text-sm sm:block',
562
+ index <= currentStepIndex
563
+ ? 'text-foreground font-medium'
564
+ : 'text-muted-foreground'
565
+ )}
566
+ >
567
+ {s.label}
568
+ </span>
569
+ </div>
570
+ </div>
571
+ ))}
572
+ </div>
573
+
574
+ {/* Error banner */}
575
+ {error && checkout && (
576
+ <div className="bg-destructive/10 border-destructive/20 text-destructive mb-6 rounded-lg border px-4 py-3 text-sm">
577
+ {error}
578
+ </div>
579
+ )}
580
+
581
+ <div className="grid grid-cols-1 gap-8 lg:grid-cols-3">
582
+ {/* Main content */}
583
+ <div className="lg:col-span-2">
584
+ {/* Delivery Method */}
585
+ {step === 'method' && (
586
+ <div>
587
+ <h2 className="text-foreground mb-4 text-lg font-semibold">{t('deliveryMethod')}</h2>
588
+ <DeliveryMethodStep onSelect={handleDeliveryTypeSelect} />
589
+ </div>
590
+ )}
591
+
592
+ {/* Address */}
593
+ {step === 'address' && (
594
+ <div>
595
+ <div className="mb-4 flex items-center justify-between">
596
+ <h2 className="text-foreground text-lg font-semibold">
597
+ {isAllDigital ? t('contactInfo') : t('shippingAddress')}
598
+ </h2>
599
+ {!isAllDigital && pickupLocations.length > 0 && (
600
+ <button
601
+ type="button"
602
+ onClick={() => setStep('method')}
603
+ className="text-primary text-sm hover:underline"
604
+ >
605
+ {t('changeMethod')}
606
+ </button>
607
+ )}
608
+ </div>
609
+ <CheckoutForm
610
+ onSubmit={handleAddressSubmit}
611
+ loading={loading}
612
+ destinations={isAllDigital ? null : destinations}
613
+ showSaveDetails={isLoggedIn && !hasSavedAddress && !isAllDigital}
614
+ emailOnly={isAllDigital}
615
+ initialValues={
616
+ checkout?.shippingAddress
617
+ ? {
618
+ email: checkout.email || '',
619
+ firstName: checkout.shippingAddress.firstName,
620
+ lastName: checkout.shippingAddress.lastName,
621
+ line1: checkout.shippingAddress.line1,
622
+ line2: checkout.shippingAddress.line2 || '',
623
+ city: checkout.shippingAddress.city,
624
+ region: checkout.shippingAddress.region || '',
625
+ postalCode: checkout.shippingAddress.postalCode,
626
+ country: checkout.shippingAddress.country,
627
+ phone: checkout.shippingAddress.phone || '',
628
+ }
629
+ : prefillAddress
630
+ ? {
631
+ email: prefillAddress.email,
632
+ firstName: prefillAddress.firstName,
633
+ lastName: prefillAddress.lastName,
634
+ line1: prefillAddress.line1,
635
+ line2: prefillAddress.line2 || '',
636
+ city: prefillAddress.city,
637
+ region: prefillAddress.region || '',
638
+ postalCode: prefillAddress.postalCode,
639
+ country: prefillAddress.country,
640
+ phone: prefillAddress.phone || '',
641
+ }
642
+ : prefillCustomer
643
+ ? {
644
+ email: prefillCustomer.email,
645
+ firstName: prefillCustomer.firstName || '',
646
+ lastName: prefillCustomer.lastName || '',
647
+ phone: prefillCustomer.phone || '',
648
+ }
649
+ : undefined
650
+ }
651
+ />
652
+ </div>
653
+ )}
654
+
655
+ {/* Step 2: Shipping */}
656
+ {step === 'shipping' && (
657
+ <div>
658
+ <div className="mb-4 flex items-center justify-between">
659
+ <h2 className="text-foreground text-lg font-semibold">{t('shippingMethod')}</h2>
660
+ <button
661
+ type="button"
662
+ onClick={() => setStep('address')}
663
+ className="text-primary text-sm hover:underline"
664
+ >
665
+ {t('editAddress')}
666
+ </button>
667
+ </div>
668
+
669
+ <ShippingStep
670
+ rates={shippingRates}
671
+ selectedRateId={selectedRateId}
672
+ onSelect={handleShippingSelect}
673
+ loading={loading}
674
+ />
675
+ </div>
676
+ )}
677
+
678
+ {/* Pickup */}
679
+ {step === 'pickup' && (
680
+ <div>
681
+ <div className="mb-4 flex items-center justify-between">
682
+ <h2 className="text-foreground text-lg font-semibold">{t('pickupLocation')}</h2>
683
+ <button
684
+ type="button"
685
+ onClick={() => setStep('method')}
686
+ className="text-primary text-sm hover:underline"
687
+ >
688
+ {t('changeMethod')}
689
+ </button>
690
+ </div>
691
+ <PickupStep
692
+ locations={pickupLocations}
693
+ onSelect={handlePickupSelect}
694
+ loading={loading}
695
+ initialEmail={checkout?.email || ''}
696
+ />
697
+ </div>
698
+ )}
699
+
700
+ {/* Custom Fields (optional, between shipping/pickup and payment) */}
701
+ {step === 'custom-fields' && checkout && (
702
+ <div>
703
+ <div className="mb-4 flex items-center justify-between">
704
+ <h2 className="text-foreground text-lg font-semibold">{t('customFieldsTitle')}</h2>
705
+ <button
706
+ type="button"
707
+ onClick={() => setStep(deliveryType === 'pickup' ? 'pickup' : 'shipping')}
708
+ className="text-primary text-sm hover:underline"
709
+ >
710
+ {deliveryType === 'pickup' ? t('changePickup') : t('changeShipping')}
711
+ </button>
712
+ </div>
713
+ <CustomFieldsStep
714
+ fields={customFields}
715
+ values={customFieldValues}
716
+ onChange={(key, value) =>
717
+ setCustomFieldValues((prev) => ({ ...prev, [key]: value }))
718
+ }
719
+ onApply={handleCustomFieldsApply}
720
+ onUploadFile={(file) => getClient().uploadCustomizationFile(file)}
721
+ loading={customFieldsLoading}
722
+ />
723
+ </div>
724
+ )}
725
+
726
+ {/* Payment */}
727
+ {step === 'payment' && checkout && (
728
+ <div>
729
+ <div className="mb-4 flex items-center justify-between">
730
+ <h2 className="text-foreground text-lg font-semibold">{t('payment')}</h2>
731
+ {customFields.length > 0 ? (
732
+ <button
733
+ type="button"
734
+ onClick={() => setStep('custom-fields')}
735
+ className="text-primary text-sm hover:underline"
736
+ >
737
+ {t('changeOptions')}
738
+ </button>
739
+ ) : (
740
+ !isAllDigital && (
741
+ <button
742
+ type="button"
743
+ onClick={() => setStep(deliveryType === 'pickup' ? 'pickup' : 'shipping')}
744
+ className="text-primary text-sm hover:underline"
745
+ >
746
+ {deliveryType === 'pickup' ? t('changePickup') : t('changeShipping')}
747
+ </button>
748
+ )
749
+ )}
750
+ </div>
751
+
752
+ <PaymentStep checkoutId={checkout.id} />
753
+ </div>
754
+ )}
755
+ </div>
756
+
757
+ {/* Order summary sidebar */}
758
+ <div className="lg:col-span-1">
759
+ <div className="bg-muted/50 border-border sticky top-24 rounded-lg border p-6">
760
+ <h3 className="text-foreground mb-4 text-lg font-semibold">{t('orderSummary')}</h3>
761
+
762
+ {/* Line items */}
763
+ {checkout?.lineItems && checkout.lineItems.length > 0 ? (
764
+ <div className="mb-4 space-y-3">
765
+ {checkout.lineItems.map((item) => {
766
+ const imageUrl = item.product.images?.[0]?.url || null;
767
+ const name = item.variant?.name || item.product.name;
768
+ const lineTotal = parseFloat(item.unitPrice) * item.quantity;
769
+
770
+ return (
771
+ <div key={item.id} className="flex gap-3">
772
+ <div className="bg-muted relative h-12 w-12 flex-shrink-0 overflow-hidden rounded">
773
+ {imageUrl ? (
774
+ <Image
775
+ src={imageUrl}
776
+ alt={name}
777
+ fill
778
+ sizes="48px"
779
+ className="object-cover"
780
+ />
781
+ ) : (
782
+ <div className="text-muted-foreground absolute inset-0 flex items-center justify-center">
783
+ <svg
784
+ className="h-5 w-5"
785
+ fill="none"
786
+ viewBox="0 0 24 24"
787
+ stroke="currentColor"
788
+ >
789
+ <path
790
+ strokeLinecap="round"
791
+ strokeLinejoin="round"
792
+ strokeWidth={1.5}
793
+ 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"
794
+ />
795
+ </svg>
796
+ </div>
797
+ )}
798
+ </div>
799
+
800
+ <div className="min-w-0 flex-1">
801
+ <p className="text-foreground truncate text-sm">{name}</p>
802
+ <p className="text-muted-foreground text-xs">
803
+ {tc('qty')} {item.quantity}
804
+ </p>
805
+ </div>
806
+
807
+ <span className="text-foreground flex-shrink-0 text-sm font-medium">
808
+ {formatPrice(lineTotal, { currency }) as string}
809
+ </span>
810
+ </div>
811
+ );
812
+ })}
813
+ </div>
814
+ ) : (
815
+ // Fallback to cart items if checkout line items aren't loaded yet
816
+ cart && (
817
+ <div className="mb-4 space-y-2">
818
+ <p className="text-muted-foreground text-sm">
819
+ {cart.items.length} {cart.items.length === 1 ? tc('item') : tc('items')}
820
+ </p>
821
+ </div>
822
+ )
823
+ )}
824
+
825
+ {/* Order bumps */}
826
+ {orderBumps?.bumps && orderBumps.bumps.length > 0 && (
827
+ <div className="border-border space-y-2 border-t pt-4">
828
+ <p className="text-foreground text-xs font-semibold uppercase tracking-wide">
829
+ {t('addToYourOrder')}
830
+ </p>
831
+ {orderBumps.bumps.map((bump) => (
832
+ <OrderBumpCard
833
+ key={bump.id}
834
+ bump={bump}
835
+ isAdded={addedBumpIds.has(bump.id)}
836
+ onToggle={handleBumpToggle}
837
+ loading={bumpLoading === bump.id}
838
+ />
839
+ ))}
840
+ </div>
841
+ )}
842
+
843
+ {/* Coupon input — show from shipping/pickup step onwards (or immediately if digital) */}
844
+ {cart &&
845
+ (isAllDigital || step === 'shipping' || step === 'pickup' || step === 'payment') && (
846
+ <div className="border-border border-t pt-4">
847
+ <CouponInput
848
+ cart={cart}
849
+ checkoutId={checkout?.id}
850
+ onUpdate={handleCouponUpdate}
851
+ />
852
+ </div>
853
+ )}
854
+
855
+ {/* Totals */}
856
+ {checkout &&
857
+ (() => {
858
+ // When the store prices include tax (VAT-style), the on-row
859
+ // `checkout.subtotal` is GROSS — it already contains the tax.
860
+ // Show the net (tax-excluded) value here, then a separate VAT
861
+ // line below, so the customer sees the breakdown the merchant
862
+ // asked for. Falls back to the raw subtotal when no breakdown
863
+ // is available yet (e.g. shipping address not entered).
864
+ const isInclusive = checkout.taxBreakdown?.pricesIncludeTax === true;
865
+ const displayedSubtotal =
866
+ isInclusive && typeof checkout.taxBreakdown?.subtotal === 'number'
867
+ ? checkout.taxBreakdown.subtotal
868
+ : parseFloat(checkout.subtotal);
869
+ const subtotalLabel = isInclusive ? tc('subtotalExclTax') : tc('subtotal');
870
+ return (
871
+ <div className="border-border space-y-2 border-t pt-4 text-sm">
872
+ <div className="flex items-center justify-between">
873
+ <span className="text-muted-foreground">{subtotalLabel}</span>
874
+ <span className="text-foreground">
875
+ {formatPrice(displayedSubtotal, { currency }) as string}
876
+ </span>
877
+ </div>
878
+
879
+ {(() => {
880
+ const totalDiscount = parseFloat(checkout.discountAmount);
881
+ const ruleAmt = parseFloat(checkout.ruleDiscountAmount || '0');
882
+ const couponAmt = totalDiscount - ruleAmt;
883
+ const rules = cart?.appliedDiscounts;
884
+ if (totalDiscount <= 0) return null;
885
+ return (
886
+ <>
887
+ {rules && rules.length > 0
888
+ ? rules.map((rule) => (
889
+ <div
890
+ key={rule.ruleId}
891
+ className="flex items-center justify-between"
892
+ >
893
+ <span className="text-muted-foreground">{rule.ruleName}</span>
894
+ <span className="text-destructive">
895
+ -
896
+ {
897
+ formatPrice(parseFloat(rule.discountAmount), {
898
+ currency,
899
+ }) as string
900
+ }
901
+ </span>
902
+ </div>
903
+ ))
904
+ : ruleAmt > 0 && (
905
+ <div className="flex items-center justify-between">
906
+ <span className="text-muted-foreground">
907
+ {tc('generalDiscount')}
908
+ </span>
909
+ <span className="text-destructive">
910
+ -{formatPrice(ruleAmt, { currency }) as string}
911
+ </span>
912
+ </div>
913
+ )}
914
+ {checkout.couponCode && couponAmt > 0 && (
915
+ <div className="flex items-center justify-between">
916
+ <span className="text-muted-foreground">
917
+ {tc('couponDiscount')} ({checkout.couponCode})
918
+ </span>
919
+ <span className="text-destructive">
920
+ -{formatPrice(couponAmt, { currency }) as string}
921
+ </span>
922
+ </div>
923
+ )}
924
+ {!checkout.couponCode &&
925
+ ruleAmt <= 0 &&
926
+ (!rules || rules.length === 0) && (
927
+ <div className="flex items-center justify-between">
928
+ <span className="text-muted-foreground">{tc('discount')}</span>
929
+ <span className="text-destructive">
930
+ -{formatPrice(totalDiscount, { currency }) as string}
931
+ </span>
932
+ </div>
933
+ )}
934
+ </>
935
+ );
936
+ })()}
937
+
938
+ {(parseFloat(checkout.shippingAmount) > 0 ||
939
+ checkout.deliveryType === 'pickup') && (
940
+ <div className="flex items-center justify-between">
941
+ <span className="text-muted-foreground">
942
+ {checkout.deliveryType === 'pickup' ? tc('pickup') : tc('shipping')}
943
+ </span>
944
+ <span className="text-foreground">
945
+ {parseFloat(checkout.shippingAmount) === 0
946
+ ? tc('free')
947
+ : (formatPrice(parseFloat(checkout.shippingAmount), {
948
+ currency,
949
+ }) as string)}
950
+ </span>
951
+ </div>
952
+ )}
953
+
954
+ <TaxDisplay
955
+ addressSet={!!checkout.shippingAddress}
956
+ taxAmount={checkout.taxAmount}
957
+ taxBreakdown={checkout.taxBreakdown}
958
+ />
959
+
960
+ {/* Custom field surcharges (one line per applied surcharge) */}
961
+ {checkout.appliedSurcharges && checkout.appliedSurcharges.length > 0 && (
962
+ <>
963
+ {checkout.appliedSurcharges.map((s) => (
964
+ <div key={s.key} className="flex items-center justify-between">
965
+ <span className="text-muted-foreground">{s.name}</span>
966
+ <span className="text-foreground">
967
+ {formatPrice(Number(s.amount), { currency }) as string}
968
+ </span>
969
+ </div>
970
+ ))}
971
+ </>
972
+ )}
973
+
974
+ <div className="border-border mt-2 border-t pt-2">
975
+ <div className="flex items-center justify-between">
976
+ <span className="text-foreground font-semibold">{tc('total')}</span>
977
+ <span className="text-foreground text-base font-semibold">
978
+ {formatPrice(parseFloat(checkout.total), { currency }) as string}
979
+ </span>
980
+ </div>
981
+ </div>
982
+ </div>
983
+ );
984
+ })()}
985
+ </div>
986
+ </div>
987
+ </div>
988
+ </div>
989
+ );
990
+ }
991
+
992
+ export default function CheckoutPage() {
993
+ return (
994
+ <Suspense
995
+ fallback={
996
+ <div className="flex min-h-[60vh] items-center justify-center">
997
+ <LoadingSpinner size="lg" />
998
+ </div>
999
+ }
1000
+ >
1001
+ <CheckoutContent />
1002
+ </Suspense>
1003
+ );
1004
+ }