create-brainerce-store 1.78.0 → 1.80.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 +27 -2
  2. package/messages/en.json +12 -3
  3. package/messages/he.json +12 -3
  4. package/package.json +10 -1
  5. package/templates/nextjs/base/.eslintrc.json +2 -0
  6. package/templates/nextjs/base/AGENTS.md.ejs +23 -5
  7. package/templates/nextjs/base/CLAUDE.md.ejs +23 -5
  8. package/templates/nextjs/base/src/app/checkout/page.tsx +19 -2
  9. package/templates/nextjs/base/src/app/order-status/page.tsx +18 -3
  10. package/templates/nextjs/base/src/app/products/[slug]/page.tsx +220 -214
  11. package/templates/nextjs/base/src/components/account/order-history.tsx +11 -4
  12. package/templates/nextjs/base/src/components/account/profile-section.tsx +7 -1
  13. package/templates/nextjs/base/src/components/auth/register-form.tsx +18 -1
  14. package/templates/nextjs/base/src/components/checkout/payment-step.tsx +14 -2
  15. package/templates/nextjs/base/src/components/tracking-bootstrap.tsx +1 -1
  16. package/templates/nextjs/base/src/core/hooks/use-product-page.ts +343 -328
  17. package/templates/nextjs/base/src/core/lib/kit.ts +88 -0
  18. package/templates/nextjs/base/src/ui/cart/gift-card-input.tsx +87 -12
  19. package/templates/nextjs/base/src/ui/layout/newsletter-signup.tsx +59 -12
  20. package/templates/nextjs/base/src/ui/product/frequently-bought-together.tsx +205 -197
  21. package/templates/nextjs/base/src/ui/product/product-card.tsx +230 -221
  22. package/templates/nextjs/base/src/ui/product/product-client-section.tsx +524 -493
  23. package/templates/nextjs/base/src/ui/product/recommendation-section.tsx +117 -108
  24. package/templates/nextjs/base/src/ui/product/stock-badge.tsx +23 -3
  25. package/templates/nextjs/designs/atelier/ui/product/frequently-bought-together.tsx +210 -202
  26. package/templates/nextjs/designs/atelier/ui/product/product-card.tsx +251 -242
  27. package/templates/nextjs/designs/atelier/ui/product/product-client-section.tsx +540 -509
  28. package/templates/nextjs/designs/atelier/ui/product/recommendation-section.tsx +110 -101
  29. package/templates/nextjs/designs/atelier/ui/product/stock-badge.tsx +22 -2
  30. package/templates/nextjs/ui-canvas/cart/gift-card-input.tsx +41 -11
  31. package/templates/nextjs/ui-canvas/layout/newsletter-signup.tsx +50 -8
  32. package/templates/nextjs/ui-canvas/product/frequently-bought-together.tsx +182 -174
  33. package/templates/nextjs/ui-canvas/product/product-card.tsx +174 -165
  34. package/templates/nextjs/ui-canvas/product/product-client-section.tsx +31 -0
  35. package/templates/nextjs/ui-canvas/product/recommendation-section.tsx +114 -105
  36. package/templates/nextjs/ui-canvas/product/stock-badge.tsx +22 -2
