create-brainerce-store 1.4.0 → 1.5.0

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 (36) hide show
  1. package/dist/index.js +2 -2
  2. package/messages/en.json +266 -258
  3. package/messages/he.json +266 -258
  4. package/package.json +45 -45
  5. package/templates/nextjs/base/src/app/account/page.tsx +108 -108
  6. package/templates/nextjs/base/src/app/auth/callback/page.tsx +90 -90
  7. package/templates/nextjs/base/src/app/cart/page.tsx +110 -110
  8. package/templates/nextjs/base/src/app/checkout/page.tsx +614 -614
  9. package/templates/nextjs/base/src/app/login/page.tsx +58 -58
  10. package/templates/nextjs/base/src/app/order-confirmation/page.tsx +193 -193
  11. package/templates/nextjs/base/src/app/page.tsx +98 -98
  12. package/templates/nextjs/base/src/app/products/[slug]/page.tsx +435 -435
  13. package/templates/nextjs/base/src/app/products/page.tsx +246 -246
  14. package/templates/nextjs/base/src/app/register/page.tsx +68 -68
  15. package/templates/nextjs/base/src/app/verify-email/page.tsx +293 -293
  16. package/templates/nextjs/base/src/components/account/order-history.tsx +198 -198
  17. package/templates/nextjs/base/src/components/account/profile-section.tsx +210 -75
  18. package/templates/nextjs/base/src/components/auth/login-form.tsx +94 -94
  19. package/templates/nextjs/base/src/components/auth/oauth-buttons.tsx +137 -137
  20. package/templates/nextjs/base/src/components/auth/register-form.tsx +184 -184
  21. package/templates/nextjs/base/src/components/cart/cart-item.tsx +153 -153
  22. package/templates/nextjs/base/src/components/cart/cart-summary.tsx +70 -70
  23. package/templates/nextjs/base/src/components/cart/coupon-input.tsx +134 -134
  24. package/templates/nextjs/base/src/components/cart/reservation-countdown.tsx +103 -103
  25. package/templates/nextjs/base/src/components/checkout/checkout-form.tsx +305 -305
  26. package/templates/nextjs/base/src/components/checkout/delivery-method-step.tsx +64 -64
  27. package/templates/nextjs/base/src/components/checkout/payment-step.tsx +350 -322
  28. package/templates/nextjs/base/src/components/checkout/pickup-step.tsx +199 -199
  29. package/templates/nextjs/base/src/components/checkout/shipping-step.tsx +110 -110
  30. package/templates/nextjs/base/src/components/checkout/tax-display.tsx +65 -65
  31. package/templates/nextjs/base/src/components/layout/footer.tsx +38 -38
  32. package/templates/nextjs/base/src/components/layout/header.tsx +332 -332
  33. package/templates/nextjs/base/src/components/products/product-card.tsx +96 -96
  34. package/templates/nextjs/base/src/components/products/product-grid.tsx +35 -35
  35. package/templates/nextjs/base/src/components/shared/loading-spinner.tsx +32 -32
  36. package/templates/nextjs/base/src/lib/translations.ts +11 -11
