create-brainerce-store 1.28.13 → 1.28.17

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