@@ -1,509 +1,540 @@
1
- 'use client';
2
-
3
- import { useEffect } from 'react';
4
- import { CdnImage as Image } from '@/ui/shared/cdn-image';
5
- import type { Product, ProductMetafield, DownloadFile } from 'brainerce';
6
- import { useProductPage } from '@/core/hooks/use-product-page';
7
- import { PriceDisplay } from '@/ui/product/price-display';
8
- import { VariantSelector } from '@/ui/product/variant-selector';
9
- import { StockBadge } from '@/ui/product/stock-badge';
10
- import { DiscountBadge } from '@/ui/product/discount-badge';
11
- import { BackInStockForm, canOfferStockAlert } from '@/ui/product/back-in-stock-form';
12
- import { RecommendationSection } from '@/ui/product/recommendation-section';
13
- import { FrequentlyBoughtTogether } from '@/ui/product/frequently-bought-together';
14
- import { CustomizationFields } from '@/ui/product/customization-fields';
15
- import { ModifierGroupSelector } from '@/ui/product/modifier-group-selector';
16
- import { useTranslations } from '@/core/lib/translations';
17
- import { flyToCart, firstVisible } from '@/ui/shared/fly-to-cart';
18
- import { openCartDrawer } from '@/ui/cart/cart-drawer';
19
- import { sanitizeProductHtml } from '@/core/lib/sanitize-html';
20
- import { cn } from '@/core/lib/utils';
21
- import {
22
- IconBag,
23
- IconCheck,
24
- IconMinus,
25
- IconPlus,
26
- IconTruck,
27
- IconBadgeCheck,
28
- IconDownload,
29
- } from '@/ui/shared/icons';
30
-
31
- /** Render a metafield value based on its type */
32
- function MetafieldValue({ field }: { field: ProductMetafield }) {
33
- const tc = useTranslations('common');
34
- switch (field.type) {
35
- case 'IMAGE': {
36
- if (!field.value) return <span>-</span>;
37
- return (
38
- <img
39
- src={field.value}
40
- alt={field.definitionName}
41
- className="h-16 w-16 rounded-lg border object-cover"
42
- />
43
- );
44
- }
45
- case 'GALLERY': {
46
- let urls: string[] = [];
47
- try {
48
- const parsed = JSON.parse(field.value);
49
- urls = Array.isArray(parsed)
50
- ? parsed.filter((u: unknown) => typeof u === 'string' && u)
51
- : [];
52
- } catch {
53
- urls = field.value ? [field.value] : [];
54
- }
55
- if (urls.length === 0) return <span>-</span>;
56
- return (
57
- <span className="flex flex-wrap gap-2">
58
- {urls.map((url, i) => (
59
- <img
60
- key={i}
61
- src={url}
62
- alt={`${field.definitionName} ${i + 1}`}
63
- className="h-16 w-16 rounded-lg border object-cover"
64
- />
65
- ))}
66
- </span>
67
- );
68
- }
69
- case 'URL':
70
- return field.value ? (
71
- <a
72
- href={field.value}
73
- target="_blank"
74
- rel="noopener noreferrer"
75
- className="text-primary underline underline-offset-2"
76
- >
77
- {field.value}
78
- </a>
79
- ) : (
80
- <span>-</span>
81
- );
82
- case 'COLOR':
83
- return field.value ? (
84
- <span className="inline-flex items-center gap-2">
85
- <span
86
- aria-hidden="true"
87
- className="inline-block h-4 w-4 rounded-full border"
88
- style={{ backgroundColor: field.value }}
89
- />
90
- {field.value}
91
- </span>
92
- ) : (
93
- <span>-</span>
94
- );
95
- case 'BOOLEAN':
96
- return <span>{field.value === 'true' ? tc('yes') : tc('no')}</span>;
97
- case 'DATE':
98
- case 'DATETIME': {
99
- if (!field.value) return <span>-</span>;
100
- try {
101
- const date = new Date(field.value);
102
- return (
103
- <span>
104
- {field.type === 'DATETIME' ? date.toLocaleString() : date.toLocaleDateString()}
105
- </span>
106
- );
107
- } catch {
108
- return <span>{field.value}</span>;
109
- }
110
- }
111
- default:
112
- return <span>{field.value || '-'}</span>;
113
- }
114
- }
115
-
116
- interface ProductClientSectionProps {
117
- product: Product;
118
- /**
119
- * From `getStoreInfo().stockAlertsEnabled` — the merchant switch for
120
- * back-in-stock alerts on this storefront. Undefined on a public-storefront
121
- * (storeId) client, where the setting does not apply and the feature is on.
122
- */
123
- stockAlertsEnabled?: boolean;
124
- }
125
-
126
- export function ProductClientSection({
127
- product: initialProduct,
128
- stockAlertsEnabled,
129
- }: ProductClientSectionProps) {
130
- const t = useTranslations('productDetail');
131
-
132
- const {
133
- product,
134
- recommendations,
135
- images,
136
- selectedImageIndex,
137
- setSelectedImageIndex,
138
- mainImageUrl,
139
- selectedVariant,
140
- setSelectedVariant,
141
- priceInfo,
142
- displayPrice,
143
- inventory,
144
- canPurchase,
145
- description,
146
- quantity,
147
- setQuantity,
148
- addingToCart,
149
- addedMessage,
150
- handleAddToCart,
151
- customizationFields,
152
- customizationValues,
153
- setCustomizationValues,
154
- customizationErrors,
155
- modifierGroups,
156
- modifierSelections,
157
- setModifierSelection,
158
- modifierError,
159
- } = useProductPage(initialProduct);
160
-
161
- // `addedMessage` flips true only after the server confirms the add (it
162
- // stays false on validation failures), so it is the reliable moment to
163
- // slide the mini-cart open.
164
- useEffect(() => {
165
- if (addedMessage) openCartDrawer();
166
- }, [addedMessage]);
167
-
168
- return (
169
- <article className="container-narrow py-8 lg:py-12">
170
- <div className="grid grid-cols-1 gap-8 lg:grid-cols-2 lg:gap-14">
171
- {/* Image Gallery */}
172
- <figure className="lg:sticky lg:top-24 lg:self-start">
173
- {/* `relative` + `aspect-square` are layout-critical for next/image fill */}
174
- <div
175
- data-pdp-gallery
176
- className="bg-secondary relative aspect-square overflow-hidden rounded-3xl border shadow-[0_28px_60px_-30px_hsl(var(--primary)/0.3)]"
177
- >
178
- {mainImageUrl ? (
179
- <Image
180
- src={mainImageUrl}
181
- alt={product.name}
182
- fill
183
- sizes="(max-width: 1024px) 100vw, 50vw"
184
- priority
185
- className="object-cover"
186
- />
187
- ) : (
188
- <span className="sr-only">{product.name}</span>
189
- )}
190
- </div>
191
-
192
- {/* Thumbnails */}
193
- {images.length > 1 && (
194
- <div className="mt-3 flex flex-wrap gap-2.5">
195
- {images.map((img, idx) => (
196
- <button
197
- key={idx}
198
- type="button"
199
- onClick={() => setSelectedImageIndex(idx)}
200
- aria-pressed={selectedImageIndex === idx}
201
- className={cn(
202
- 'bg-secondary relative h-[4.5rem] w-[4.5rem] overflow-hidden rounded-lg border-2 transition-colors',
203
- selectedImageIndex === idx
204
- ? 'border-primary'
205
- : 'hover:border-border border-transparent'
206
- )}
207
- >
208
- <Image
209
- src={img.url}
210
- alt={img.alt || `${product.name} ${idx + 1}`}
211
- fill
212
- sizes="72px"
213
- className="object-cover"
214
- />
215
- </button>
216
- ))}
217
- </div>
218
- )}
219
- <figcaption className="sr-only">{product.name}</figcaption>
220
- </figure>
221
-
222
- {/* Product Info / buy box */}
223
- <section className="max-w-xl">
224
- {/* Categories */}
225
- {product.categories && product.categories.length > 0 && (
226
- <ul className="mb-3 flex flex-wrap gap-1.5">
227
- {product.categories.map((cat) => (
228
- <li key={cat.id} className="badge-soft">
229
- {cat.name}
230
- </li>
231
- ))}
232
- </ul>
233
- )}
234
-
235
- {/* Brand */}
236
- {(product as { brands?: Array<{ id: string; name: string }> }).brands &&
237
- (product as { brands: Array<{ id: string; name: string }> }).brands.length > 0 && (
238
- <p className="text-muted-foreground mb-1 text-sm">
239
- {t('by')}{' '}
240
- <span className="text-foreground font-medium">
241
- {(product as { brands: Array<{ id: string; name: string }> }).brands
242
- .map((b) => b.name)
243
- .join(', ')}
244
- </span>
245
- </p>
246
- )}
247
-
248
- {/* Title */}
249
- <h1 className="text-3xl sm:text-4xl">{product.name}</h1>
250
-
251
- {/* Tags */}
252
- {(product as unknown as { tags?: Array<{ id: string; name: string }> }).tags &&
253
- (product as unknown as { tags: Array<{ id: string; name: string }> }).tags.length >
254
- 0 && (
255
- <ul className="text-muted-foreground mt-2 flex flex-wrap gap-1.5 text-xs">
256
- {(product as unknown as { tags: Array<{ id: string; name: string }> }).tags.map(
257
- (tag) => (
258
- <li key={tag.id}>#{tag.name}</li>
259
- )
260
- )}
261
- </ul>
262
- )}
263
-
264
- {/* Price + stock */}
265
- <div className="mt-5 flex flex-wrap items-center gap-4 border-b pb-6">
266
- <PriceDisplay
267
- price={displayPrice.price}
268
- salePrice={displayPrice.salePrice ?? undefined}
269
- currency={displayPrice.currency}
270
- size="lg"
271
- />
272
- {/* Active discount rule on this product, as a badge.
273
- `product.discount` is returned by getProductBySlug and is
274
- null/absent when no rule applies, and DiscountBadge returns
275
- null on a falsy `discount`, so this renders nothing on a store
276
- with no discounts configured. */}
277
- <DiscountBadge discount={product.discount} />
278
- {product.isDownloadable ? (
279
- <span className="badge-soft">
280
- <IconDownload size={16} />
281
- {t('instantDownload')}
282
- </span>
283
- ) : (
284
- <StockBadge inventory={inventory} />
285
- )}
286
- </div>
287
-
288
- {/* Downloadable files info */}
289
- {product.isDownloadable && product.downloads && product.downloads.length > 0 && (
290
- <section className="bg-secondary/60 mt-6 rounded-xl border p-4">
291
- <h2 className="text-sm font-semibold">
292
- {t('filesIncluded').replace('{count}', String(product.downloads.length))}
293
- </h2>
294
- <ul className="text-muted-foreground mt-2 space-y-1.5 text-sm">
295
- {product.downloads.map((file: DownloadFile) => (
296
- <li key={file.id} className="flex items-center gap-2">
297
- <IconDownload size={16} />
298
- <span>{file.name}</span>
299
- {file.size && (
300
- <span className="text-xs">
301
- (
302
- {file.size < 1024 * 1024
303
- ? `${(file.size / 1024).toFixed(0)} KB`
304
- : `${(file.size / (1024 * 1024)).toFixed(1)} MB`}
305
- )
306
- </span>
307
- )}
308
- </li>
309
- ))}
310
- </ul>
311
- </section>
312
- )}
313
-
314
- {/* Variant Selector */}
315
- {product.type === 'VARIABLE' && product.variants && product.variants.length > 0 && (
316
- <VariantSelector
317
- product={product}
318
- selectedVariant={selectedVariant}
319
- onVariantChange={setSelectedVariant}
320
- className="mt-6"
321
- />
322
- )}
323
-
324
- {/* Customization Fields (buyer input) */}
325
- {customizationFields.length > 0 && (
326
- <CustomizationFields
327
- fields={customizationFields}
328
- values={customizationValues}
329
- onChange={setCustomizationValues}
330
- errors={customizationErrors}
331
- />
332
- )}
333
-
334
- {/* Modifier groups (gift wrap, engraving options, …) */}
335
- {modifierGroups.length > 0 && (
336
- <div className="mt-6 space-y-5">
337
- {modifierGroups.map((group) => (
338
- <ModifierGroupSelector
339
- key={group.attachmentId ?? group.id}
340
- group={group}
341
- value={modifierSelections[group.id] ?? []}
342
- onChange={(next) => setModifierSelection(group.id, next)}
343
- disabled={addingToCart}
344
- />
345
- ))}
346
- {modifierError && (
347
- <p role="alert" className="text-destructive text-sm font-medium">
348
- {modifierError}
349
- </p>
350
- )}
351
- </div>
352
- )}
353
-
354
- {/* Quantity + Add to Cart */}
355
- <div className="mt-7 flex flex-wrap items-center gap-3">
356
- <div
357
- className="flex h-12 items-center rounded-full border"
358
- role="group"
359
- aria-label={t('quantityLabel')}
360
- >
361
- <button
362
- type="button"
363
- onClick={() => setQuantity((q) => Math.max(1, q - 1))}
364
- aria-label={t('decreaseQuantity')}
365
- className="text-foreground hover:bg-secondary flex h-full w-11 items-center justify-center rounded-s-full transition-colors disabled:opacity-40"
366
- disabled={quantity <= 1}
367
- >
368
- <IconMinus size={16} />
369
- </button>
370
- <span aria-live="polite" className="min-w-8 text-center text-sm font-semibold">
371
- {quantity}
372
- </span>
373
- <button
374
- type="button"
375
- onClick={() => setQuantity((q) => q + 1)}
376
- aria-label={t('increaseQuantity')}
377
- className="text-foreground hover:bg-secondary flex h-full w-11 items-center justify-center rounded-e-full transition-colors"
378
- >
379
- <IconPlus size={16} />
380
- </button>
381
- </div>
382
-
383
- <button
384
- type="button"
385
- onClick={() => {
386
- flyToCart(firstVisible('[data-pdp-gallery]'));
387
- handleAddToCart();
388
- }}
389
- disabled={!canPurchase || addingToCart}
390
- className={cn(
391
- 'btn-primary btn-lg flex-1 sm:min-w-64 sm:flex-none',
392
- addedMessage && 'bg-primary/90'
393
- )}
394
- >
395
- {addedMessage ? <IconCheck size={20} /> : <IconBag size={20} />}
396
- {addingToCart
397
- ? t('addingToCart')
398
- : addedMessage
399
- ? t('addedToCart')
400
- : !canPurchase
401
- ? t('outOfStock')
402
- : t('addToCart')}
403
- </button>
404
- </div>
405
-
406
- {/*
407
- Sold out is not the end of the page. `canOfferStockAlert` is the whole
408
- gate it also covers the merchant's switch and backorderable items,
409
- where an alert would tell someone to come back and do what they can
410
- already do. Pass the selected variant: without it a shopper who wanted
411
- the medium is mailed when the small returns.
412
- */}
413
- {canOfferStockAlert(inventory, stockAlertsEnabled) && (
414
- <div className="mt-6">
415
- <BackInStockForm productId={product.id} variantId={selectedVariant?.id} />
416
- </div>
417
- )}
418
-
419
- {/* Reassurance row */}
420
- <ul className="text-muted-foreground mt-6 space-y-2 border-t pt-5 text-sm">
421
- <li className="flex items-center gap-2.5">
422
- <span className="text-primary">
423
- <IconTruck size={20} />
424
- </span>
425
- {t('shippingNote')}
426
- </li>
427
- <li className="flex items-center gap-2.5">
428
- <span className="text-primary">
429
- <IconBadgeCheck size={20} />
430
- </span>
431
- {t('guaranteeNote')}
432
- </li>
433
- </ul>
434
-
435
- {/* Download after purchase note */}
436
- {product.isDownloadable && (
437
- <p className="text-muted-foreground mt-4 text-sm">{t('downloadAfterPurchase')}</p>
438
- )}
439
-
440
- {/* Description */}
441
- {description && (
442
- <section className="mt-8">
443
- <h2 className="mb-3 text-xl">{t('description')}</h2>
444
- {'html' in description ? (
445
- <div
446
- className="prose-store"
447
- dangerouslySetInnerHTML={{ __html: sanitizeProductHtml(description.html) }}
448
- />
449
- ) : (
450
- <p className="prose-store whitespace-pre-wrap">{description.text}</p>
451
- )}
452
- </section>
453
- )}
454
-
455
- {/* Metafields / Specifications */}
456
- {product.metafields && product.metafields.length > 0 && (
457
- <section className="mt-8">
458
- <h2 className="mb-3 text-xl">{t('specifications')}</h2>
459
- <table className="w-full overflow-hidden rounded-xl border text-sm">
460
- <tbody className="divide-y">
461
- {product.metafields.map((field) => (
462
- <tr key={field.id} className="odd:bg-secondary/50">
463
- <th
464
- scope="row"
465
- className="text-muted-foreground w-1/3 px-4 py-3 text-start font-medium"
466
- >
467
- {field.definitionName}
468
- </th>
469
- <td className="px-4 py-3">
470
- <MetafieldValue field={field} />
471
- </td>
472
- </tr>
473
- ))}
474
- </tbody>
475
- </table>
476
- </section>
477
- )}
478
- </section>
479
- </div>
480
-
481
- {/* Frequently Bought Together (cross-sells) */}
482
- {recommendations?.crossSells && recommendations.crossSells.length > 0 && (
483
- <FrequentlyBoughtTogether
484
- items={recommendations.crossSells}
485
- currentProduct={product}
486
- className="mt-14"
487
- />
488
- )}
489
-
490
- {/* Upsells */}
491
- {recommendations?.upsells && recommendations.upsells.length > 0 && (
492
- <RecommendationSection
493
- title={t('upgradeYourChoice')}
494
- items={recommendations.upsells}
495
- className="mt-14"
496
- />
497
- )}
498
-
499
- {/* Related products */}
500
- {recommendations?.related && recommendations.related.length > 0 && (
501
- <RecommendationSection
502
- title={t('similarProducts')}
503
- items={recommendations.related}
504
- className="mt-14"
505
- />
506
- )}
507
- </article>
508
- );
509
- }
1
+ 'use client';
2
+
3
+ import { useEffect } from 'react';
4
+ import { CdnImage as Image } from '@/ui/shared/cdn-image';
5
+ import type { Product, ProductMetafield, DownloadFile } from 'brainerce';
6
+ import { useProductPage } from '@/core/hooks/use-product-page';
7
+ import { PriceDisplay } from '@/ui/product/price-display';
8
+ import { VariantSelector } from '@/ui/product/variant-selector';
9
+ import { StockBadge } from '@/ui/product/stock-badge';
10
+ import { DiscountBadge } from '@/ui/product/discount-badge';
11
+ import { BackInStockForm, canOfferStockAlert } from '@/ui/product/back-in-stock-form';
12
+ import { RecommendationSection } from '@/ui/product/recommendation-section';
13
+ import { FrequentlyBoughtTogether } from '@/ui/product/frequently-bought-together';
14
+ import { CustomizationFields } from '@/ui/product/customization-fields';
15
+ import { ModifierGroupSelector } from '@/ui/product/modifier-group-selector';
16
+ import { useTranslations } from '@/core/lib/translations';
17
+ import { flyToCart, firstVisible } from '@/ui/shared/fly-to-cart';
18
+ import { openCartDrawer } from '@/ui/cart/cart-drawer';
19
+ import { sanitizeProductHtml } from '@/core/lib/sanitize-html';
20
+ import { cn } from '@/core/lib/utils';
21
+ import {
22
+ IconBag,
23
+ IconCheck,
24
+ IconMinus,
25
+ IconPlus,
26
+ IconTruck,
27
+ IconBadgeCheck,
28
+ IconDownload,
29
+ } from '@/ui/shared/icons';
30
+
31
+ /** Render a metafield value based on its type */
32
+ function MetafieldValue({ field }: { field: ProductMetafield }) {
33
+ const tc = useTranslations('common');
34
+ switch (field.type) {
35
+ case 'IMAGE': {
36
+ if (!field.value) return <span>-</span>;
37
+ return (
38
+ <img
39
+ src={field.value}
40
+ alt={field.definitionName}
41
+ className="h-16 w-16 rounded-lg border object-cover"
42
+ />
43
+ );
44
+ }
45
+ case 'GALLERY': {
46
+ let urls: string[] = [];
47
+ try {
48
+ const parsed = JSON.parse(field.value);
49
+ urls = Array.isArray(parsed)
50
+ ? parsed.filter((u: unknown) => typeof u === 'string' && u)
51
+ : [];
52
+ } catch {
53
+ urls = field.value ? [field.value] : [];
54
+ }
55
+ if (urls.length === 0) return <span>-</span>;
56
+ return (
57
+ <span className="flex flex-wrap gap-2">
58
+ {urls.map((url, i) => (
59
+ <img
60
+ key={i}
61
+ src={url}
62
+ alt={`${field.definitionName} ${i + 1}`}
63
+ className="h-16 w-16 rounded-lg border object-cover"
64
+ />
65
+ ))}
66
+ </span>
67
+ );
68
+ }
69
+ case 'URL':
70
+ return field.value ? (
71
+ <a
72
+ href={field.value}
73
+ target="_blank"
74
+ rel="noopener noreferrer"
75
+ className="text-primary underline underline-offset-2"
76
+ >
77
+ {field.value}
78
+ </a>
79
+ ) : (
80
+ <span>-</span>
81
+ );
82
+ case 'COLOR':
83
+ return field.value ? (
84
+ <span className="inline-flex items-center gap-2">
85
+ <span
86
+ aria-hidden="true"
87
+ className="inline-block h-4 w-4 rounded-full border"
88
+ style={{ backgroundColor: field.value }}
89
+ />
90
+ {field.value}
91
+ </span>
92
+ ) : (
93
+ <span>-</span>
94
+ );
95
+ case 'BOOLEAN':
96
+ return <span>{field.value === 'true' ? tc('yes') : tc('no')}</span>;
97
+ case 'DATE':
98
+ case 'DATETIME': {
99
+ if (!field.value) return <span>-</span>;
100
+ try {
101
+ const date = new Date(field.value);
102
+ return (
103
+ <span>
104
+ {field.type === 'DATETIME' ? date.toLocaleString() : date.toLocaleDateString()}
105
+ </span>
106
+ );
107
+ } catch {
108
+ return <span>{field.value}</span>;
109
+ }
110
+ }
111
+ default:
112
+ return <span>{field.value || '-'}</span>;
113
+ }
114
+ }
115
+
116
+ interface ProductClientSectionProps {
117
+ product: Product;
118
+ /**
119
+ * From `getStoreInfo().stockAlertsEnabled` — the merchant switch for
120
+ * back-in-stock alerts on this storefront. Undefined on a public-storefront
121
+ * (storeId) client, where the setting does not apply and the feature is on.
122
+ */
123
+ stockAlertsEnabled?: boolean;
124
+ }
125
+
126
+ export function ProductClientSection({
127
+ product: initialProduct,
128
+ stockAlertsEnabled,
129
+ }: ProductClientSectionProps) {
130
+ const t = useTranslations('productDetail');
131
+
132
+ const {
133
+ product,
134
+ recommendations,
135
+ images,
136
+ selectedImageIndex,
137
+ setSelectedImageIndex,
138
+ mainImageUrl,
139
+ selectedVariant,
140
+ setSelectedVariant,
141
+ priceInfo,
142
+ displayPrice,
143
+ inventory,
144
+ canPurchase,
145
+ description,
146
+ quantity,
147
+ setQuantity,
148
+ addingToCart,
149
+ addedMessage,
150
+ handleAddToCart,
151
+ customizationFields,
152
+ customizationValues,
153
+ setCustomizationValues,
154
+ customizationErrors,
155
+ modifierGroups,
156
+ modifierSelections,
157
+ setModifierSelection,
158
+ modifierError,
159
+ } = useProductPage(initialProduct);
160
+
161
+ // `addedMessage` flips true only after the server confirms the add (it
162
+ // stays false on validation failures), so it is the reliable moment to
163
+ // slide the mini-cart open.
164
+ useEffect(() => {
165
+ if (addedMessage) openCartDrawer();
166
+ }, [addedMessage]);
167
+
168
+ return (
169
+ <article className="container-narrow py-8 lg:py-12">
170
+ <div className="grid grid-cols-1 gap-8 lg:grid-cols-2 lg:gap-14">
171
+ {/* Image Gallery */}
172
+ <figure className="lg:sticky lg:top-24 lg:self-start">
173
+ {/* `relative` + `aspect-square` are layout-critical for next/image fill */}
174
+ <div
175
+ data-pdp-gallery
176
+ className="bg-secondary relative aspect-square overflow-hidden rounded-3xl border shadow-[0_28px_60px_-30px_hsl(var(--primary)/0.3)]"
177
+ >
178
+ {mainImageUrl ? (
179
+ <Image
180
+ src={mainImageUrl}
181
+ alt={product.name}
182
+ fill
183
+ sizes="(max-width: 1024px) 100vw, 50vw"
184
+ priority
185
+ className="object-cover"
186
+ />
187
+ ) : (
188
+ <span className="sr-only">{product.name}</span>
189
+ )}
190
+ </div>
191
+
192
+ {/* Thumbnails */}
193
+ {images.length > 1 && (
194
+ <div className="mt-3 flex flex-wrap gap-2.5">
195
+ {images.map((img, idx) => (
196
+ <button
197
+ key={idx}
198
+ type="button"
199
+ onClick={() => setSelectedImageIndex(idx)}
200
+ aria-pressed={selectedImageIndex === idx}
201
+ className={cn(
202
+ 'bg-secondary relative h-[4.5rem] w-[4.5rem] overflow-hidden rounded-lg border-2 transition-colors',
203
+ selectedImageIndex === idx
204
+ ? 'border-primary'
205
+ : 'hover:border-border border-transparent'
206
+ )}
207
+ >
208
+ <Image
209
+ src={img.url}
210
+ alt={img.alt || `${product.name} ${idx + 1}`}
211
+ fill
212
+ sizes="72px"
213
+ className="object-cover"
214
+ />
215
+ </button>
216
+ ))}
217
+ </div>
218
+ )}
219
+ <figcaption className="sr-only">{product.name}</figcaption>
220
+ </figure>
221
+
222
+ {/* Product Info / buy box */}
223
+ <section className="max-w-xl">
224
+ {/* Categories */}
225
+ {product.categories && product.categories.length > 0 && (
226
+ <ul className="mb-3 flex flex-wrap gap-1.5">
227
+ {product.categories.map((cat) => (
228
+ <li key={cat.id} className="badge-soft">
229
+ {cat.name}
230
+ </li>
231
+ ))}
232
+ </ul>
233
+ )}
234
+
235
+ {/* Brand */}
236
+ {(product as { brands?: Array<{ id: string; name: string }> }).brands &&
237
+ (product as { brands: Array<{ id: string; name: string }> }).brands.length > 0 && (
238
+ <p className="text-muted-foreground mb-1 text-sm">
239
+ {t('by')}{' '}
240
+ <span className="text-foreground font-medium">
241
+ {(product as { brands: Array<{ id: string; name: string }> }).brands
242
+ .map((b) => b.name)
243
+ .join(', ')}
244
+ </span>
245
+ </p>
246
+ )}
247
+
248
+ {/* Title */}
249
+ <h1 className="text-3xl sm:text-4xl">{product.name}</h1>
250
+
251
+ {/* Tags */}
252
+ {(product as unknown as { tags?: Array<{ id: string; name: string }> }).tags &&
253
+ (product as unknown as { tags: Array<{ id: string; name: string }> }).tags.length >
254
+ 0 && (
255
+ <ul className="text-muted-foreground mt-2 flex flex-wrap gap-1.5 text-xs">
256
+ {(product as unknown as { tags: Array<{ id: string; name: string }> }).tags.map(
257
+ (tag) => (
258
+ <li key={tag.id}>#{tag.name}</li>
259
+ )
260
+ )}
261
+ </ul>
262
+ )}
263
+
264
+ {/* Price + stock */}
265
+ <div className="mt-5 flex flex-wrap items-center gap-4 border-b pb-6">
266
+ <PriceDisplay
267
+ price={displayPrice.price}
268
+ salePrice={displayPrice.salePrice ?? undefined}
269
+ currency={displayPrice.currency}
270
+ size="lg"
271
+ />
272
+ {/* Active discount rule on this product, as a badge.
273
+ `product.discount` is returned by getProductBySlug and is
274
+ null/absent when no rule applies, and DiscountBadge returns
275
+ null on a falsy `discount`, so this renders nothing on a store
276
+ with no discounts configured. */}
277
+ <DiscountBadge discount={product.discount} />
278
+ {product.isDownloadable ? (
279
+ <span className="badge-soft">
280
+ <IconDownload size={16} />
281
+ {t('instantDownload')}
282
+ </span>
283
+ ) : (
284
+ <StockBadge inventory={inventory} />
285
+ )}
286
+ </div>
287
+
288
+ {/* Downloadable files info */}
289
+ {product.isDownloadable && product.downloads && product.downloads.length > 0 && (
290
+ <section className="bg-secondary/60 mt-6 rounded-xl border p-4">
291
+ <h2 className="text-sm font-semibold">
292
+ {t('filesIncluded').replace('{count}', String(product.downloads.length))}
293
+ </h2>
294
+ <ul className="text-muted-foreground mt-2 space-y-1.5 text-sm">
295
+ {product.downloads.map((file: DownloadFile) => (
296
+ <li key={file.id} className="flex items-center gap-2">
297
+ <IconDownload size={16} />
298
+ <span>{file.name}</span>
299
+ {file.size && (
300
+ <span className="text-xs">
301
+ (
302
+ {file.size < 1024 * 1024
303
+ ? `${(file.size / 1024).toFixed(0)} KB`
304
+ : `${(file.size / (1024 * 1024)).toFixed(1)} MB`}
305
+ )
306
+ </span>
307
+ )}
308
+ </li>
309
+ ))}
310
+ </ul>
311
+ </section>
312
+ )}
313
+
314
+ {/* Variant Selector */}
315
+ {/* A KIT is bought as ONE line, but the shopper needs to see what is
316
+ in the box before deciding. These rows are display only — never add
317
+ them to the cart individually; the kit reserves its components on
318
+ its own. */}
319
+ {product.type === 'KIT' && product.kitComponents?.length ? (
320
+ <div className="mb-6">
321
+ <h2 className="mb-3 text-sm font-medium">{t('whatsInTheBox')}</h2>
322
+ <ul className="divide-y rounded-lg border">
323
+ {product.kitComponents.map((c) => (
324
+ <li
325
+ key={`${c.productId}-${c.variantId ?? ''}`}
326
+ className="flex items-center gap-3 p-3"
327
+ >
328
+ {c.image ? (
329
+ // eslint-disable-next-line @next/next/no-img-element
330
+ <img
331
+ src={c.image}
332
+ alt={c.name}
333
+ className="h-10 w-10 shrink-0 rounded border object-cover"
334
+ />
335
+ ) : (
336
+ <div className="bg-muted h-10 w-10 shrink-0 rounded border" />
337
+ )}
338
+ <span className="flex-1 text-sm">{c.name}</span>
339
+ <span className="text-muted-foreground text-sm">x{c.quantity}</span>
340
+ </li>
341
+ ))}
342
+ </ul>
343
+ </div>
344
+ ) : null}
345
+
346
+ {product.type === 'VARIABLE' && product.variants && product.variants.length > 0 && (
347
+ <VariantSelector
348
+ product={product}
349
+ selectedVariant={selectedVariant}
350
+ onVariantChange={setSelectedVariant}
351
+ className="mt-6"
352
+ />
353
+ )}
354
+
355
+ {/* Customization Fields (buyer input) */}
356
+ {customizationFields.length > 0 && (
357
+ <CustomizationFields
358
+ fields={customizationFields}
359
+ values={customizationValues}
360
+ onChange={setCustomizationValues}
361
+ errors={customizationErrors}
362
+ />
363
+ )}
364
+
365
+ {/* Modifier groups (gift wrap, engraving options, …) */}
366
+ {modifierGroups.length > 0 && (
367
+ <div className="mt-6 space-y-5">
368
+ {modifierGroups.map((group) => (
369
+ <ModifierGroupSelector
370
+ key={group.attachmentId ?? group.id}
371
+ group={group}
372
+ value={modifierSelections[group.id] ?? []}
373
+ onChange={(next) => setModifierSelection(group.id, next)}
374
+ disabled={addingToCart}
375
+ />
376
+ ))}
377
+ {modifierError && (
378
+ <p role="alert" className="text-destructive text-sm font-medium">
379
+ {modifierError}
380
+ </p>
381
+ )}
382
+ </div>
383
+ )}
384
+
385
+ {/* Quantity + Add to Cart */}
386
+ <div className="mt-7 flex flex-wrap items-center gap-3">
387
+ <div
388
+ className="flex h-12 items-center rounded-full border"
389
+ role="group"
390
+ aria-label={t('quantityLabel')}
391
+ >
392
+ <button
393
+ type="button"
394
+ onClick={() => setQuantity((q) => Math.max(1, q - 1))}
395
+ aria-label={t('decreaseQuantity')}
396
+ className="text-foreground hover:bg-secondary flex h-full w-11 items-center justify-center rounded-s-full transition-colors disabled:opacity-40"
397
+ disabled={quantity <= 1}
398
+ >
399
+ <IconMinus size={16} />
400
+ </button>
401
+ <span aria-live="polite" className="min-w-8 text-center text-sm font-semibold">
402
+ {quantity}
403
+ </span>
404
+ <button
405
+ type="button"
406
+ onClick={() => setQuantity((q) => q + 1)}
407
+ aria-label={t('increaseQuantity')}
408
+ className="text-foreground hover:bg-secondary flex h-full w-11 items-center justify-center rounded-e-full transition-colors"
409
+ >
410
+ <IconPlus size={16} />
411
+ </button>
412
+ </div>
413
+
414
+ <button
415
+ type="button"
416
+ onClick={() => {
417
+ flyToCart(firstVisible('[data-pdp-gallery]'));
418
+ handleAddToCart();
419
+ }}
420
+ disabled={!canPurchase || addingToCart}
421
+ className={cn(
422
+ 'btn-primary btn-lg flex-1 sm:min-w-64 sm:flex-none',
423
+ addedMessage && 'bg-primary/90'
424
+ )}
425
+ >
426
+ {addedMessage ? <IconCheck size={20} /> : <IconBag size={20} />}
427
+ {addingToCart
428
+ ? t('addingToCart')
429
+ : addedMessage
430
+ ? t('addedToCart')
431
+ : !canPurchase
432
+ ? t('outOfStock')
433
+ : t('addToCart')}
434
+ </button>
435
+ </div>
436
+
437
+ {/*
438
+ Sold out is not the end of the page. `canOfferStockAlert` is the whole
439
+ gate — it also covers the merchant's switch and backorderable items,
440
+ where an alert would tell someone to come back and do what they can
441
+ already do. Pass the selected variant: without it a shopper who wanted
442
+ the medium is mailed when the small returns.
443
+ */}
444
+ {canOfferStockAlert(inventory, stockAlertsEnabled) && (
445
+ <div className="mt-6">
446
+ <BackInStockForm productId={product.id} variantId={selectedVariant?.id} />
447
+ </div>
448
+ )}
449
+
450
+ {/* Reassurance row */}
451
+ <ul className="text-muted-foreground mt-6 space-y-2 border-t pt-5 text-sm">
452
+ <li className="flex items-center gap-2.5">
453
+ <span className="text-primary">
454
+ <IconTruck size={20} />
455
+ </span>
456
+ {t('shippingNote')}
457
+ </li>
458
+ <li className="flex items-center gap-2.5">
459
+ <span className="text-primary">
460
+ <IconBadgeCheck size={20} />
461
+ </span>
462
+ {t('guaranteeNote')}
463
+ </li>
464
+ </ul>
465
+
466
+ {/* Download after purchase note */}
467
+ {product.isDownloadable && (
468
+ <p className="text-muted-foreground mt-4 text-sm">{t('downloadAfterPurchase')}</p>
469
+ )}
470
+
471
+ {/* Description */}
472
+ {description && (
473
+ <section className="mt-8">
474
+ <h2 className="mb-3 text-xl">{t('description')}</h2>
475
+ {'html' in description ? (
476
+ <div
477
+ className="prose-store"
478
+ dangerouslySetInnerHTML={{ __html: sanitizeProductHtml(description.html) }}
479
+ />
480
+ ) : (
481
+ <p className="prose-store whitespace-pre-wrap">{description.text}</p>
482
+ )}
483
+ </section>
484
+ )}
485
+
486
+ {/* Metafields / Specifications */}
487
+ {product.metafields && product.metafields.length > 0 && (
488
+ <section className="mt-8">
489
+ <h2 className="mb-3 text-xl">{t('specifications')}</h2>
490
+ <table className="w-full overflow-hidden rounded-xl border text-sm">
491
+ <tbody className="divide-y">
492
+ {product.metafields.map((field) => (
493
+ <tr key={field.id} className="odd:bg-secondary/50">
494
+ <th
495
+ scope="row"
496
+ className="text-muted-foreground w-1/3 px-4 py-3 text-start font-medium"
497
+ >
498
+ {field.definitionName}
499
+ </th>
500
+ <td className="px-4 py-3">
501
+ <MetafieldValue field={field} />
502
+ </td>
503
+ </tr>
504
+ ))}
505
+ </tbody>
506
+ </table>
507
+ </section>
508
+ )}
509
+ </section>
510
+ </div>
511
+
512
+ {/* Frequently Bought Together (cross-sells) */}
513
+ {recommendations?.crossSells && recommendations.crossSells.length > 0 && (
514
+ <FrequentlyBoughtTogether
515
+ items={recommendations.crossSells}
516
+ currentProduct={product}
517
+ className="mt-14"
518
+ />
519
+ )}
520
+
521
+ {/* Upsells */}
522
+ {recommendations?.upsells && recommendations.upsells.length > 0 && (
523
+ <RecommendationSection
524
+ title={t('upgradeYourChoice')}
525
+ items={recommendations.upsells}
526
+ className="mt-14"
527
+ />
528
+ )}
529
+
530
+ {/* Related products */}
531
+ {recommendations?.related && recommendations.related.length > 0 && (
532
+ <RecommendationSection
533
+ title={t('similarProducts')}
534
+ items={recommendations.related}
535
+ className="mt-14"
536
+ />
537
+ )}
538
+ </article>
539
+ );
540
+ }