@@ -1,614 +1,614 @@
1
- 'use client';
2
-
3
- import { Suspense, useEffect, useState, useCallback } from 'react';
4
- import { useSearchParams } from 'next/navigation';
5
- import Image from 'next/image';
6
- import Link from 'next/link';
7
- import type {
8
- Checkout,
9
- ShippingRate,
10
- SetShippingAddressDto,
11
- ShippingDestinations,
12
- PickupLocation,
13
- } from 'brainerce';
14
- import { formatPrice } from 'brainerce';
15
- import { getClient } from '@/lib/brainerce';
16
- import { useStoreInfo, useAuth, useCart } from '@/providers/store-provider';
17
- import { CheckoutForm } from '@/components/checkout/checkout-form';
18
- import { ShippingStep } from '@/components/checkout/shipping-step';
19
- import { PaymentStep } from '@/components/checkout/payment-step';
20
- import { DeliveryMethodStep } from '@/components/checkout/delivery-method-step';
21
- import { PickupStep } from '@/components/checkout/pickup-step';
22
- import { TaxDisplay } from '@/components/checkout/tax-display';
23
- import { ReservationCountdown } from '@/components/cart/reservation-countdown';
24
- import { LoadingSpinner } from '@/components/shared/loading-spinner';
25
- import { useTranslations } from '@/lib/translations';
26
- import { cn } from '@/lib/utils';
27
-
28
- type CheckoutStep = 'method' | 'address' | 'shipping' | 'pickup' | 'payment';
29
-
30
- function CheckoutContent() {
31
- const searchParams = useSearchParams();
32
- const { storeInfo } = useStoreInfo();
33
- const { isLoggedIn } = useAuth();
34
- const { cart } = useCart();
35
- const currency = storeInfo?.currency || 'USD';
36
- const t = useTranslations('checkout');
37
- const tc = useTranslations('common');
38
-
39
- const [step, setStep] = useState<CheckoutStep>('address');
40
- const [checkout, setCheckout] = useState<Checkout | null>(null);
41
- const [shippingRates, setShippingRates] = useState<ShippingRate[]>([]);
42
- const [selectedRateId, setSelectedRateId] = useState<string | null>(null);
43
- const [loading, setLoading] = useState(false);
44
- const [initializing, setInitializing] = useState(true);
45
- const [error, setError] = useState<string | null>(null);
46
- const [destinations, setDestinations] = useState<ShippingDestinations | null>(null);
47
- const [pickupLocations, setPickupLocations] = useState<PickupLocation[]>([]);
48
- const [deliveryType, setDeliveryType] = useState<'shipping' | 'pickup'>('shipping');
49
-
50
- // Check for returning from canceled payment
51
- const canceled = searchParams.get('canceled') === 'true';
52
- const existingCheckoutId = searchParams.get('checkout_id');
53
-
54
- // Initialize or resume checkout
55
- const initCheckout = useCallback(async () => {
56
- try {
57
- setInitializing(true);
58
- setError(null);
59
- const client = getClient();
60
-
61
- // Fetch shipping destinations and pickup locations in parallel
62
- client
63
- .getShippingDestinations()
64
- .then(setDestinations)
65
- .catch(() => {});
66
-
67
- const locations = await client.getPickupLocations().catch(() => [] as PickupLocation[]);
68
- setPickupLocations(locations);
69
-
70
- // If returning with existing checkout ID, resume it
71
- if (existingCheckoutId) {
72
- const existing = await client.getCheckout(existingCheckoutId);
73
- setCheckout(existing);
74
-
75
- // Determine step based on checkout state
76
- if (existing.deliveryType === 'pickup' && existing.pickupLocation) {
77
- setDeliveryType('pickup');
78
- setStep('payment');
79
- } else if (existing.shippingAddress && existing.shippingRateId) {
80
- setStep('payment');
81
- } else if (existing.shippingAddress) {
82
- // Fetch shipping rates
83
- const rates = await client.getShippingRates(existing.id);
84
- setShippingRates(rates);
85
- setStep('shipping');
86
- } else if (locations.length > 0) {
87
- setStep('method');
88
- }
89
- return;
90
- }
91
-
92
- // Create new checkout — cart is always server-side now
93
- if (cart && cart.id) {
94
- if (isLoggedIn) {
95
- // Logged-in user: create checkout from customer cart
96
- const newCheckout = await client.createCheckout({ cartId: cart.id });
97
- setCheckout(newCheckout);
98
- } else {
99
- // Guest user: start guest checkout (creates checkout from session cart)
100
- const result = await client.startGuestCheckout();
101
- if (result.tracked) {
102
- const newCheckout = await client.getCheckout(result.checkoutId);
103
- setCheckout(newCheckout);
104
- } else {
105
- setError(t('failedToStartCheckout'));
106
- }
107
- }
108
- } else {
109
- setError(t('cartIsEmpty'));
110
- }
111
-
112
- // If pickup locations exist, start with delivery method selection
113
- if (locations.length > 0) {
114
- setStep('method');
115
- }
116
- } catch (err) {
117
- const message = err instanceof Error ? err.message : t('failedToInitCheckout');
118
- setError(message);
119
- } finally {
120
- setInitializing(false);
121
- }
122
- }, [existingCheckoutId, isLoggedIn, cart]);
123
-
124
- const cartLoaded = cart !== null;
125
- useEffect(() => {
126
- if (cartLoaded) {
127
- initCheckout();
128
- }
129
- }, [cartLoaded, initCheckout]);
130
-
131
- // Handle shipping address submission
132
- async function handleAddressSubmit(address: SetShippingAddressDto) {
133
- if (!checkout) return;
134
-
135
- try {
136
- setLoading(true);
137
- setError(null);
138
- const client = getClient();
139
-
140
- const response = await client.setShippingAddress(checkout.id, address);
141
- setCheckout(response.checkout);
142
- setShippingRates(response.rates);
143
- setStep('shipping');
144
- } catch (err) {
145
- const message = err instanceof Error ? err.message : t('failedToSaveAddress');
146
- setError(message);
147
- } finally {
148
- setLoading(false);
149
- }
150
- }
151
-
152
- // Handle shipping method selection
153
- async function handleShippingSelect(rateId: string) {
154
- if (!checkout) return;
155
-
156
- try {
157
- setLoading(true);
158
- setError(null);
159
- setSelectedRateId(rateId);
160
- const client = getClient();
161
-
162
- const updated = await client.selectShippingMethod(checkout.id, rateId);
163
- setCheckout(updated);
164
- setStep('payment');
165
- } catch (err) {
166
- const message = err instanceof Error ? err.message : t('failedToSelectShipping');
167
- setError(message);
168
- } finally {
169
- setLoading(false);
170
- }
171
- }
172
-
173
- // Handle delivery method selection
174
- async function handleDeliveryTypeSelect(method: 'shipping' | 'pickup') {
175
- if (!checkout) return;
176
-
177
- try {
178
- setLoading(true);
179
- setError(null);
180
- setDeliveryType(method);
181
- const client = getClient();
182
-
183
- await client.setDeliveryType(checkout.id, method);
184
-
185
- if (method === 'shipping') {
186
- setStep('address');
187
- } else {
188
- setStep('pickup');
189
- }
190
- } catch (err) {
191
- const message = err instanceof Error ? err.message : t('failedToSetDeliveryMethod');
192
- setError(message);
193
- } finally {
194
- setLoading(false);
195
- }
196
- }
197
-
198
- // Handle pickup location selection
199
- async function handlePickupSelect(
200
- locationId: string,
201
- customerInfo: { email: string; firstName?: string; lastName?: string; phone?: string }
202
- ) {
203
- if (!checkout) return;
204
-
205
- try {
206
- setLoading(true);
207
- setError(null);
208
- const client = getClient();
209
-
210
- const updated = await client.selectPickupLocation(checkout.id, {
211
- pickupRateId: locationId,
212
- email: customerInfo.email,
213
- firstName: customerInfo.firstName,
214
- lastName: customerInfo.lastName,
215
- phone: customerInfo.phone,
216
- });
217
- setCheckout(updated);
218
- setStep('payment');
219
- } catch (err) {
220
- const message = err instanceof Error ? err.message : t('failedToSelectPickup');
221
- setError(message);
222
- } finally {
223
- setLoading(false);
224
- }
225
- }
226
-
227
- if (initializing) {
228
- return (
229
- <div className="flex min-h-[60vh] items-center justify-center">
230
- <LoadingSpinner size="lg" />
231
- </div>
232
- );
233
- }
234
-
235
- // Empty cart
236
- if (!cart || cart.items.length === 0) {
237
- return (
238
- <div className="mx-auto max-w-7xl px-4 py-16 text-center sm:px-6 lg:px-8">
239
- <h1 className="text-foreground text-2xl font-bold">{t('emptyCart')}</h1>
240
- <p className="text-muted-foreground mt-2">{t('emptyCartSubtitle')}</p>
241
- <Link
242
- href="/products"
243
- className="bg-primary text-primary-foreground mt-6 inline-flex items-center rounded px-6 py-3 font-medium transition-opacity hover:opacity-90"
244
- >
245
- {tc('shopNow')}
246
- </Link>
247
- </div>
248
- );
249
- }
250
-
251
- if (error && !checkout) {
252
- return (
253
- <div className="mx-auto max-w-7xl px-4 py-16 text-center sm:px-6 lg:px-8">
254
- <h1 className="text-foreground text-2xl font-bold">{t('errorTitle')}</h1>
255
- <p className="text-destructive mt-2">{error}</p>
256
- <Link
257
- href="/cart"
258
- className="bg-primary text-primary-foreground mt-6 inline-flex items-center rounded px-6 py-3 font-medium transition-opacity hover:opacity-90"
259
- >
260
- {t('returnToCart')}
261
- </Link>
262
- </div>
263
- );
264
- }
265
-
266
- const steps: { key: CheckoutStep; label: string }[] =
267
- pickupLocations.length > 0
268
- ? deliveryType === 'pickup'
269
- ? [
270
- { key: 'method', label: t('stepMethod') },
271
- { key: 'pickup', label: t('stepPickup') },
272
- { key: 'payment', label: t('stepPayment') },
273
- ]
274
- : [
275
- { key: 'method', label: t('stepMethod') },
276
- { key: 'address', label: t('stepAddress') },
277
- { key: 'shipping', label: t('stepShipping') },
278
- { key: 'payment', label: t('stepPayment') },
279
- ]
280
- : [
281
- { key: 'address', label: t('stepAddress') },
282
- { key: 'shipping', label: t('stepShipping') },
283
- { key: 'payment', label: t('stepPayment') },
284
- ];
285
-
286
- const currentStepIndex = steps.findIndex((s) => s.key === step);
287
-
288
- return (
289
- <div className="mx-auto max-w-7xl px-4 py-8 sm:px-6 lg:px-8">
290
- <h1 className="text-foreground mb-6 text-2xl font-bold">{t('title')}</h1>
291
-
292
- {/* Canceled payment banner */}
293
- {canceled && (
294
- <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">
295
- {t('paymentCanceledBanner')}
296
- </div>
297
- )}
298
-
299
- {/* Reservation countdown */}
300
- {checkout?.reservation?.hasReservation && (
301
- <ReservationCountdown reservation={checkout.reservation} className="mb-6" />
302
- )}
303
-
304
- {/* Step indicator */}
305
- <div className="mb-8 flex items-center gap-2">
306
- {steps.map((s, index) => (
307
- <div key={s.key} className="flex items-center">
308
- {index > 0 && (
309
- <div
310
- className={cn(
311
- 'mx-2 h-px w-8 sm:w-12',
312
- index <= currentStepIndex ? 'bg-primary' : 'bg-border'
313
- )}
314
- />
315
- )}
316
- <div className="flex items-center gap-2">
317
- <div
318
- className={cn(
319
- 'flex h-7 w-7 items-center justify-center rounded-full text-xs font-medium',
320
- index < currentStepIndex
321
- ? 'bg-primary text-primary-foreground'
322
- : index === currentStepIndex
323
- ? 'bg-primary text-primary-foreground'
324
- : 'bg-muted text-muted-foreground'
325
- )}
326
- >
327
- {index < currentStepIndex ? (
328
- <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
329
- <path
330
- strokeLinecap="round"
331
- strokeLinejoin="round"
332
- strokeWidth={2}
333
- d="M5 13l4 4L19 7"
334
- />
335
- </svg>
336
- ) : (
337
- index + 1
338
- )}
339
- </div>
340
- <span
341
- className={cn(
342
- 'hidden text-sm sm:block',
343
- index <= currentStepIndex
344
- ? 'text-foreground font-medium'
345
- : 'text-muted-foreground'
346
- )}
347
- >
348
- {s.label}
349
- </span>
350
- </div>
351
- </div>
352
- ))}
353
- </div>
354
-
355
- {/* Error banner */}
356
- {error && checkout && (
357
- <div className="bg-destructive/10 border-destructive/20 text-destructive mb-6 rounded-lg border px-4 py-3 text-sm">
358
- {error}
359
- </div>
360
- )}
361
-
362
- <div className="grid grid-cols-1 gap-8 lg:grid-cols-3">
363
- {/* Main content */}
364
- <div className="lg:col-span-2">
365
- {/* Delivery Method */}
366
- {step === 'method' && (
367
- <div>
368
- <h2 className="text-foreground mb-4 text-lg font-semibold">{t('deliveryMethod')}</h2>
369
- <DeliveryMethodStep onSelect={handleDeliveryTypeSelect} />
370
- </div>
371
- )}
372
-
373
- {/* Address */}
374
- {step === 'address' && (
375
- <div>
376
- <div className="mb-4 flex items-center justify-between">
377
- <h2 className="text-foreground text-lg font-semibold">{t('shippingAddress')}</h2>
378
- {pickupLocations.length > 0 && (
379
- <button
380
- type="button"
381
- onClick={() => setStep('method')}
382
- className="text-primary text-sm hover:underline"
383
- >
384
- {t('changeMethod')}
385
- </button>
386
- )}
387
- </div>
388
- <CheckoutForm
389
- onSubmit={handleAddressSubmit}
390
- loading={loading}
391
- destinations={destinations}
392
- initialValues={
393
- checkout?.shippingAddress
394
- ? {
395
- email: checkout.email || '',
396
- firstName: checkout.shippingAddress.firstName,
397
- lastName: checkout.shippingAddress.lastName,
398
- line1: checkout.shippingAddress.line1,
399
- line2: checkout.shippingAddress.line2 || '',
400
- city: checkout.shippingAddress.city,
401
- region: checkout.shippingAddress.region || '',
402
- postalCode: checkout.shippingAddress.postalCode,
403
- country: checkout.shippingAddress.country,
404
- phone: checkout.shippingAddress.phone || '',
405
- }
406
- : undefined
407
- }
408
- />
409
- </div>
410
- )}
411
-
412
- {/* Step 2: Shipping */}
413
- {step === 'shipping' && (
414
- <div>
415
- <div className="mb-4 flex items-center justify-between">
416
- <h2 className="text-foreground text-lg font-semibold">{t('shippingMethod')}</h2>
417
- <button
418
- type="button"
419
- onClick={() => setStep('address')}
420
- className="text-primary text-sm hover:underline"
421
- >
422
- {t('editAddress')}
423
- </button>
424
- </div>
425
-
426
- <ShippingStep
427
- rates={shippingRates}
428
- selectedRateId={selectedRateId}
429
- onSelect={handleShippingSelect}
430
- loading={loading}
431
- />
432
- </div>
433
- )}
434
-
435
- {/* Pickup */}
436
- {step === 'pickup' && (
437
- <div>
438
- <div className="mb-4 flex items-center justify-between">
439
- <h2 className="text-foreground text-lg font-semibold">{t('pickupLocation')}</h2>
440
- <button
441
- type="button"
442
- onClick={() => setStep('method')}
443
- className="text-primary text-sm hover:underline"
444
- >
445
- {t('changeMethod')}
446
- </button>
447
- </div>
448
- <PickupStep
449
- locations={pickupLocations}
450
- onSelect={handlePickupSelect}
451
- loading={loading}
452
- initialEmail={checkout?.email || ''}
453
- />
454
- </div>
455
- )}
456
-
457
- {/* Payment */}
458
- {step === 'payment' && checkout && (
459
- <div>
460
- <div className="mb-4 flex items-center justify-between">
461
- <h2 className="text-foreground text-lg font-semibold">{t('payment')}</h2>
462
- <button
463
- type="button"
464
- onClick={() => setStep(deliveryType === 'pickup' ? 'pickup' : 'shipping')}
465
- className="text-primary text-sm hover:underline"
466
- >
467
- {deliveryType === 'pickup' ? t('changePickup') : t('changeShipping')}
468
- </button>
469
- </div>
470
-
471
- <PaymentStep checkoutId={checkout.id} />
472
- </div>
473
- )}
474
- </div>
475
-
476
- {/* Order summary sidebar */}
477
- <div className="lg:col-span-1">
478
- <div className="bg-muted/50 border-border sticky top-24 rounded-lg border p-6">
479
- <h3 className="text-foreground mb-4 text-lg font-semibold">{t('orderSummary')}</h3>
480
-
481
- {/* Line items */}
482
- {checkout?.lineItems && checkout.lineItems.length > 0 ? (
483
- <div className="mb-4 space-y-3">
484
- {checkout.lineItems.map((item) => {
485
- const imageUrl = item.product.images?.[0]?.url || null;
486
- const name = item.variant?.name || item.product.name;
487
- const lineTotal = parseFloat(item.unitPrice) * item.quantity;
488
-
489
- return (
490
- <div key={item.id} className="flex gap-3">
491
- <div className="bg-muted relative h-12 w-12 flex-shrink-0 overflow-hidden rounded">
492
- {imageUrl ? (
493
- <Image
494
- src={imageUrl}
495
- alt={name}
496
- fill
497
- sizes="48px"
498
- className="object-cover"
499
- />
500
- ) : (
501
- <div className="text-muted-foreground absolute inset-0 flex items-center justify-center">
502
- <svg
503
- className="h-5 w-5"
504
- fill="none"
505
- viewBox="0 0 24 24"
506
- stroke="currentColor"
507
- >
508
- <path
509
- strokeLinecap="round"
510
- strokeLinejoin="round"
511
- strokeWidth={1.5}
512
- 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"
513
- />
514
- </svg>
515
- </div>
516
- )}
517
- </div>
518
-
519
- <div className="min-w-0 flex-1">
520
- <p className="text-foreground truncate text-sm">{name}</p>
521
- <p className="text-muted-foreground text-xs">
522
- {tc('qty')} {item.quantity}
523
- </p>
524
- </div>
525
-
526
- <span className="text-foreground flex-shrink-0 text-sm font-medium">
527
- {formatPrice(lineTotal, { currency }) as string}
528
- </span>
529
- </div>
530
- );
531
- })}
532
- </div>
533
- ) : (
534
- // Fallback to cart items if checkout line items aren't loaded yet
535
- cart && (
536
- <div className="mb-4 space-y-2">
537
- <p className="text-muted-foreground text-sm">
538
- {cart.items.length} {cart.items.length === 1 ? tc('item') : tc('items')}
539
- </p>
540
- </div>
541
- )
542
- )}
543
-
544
- {/* Totals */}
545
- {checkout && (
546
- <div className="border-border space-y-2 border-t pt-4 text-sm">
547
- <div className="flex items-center justify-between">
548
- <span className="text-muted-foreground">{tc('subtotal')}</span>
549
- <span className="text-foreground">
550
- {formatPrice(parseFloat(checkout.subtotal), { currency }) as string}
551
- </span>
552
- </div>
553
-
554
- {parseFloat(checkout.discountAmount) > 0 && (
555
- <div className="flex items-center justify-between">
556
- <span className="text-muted-foreground">{tc('discount')}</span>
557
- <span className="text-destructive">
558
- -{formatPrice(parseFloat(checkout.discountAmount), { currency }) as string}
559
- </span>
560
- </div>
561
- )}
562
-
563
- {(parseFloat(checkout.shippingAmount) > 0 ||
564
- checkout.deliveryType === 'pickup') && (
565
- <div className="flex items-center justify-between">
566
- <span className="text-muted-foreground">
567
- {checkout.deliveryType === 'pickup' ? tc('pickup') : tc('shipping')}
568
- </span>
569
- <span className="text-foreground">
570
- {parseFloat(checkout.shippingAmount) === 0
571
- ? tc('free')
572
- : (formatPrice(parseFloat(checkout.shippingAmount), {
573
- currency,
574
- }) as string)}
575
- </span>
576
- </div>
577
- )}
578
-
579
- <TaxDisplay
580
- addressSet={!!checkout.shippingAddress}
581
- taxAmount={checkout.taxAmount}
582
- taxBreakdown={checkout.taxBreakdown}
583
- />
584
-
585
- <div className="border-border mt-2 border-t pt-2">
586
- <div className="flex items-center justify-between">
587
- <span className="text-foreground font-semibold">{tc('total')}</span>
588
- <span className="text-foreground text-base font-semibold">
589
- {formatPrice(parseFloat(checkout.total), { currency }) as string}
590
- </span>
591
- </div>
592
- </div>
593
- </div>
594
- )}
595
- </div>
596
- </div>
597
- </div>
598
- </div>
599
- );
600
- }
601
-
602
- export default function CheckoutPage() {
603
- return (
604
- <Suspense
605
- fallback={
606
- <div className="flex min-h-[60vh] items-center justify-center">
607
- <LoadingSpinner size="lg" />
608
- </div>
609
- }
610
- >
611
- <CheckoutContent />
612
- </Suspense>
613
- );
614
- }
1
+ 'use client';
2
+
3
+ import { Suspense, useEffect, useState, useCallback } from 'react';
4
+ import { useSearchParams } from 'next/navigation';
5
+ import Image from 'next/image';
6
+ import Link from 'next/link';
7
+ import type {
8
+ Checkout,
9
+ ShippingRate,
10
+ SetShippingAddressDto,
11
+ ShippingDestinations,
12
+ PickupLocation,
13
+ } from 'brainerce';
14
+ import { formatPrice } from 'brainerce';
15
+ import { getClient } from '@/lib/brainerce';
16
+ import { useStoreInfo, useAuth, useCart } from '@/providers/store-provider';
17
+ import { CheckoutForm } from '@/components/checkout/checkout-form';
18
+ import { ShippingStep } from '@/components/checkout/shipping-step';
19
+ import { PaymentStep } from '@/components/checkout/payment-step';
20
+ import { DeliveryMethodStep } from '@/components/checkout/delivery-method-step';
21
+ import { PickupStep } from '@/components/checkout/pickup-step';
22
+ import { TaxDisplay } from '@/components/checkout/tax-display';
23
+ import { ReservationCountdown } from '@/components/cart/reservation-countdown';
24
+ import { LoadingSpinner } from '@/components/shared/loading-spinner';
25
+ import { useTranslations } from '@/lib/translations';
26
+ import { cn } from '@/lib/utils';
27
+
28
+ type CheckoutStep = 'method' | 'address' | 'shipping' | 'pickup' | 'payment';
29
+
30
+ function CheckoutContent() {
31
+ const searchParams = useSearchParams();
32
+ const { storeInfo } = useStoreInfo();
33
+ const { isLoggedIn } = useAuth();
34
+ const { cart } = useCart();
35
+ const currency = storeInfo?.currency || 'USD';
36
+ const t = useTranslations('checkout');
37
+ const tc = useTranslations('common');
38
+
39
+ const [step, setStep] = useState<CheckoutStep>('address');
40
+ const [checkout, setCheckout] = useState<Checkout | null>(null);
41
+ const [shippingRates, setShippingRates] = useState<ShippingRate[]>([]);
42
+ const [selectedRateId, setSelectedRateId] = useState<string | null>(null);
43
+ const [loading, setLoading] = useState(false);
44
+ const [initializing, setInitializing] = useState(true);
45
+ const [error, setError] = useState<string | null>(null);
46
+ const [destinations, setDestinations] = useState<ShippingDestinations | null>(null);
47
+ const [pickupLocations, setPickupLocations] = useState<PickupLocation[]>([]);
48
+ const [deliveryType, setDeliveryType] = useState<'shipping' | 'pickup'>('shipping');
49
+
50
+ // Check for returning from canceled payment
51
+ const canceled = searchParams.get('canceled') === 'true';
52
+ const existingCheckoutId = searchParams.get('checkout_id');
53
+
54
+ // Initialize or resume checkout
55
+ const initCheckout = useCallback(async () => {
56
+ try {
57
+ setInitializing(true);
58
+ setError(null);
59
+ const client = getClient();
60
+
61
+ // Fetch shipping destinations and pickup locations in parallel
62
+ client
63
+ .getShippingDestinations()
64
+ .then(setDestinations)
65
+ .catch(() => {});
66
+
67
+ const locations = await client.getPickupLocations().catch(() => [] as PickupLocation[]);
68
+ setPickupLocations(locations);
69
+
70
+ // If returning with existing checkout ID, resume it
71
+ if (existingCheckoutId) {
72
+ const existing = await client.getCheckout(existingCheckoutId);
73
+ setCheckout(existing);
74
+
75
+ // Determine step based on checkout state
76
+ if (existing.deliveryType === 'pickup' && existing.pickupLocation) {
77
+ setDeliveryType('pickup');
78
+ setStep('payment');
79
+ } else if (existing.shippingAddress && existing.shippingRateId) {
80
+ setStep('payment');
81
+ } else if (existing.shippingAddress) {
82
+ // Fetch shipping rates
83
+ const rates = await client.getShippingRates(existing.id);
84
+ setShippingRates(rates);
85
+ setStep('shipping');
86
+ } else if (locations.length > 0) {
87
+ setStep('method');
88
+ }
89
+ return;
90
+ }
91
+
92
+ // Create new checkout — cart is always server-side now
93
+ if (cart && cart.id) {
94
+ if (isLoggedIn) {
95
+ // Logged-in user: create checkout from customer cart
96
+ const newCheckout = await client.createCheckout({ cartId: cart.id });
97
+ setCheckout(newCheckout);
98
+ } else {
99
+ // Guest user: start guest checkout (creates checkout from session cart)
100
+ const result = await client.startGuestCheckout();
101
+ if (result.tracked) {
102
+ const newCheckout = await client.getCheckout(result.checkoutId);
103
+ setCheckout(newCheckout);
104
+ } else {
105
+ setError(t('failedToStartCheckout'));
106
+ }
107
+ }
108
+ } else {
109
+ setError(t('cartIsEmpty'));
110
+ }
111
+
112
+ // If pickup locations exist, start with delivery method selection
113
+ if (locations.length > 0) {
114
+ setStep('method');
115
+ }
116
+ } catch (err) {
117
+ const message = err instanceof Error ? err.message : t('failedToInitCheckout');
118
+ setError(message);
119
+ } finally {
120
+ setInitializing(false);
121
+ }
122
+ }, [existingCheckoutId, isLoggedIn, cart]);
123
+
124
+ const cartLoaded = cart !== null;
125
+ useEffect(() => {
126
+ if (cartLoaded) {
127
+ initCheckout();
128
+ }
129
+ }, [cartLoaded, initCheckout]);
130
+
131
+ // Handle shipping address submission
132
+ async function handleAddressSubmit(address: SetShippingAddressDto) {
133
+ if (!checkout) return;
134
+
135
+ try {
136
+ setLoading(true);
137
+ setError(null);
138
+ const client = getClient();
139
+
140
+ const response = await client.setShippingAddress(checkout.id, address);
141
+ setCheckout(response.checkout);
142
+ setShippingRates(response.rates);
143
+ setStep('shipping');
144
+ } catch (err) {
145
+ const message = err instanceof Error ? err.message : t('failedToSaveAddress');
146
+ setError(message);
147
+ } finally {
148
+ setLoading(false);
149
+ }
150
+ }
151
+
152
+ // Handle shipping method selection
153
+ async function handleShippingSelect(rateId: string) {
154
+ if (!checkout) return;
155
+
156
+ try {
157
+ setLoading(true);
158
+ setError(null);
159
+ setSelectedRateId(rateId);
160
+ const client = getClient();
161
+
162
+ const updated = await client.selectShippingMethod(checkout.id, rateId);
163
+ setCheckout(updated);
164
+ setStep('payment');
165
+ } catch (err) {
166
+ const message = err instanceof Error ? err.message : t('failedToSelectShipping');
167
+ setError(message);
168
+ } finally {
169
+ setLoading(false);
170
+ }
171
+ }
172
+
173
+ // Handle delivery method selection
174
+ async function handleDeliveryTypeSelect(method: 'shipping' | 'pickup') {
175
+ if (!checkout) return;
176
+
177
+ try {
178
+ setLoading(true);
179
+ setError(null);
180
+ setDeliveryType(method);
181
+ const client = getClient();
182
+
183
+ await client.setDeliveryType(checkout.id, method);
184
+
185
+ if (method === 'shipping') {
186
+ setStep('address');
187
+ } else {
188
+ setStep('pickup');
189
+ }
190
+ } catch (err) {
191
+ const message = err instanceof Error ? err.message : t('failedToSetDeliveryMethod');
192
+ setError(message);
193
+ } finally {
194
+ setLoading(false);
195
+ }
196
+ }
197
+
198
+ // Handle pickup location selection
199
+ async function handlePickupSelect(
200
+ locationId: string,
201
+ customerInfo: { email: string; firstName?: string; lastName?: string; phone?: string }
202
+ ) {
203
+ if (!checkout) return;
204
+
205
+ try {
206
+ setLoading(true);
207
+ setError(null);
208
+ const client = getClient();
209
+
210
+ const updated = await client.selectPickupLocation(checkout.id, {
211
+ pickupRateId: locationId,
212
+ email: customerInfo.email,
213
+ firstName: customerInfo.firstName,
214
+ lastName: customerInfo.lastName,
215
+ phone: customerInfo.phone,
216
+ });
217
+ setCheckout(updated);
218
+ setStep('payment');
219
+ } catch (err) {
220
+ const message = err instanceof Error ? err.message : t('failedToSelectPickup');
221
+ setError(message);
222
+ } finally {
223
+ setLoading(false);
224
+ }
225
+ }
226
+
227
+ if (initializing) {
228
+ return (
229
+ <div className="flex min-h-[60vh] items-center justify-center">
230
+ <LoadingSpinner size="lg" />
231
+ </div>
232
+ );
233
+ }
234
+
235
+ // Empty cart
236
+ if (!cart || cart.items.length === 0) {
237
+ return (
238
+ <div className="mx-auto max-w-7xl px-4 py-16 text-center sm:px-6 lg:px-8">
239
+ <h1 className="text-foreground text-2xl font-bold">{t('emptyCart')}</h1>
240
+ <p className="text-muted-foreground mt-2">{t('emptyCartSubtitle')}</p>
241
+ <Link
242
+ href="/products"
243
+ className="bg-primary text-primary-foreground mt-6 inline-flex items-center rounded px-6 py-3 font-medium transition-opacity hover:opacity-90"
244
+ >
245
+ {tc('shopNow')}
246
+ </Link>
247
+ </div>
248
+ );
249
+ }
250
+
251
+ if (error && !checkout) {
252
+ return (
253
+ <div className="mx-auto max-w-7xl px-4 py-16 text-center sm:px-6 lg:px-8">
254
+ <h1 className="text-foreground text-2xl font-bold">{t('errorTitle')}</h1>
255
+ <p className="text-destructive mt-2">{error}</p>
256
+ <Link
257
+ href="/cart"
258
+ className="bg-primary text-primary-foreground mt-6 inline-flex items-center rounded px-6 py-3 font-medium transition-opacity hover:opacity-90"
259
+ >
260
+ {t('returnToCart')}
261
+ </Link>
262
+ </div>
263
+ );
264
+ }
265
+
266
+ const steps: { key: CheckoutStep; label: string }[] =
267
+ pickupLocations.length > 0
268
+ ? deliveryType === 'pickup'
269
+ ? [
270
+ { key: 'method', label: t('stepMethod') },
271
+ { key: 'pickup', label: t('stepPickup') },
272
+ { key: 'payment', label: t('stepPayment') },
273
+ ]
274
+ : [
275
+ { key: 'method', label: t('stepMethod') },
276
+ { key: 'address', label: t('stepAddress') },
277
+ { key: 'shipping', label: t('stepShipping') },
278
+ { key: 'payment', label: t('stepPayment') },
279
+ ]
280
+ : [
281
+ { key: 'address', label: t('stepAddress') },
282
+ { key: 'shipping', label: t('stepShipping') },
283
+ { key: 'payment', label: t('stepPayment') },
284
+ ];
285
+
286
+ const currentStepIndex = steps.findIndex((s) => s.key === step);
287
+
288
+ return (
289
+ <div className="mx-auto max-w-7xl px-4 py-8 sm:px-6 lg:px-8">
290
+ <h1 className="text-foreground mb-6 text-2xl font-bold">{t('title')}</h1>
291
+
292
+ {/* Canceled payment banner */}
293
+ {canceled && (
294
+ <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">
295
+ {t('paymentCanceledBanner')}
296
+ </div>
297
+ )}
298
+
299
+ {/* Reservation countdown */}
300
+ {checkout?.reservation?.hasReservation && (
301
+ <ReservationCountdown reservation={checkout.reservation} className="mb-6" />
302
+ )}
303
+
304
+ {/* Step indicator */}
305
+ <div className="mb-8 flex items-center gap-2">
306
+ {steps.map((s, index) => (
307
+ <div key={s.key} className="flex items-center">
308
+ {index > 0 && (
309
+ <div
310
+ className={cn(
311
+ 'mx-2 h-px w-8 sm:w-12',
312
+ index <= currentStepIndex ? 'bg-primary' : 'bg-border'
313
+ )}
314
+ />
315
+ )}
316
+ <div className="flex items-center gap-2">
317
+ <div
318
+ className={cn(
319
+ 'flex h-7 w-7 items-center justify-center rounded-full text-xs font-medium',
320
+ index < currentStepIndex
321
+ ? 'bg-primary text-primary-foreground'
322
+ : index === currentStepIndex
323
+ ? 'bg-primary text-primary-foreground'
324
+ : 'bg-muted text-muted-foreground'
325
+ )}
326
+ >
327
+ {index < currentStepIndex ? (
328
+ <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
329
+ <path
330
+ strokeLinecap="round"
331
+ strokeLinejoin="round"
332
+ strokeWidth={2}
333
+ d="M5 13l4 4L19 7"
334
+ />
335
+ </svg>
336
+ ) : (
337
+ index + 1
338
+ )}
339
+ </div>
340
+ <span
341
+ className={cn(
342
+ 'hidden text-sm sm:block',
343
+ index <= currentStepIndex
344
+ ? 'text-foreground font-medium'
345
+ : 'text-muted-foreground'
346
+ )}
347
+ >
348
+ {s.label}
349
+ </span>
350
+ </div>
351
+ </div>
352
+ ))}
353
+ </div>
354
+
355
+ {/* Error banner */}
356
+ {error && checkout && (
357
+ <div className="bg-destructive/10 border-destructive/20 text-destructive mb-6 rounded-lg border px-4 py-3 text-sm">
358
+ {error}
359
+ </div>
360
+ )}
361
+
362
+ <div className="grid grid-cols-1 gap-8 lg:grid-cols-3">
363
+ {/* Main content */}
364
+ <div className="lg:col-span-2">
365
+ {/* Delivery Method */}
366
+ {step === 'method' && (
367
+ <div>
368
+ <h2 className="text-foreground mb-4 text-lg font-semibold">{t('deliveryMethod')}</h2>
369
+ <DeliveryMethodStep onSelect={handleDeliveryTypeSelect} />
370
+ </div>
371
+ )}
372
+
373
+ {/* Address */}
374
+ {step === 'address' && (
375
+ <div>
376
+ <div className="mb-4 flex items-center justify-between">
377
+ <h2 className="text-foreground text-lg font-semibold">{t('shippingAddress')}</h2>
378
+ {pickupLocations.length > 0 && (
379
+ <button
380
+ type="button"
381
+ onClick={() => setStep('method')}
382
+ className="text-primary text-sm hover:underline"
383
+ >
384
+ {t('changeMethod')}
385
+ </button>
386
+ )}
387
+ </div>
388
+ <CheckoutForm
389
+ onSubmit={handleAddressSubmit}
390
+ loading={loading}
391
+ destinations={destinations}
392
+ initialValues={
393
+ checkout?.shippingAddress
394
+ ? {
395
+ email: checkout.email || '',
396
+ firstName: checkout.shippingAddress.firstName,
397
+ lastName: checkout.shippingAddress.lastName,
398
+ line1: checkout.shippingAddress.line1,
399
+ line2: checkout.shippingAddress.line2 || '',
400
+ city: checkout.shippingAddress.city,
401
+ region: checkout.shippingAddress.region || '',
402
+ postalCode: checkout.shippingAddress.postalCode,
403
+ country: checkout.shippingAddress.country,
404
+ phone: checkout.shippingAddress.phone || '',
405
+ }
406
+ : undefined
407
+ }
408
+ />
409
+ </div>
410
+ )}
411
+
412
+ {/* Step 2: Shipping */}
413
+ {step === 'shipping' && (
414
+ <div>
415
+ <div className="mb-4 flex items-center justify-between">
416
+ <h2 className="text-foreground text-lg font-semibold">{t('shippingMethod')}</h2>
417
+ <button
418
+ type="button"
419
+ onClick={() => setStep('address')}
420
+ className="text-primary text-sm hover:underline"
421
+ >
422
+ {t('editAddress')}
423
+ </button>
424
+ </div>
425
+
426
+ <ShippingStep
427
+ rates={shippingRates}
428
+ selectedRateId={selectedRateId}
429
+ onSelect={handleShippingSelect}
430
+ loading={loading}
431
+ />
432
+ </div>
433
+ )}
434
+
435
+ {/* Pickup */}
436
+ {step === 'pickup' && (
437
+ <div>
438
+ <div className="mb-4 flex items-center justify-between">
439
+ <h2 className="text-foreground text-lg font-semibold">{t('pickupLocation')}</h2>
440
+ <button
441
+ type="button"
442
+ onClick={() => setStep('method')}
443
+ className="text-primary text-sm hover:underline"
444
+ >
445
+ {t('changeMethod')}
446
+ </button>
447
+ </div>
448
+ <PickupStep
449
+ locations={pickupLocations}
450
+ onSelect={handlePickupSelect}
451
+ loading={loading}
452
+ initialEmail={checkout?.email || ''}
453
+ />
454
+ </div>
455
+ )}
456
+
457
+ {/* Payment */}
458
+ {step === 'payment' && checkout && (
459
+ <div>
460
+ <div className="mb-4 flex items-center justify-between">
461
+ <h2 className="text-foreground text-lg font-semibold">{t('payment')}</h2>
462
+ <button
463
+ type="button"
464
+ onClick={() => setStep(deliveryType === 'pickup' ? 'pickup' : 'shipping')}
465
+ className="text-primary text-sm hover:underline"
466
+ >
467
+ {deliveryType === 'pickup' ? t('changePickup') : t('changeShipping')}
468
+ </button>
469
+ </div>
470
+
471
+ <PaymentStep checkoutId={checkout.id} />
472
+ </div>
473
+ )}
474
+ </div>
475
+
476
+ {/* Order summary sidebar */}
477
+ <div className="lg:col-span-1">
478
+ <div className="bg-muted/50 border-border sticky top-24 rounded-lg border p-6">
479
+ <h3 className="text-foreground mb-4 text-lg font-semibold">{t('orderSummary')}</h3>
480
+
481
+ {/* Line items */}
482
+ {checkout?.lineItems && checkout.lineItems.length > 0 ? (
483
+ <div className="mb-4 space-y-3">
484
+ {checkout.lineItems.map((item) => {
485
+ const imageUrl = item.product.images?.[0]?.url || null;
486
+ const name = item.variant?.name || item.product.name;
487
+ const lineTotal = parseFloat(item.unitPrice) * item.quantity;
488
+
489
+ return (
490
+ <div key={item.id} className="flex gap-3">
491
+ <div className="bg-muted relative h-12 w-12 flex-shrink-0 overflow-hidden rounded">
492
+ {imageUrl ? (
493
+ <Image
494
+ src={imageUrl}
495
+ alt={name}
496
+ fill
497
+ sizes="48px"
498
+ className="object-cover"
499
+ />
500
+ ) : (
501
+ <div className="text-muted-foreground absolute inset-0 flex items-center justify-center">
502
+ <svg
503
+ className="h-5 w-5"
504
+ fill="none"
505
+ viewBox="0 0 24 24"
506
+ stroke="currentColor"
507
+ >
508
+ <path
509
+ strokeLinecap="round"
510
+ strokeLinejoin="round"
511
+ strokeWidth={1.5}
512
+ 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"
513
+ />
514
+ </svg>
515
+ </div>
516
+ )}
517
+ </div>
518
+
519
+ <div className="min-w-0 flex-1">
520
+ <p className="text-foreground truncate text-sm">{name}</p>
521
+ <p className="text-muted-foreground text-xs">
522
+ {tc('qty')} {item.quantity}
523
+ </p>
524
+ </div>
525
+
526
+ <span className="text-foreground flex-shrink-0 text-sm font-medium">
527
+ {formatPrice(lineTotal, { currency }) as string}
528
+ </span>
529
+ </div>
530
+ );
531
+ })}
532
+ </div>
533
+ ) : (
534
+ // Fallback to cart items if checkout line items aren't loaded yet
535
+ cart && (
536
+ <div className="mb-4 space-y-2">
537
+ <p className="text-muted-foreground text-sm">
538
+ {cart.items.length} {cart.items.length === 1 ? tc('item') : tc('items')}
539
+ </p>
540
+ </div>
541
+ )
542
+ )}
543
+
544
+ {/* Totals */}
545
+ {checkout && (
546
+ <div className="border-border space-y-2 border-t pt-4 text-sm">
547
+ <div className="flex items-center justify-between">
548
+ <span className="text-muted-foreground">{tc('subtotal')}</span>
549
+ <span className="text-foreground">
550
+ {formatPrice(parseFloat(checkout.subtotal), { currency }) as string}
551
+ </span>
552
+ </div>
553
+
554
+ {parseFloat(checkout.discountAmount) > 0 && (
555
+ <div className="flex items-center justify-between">
556
+ <span className="text-muted-foreground">{tc('discount')}</span>
557
+ <span className="text-destructive">
558
+ -{formatPrice(parseFloat(checkout.discountAmount), { currency }) as string}
559
+ </span>
560
+ </div>
561
+ )}
562
+
563
+ {(parseFloat(checkout.shippingAmount) > 0 ||
564
+ checkout.deliveryType === 'pickup') && (
565
+ <div className="flex items-center justify-between">
566
+ <span className="text-muted-foreground">
567
+ {checkout.deliveryType === 'pickup' ? tc('pickup') : tc('shipping')}
568
+ </span>
569
+ <span className="text-foreground">
570
+ {parseFloat(checkout.shippingAmount) === 0
571
+ ? tc('free')
572
+ : (formatPrice(parseFloat(checkout.shippingAmount), {
573
+ currency,
574
+ }) as string)}
575
+ </span>
576
+ </div>
577
+ )}
578
+
579
+ <TaxDisplay
580
+ addressSet={!!checkout.shippingAddress}
581
+ taxAmount={checkout.taxAmount}
582
+ taxBreakdown={checkout.taxBreakdown}
583
+ />
584
+
585
+ <div className="border-border mt-2 border-t pt-2">
586
+ <div className="flex items-center justify-between">
587
+ <span className="text-foreground font-semibold">{tc('total')}</span>
588
+ <span className="text-foreground text-base font-semibold">
589
+ {formatPrice(parseFloat(checkout.total), { currency }) as string}
590
+ </span>
591
+ </div>
592
+ </div>
593
+ </div>
594
+ )}
595
+ </div>
596
+ </div>
597
+ </div>
598
+ </div>
599
+ );
600
+ }
601
+
602
+ export default function CheckoutPage() {
603
+ return (
604
+ <Suspense
605
+ fallback={
606
+ <div className="flex min-h-[60vh] items-center justify-center">
607
+ <LoadingSpinner size="lg" />
608
+ </div>
609
+ }
610
+ >
611
+ <CheckoutContent />
612
+ </Suspense>
613
+ );
614
+ }