create-brainerce-store 1.28.21 → 1.29.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,529 +1,566 @@
1
- 'use client';
2
-
3
- import { useEffect, useState, useMemo } from 'react';
4
- import Image from 'next/image';
5
- import type {
6
- Product,
7
- ProductVariant,
8
- ProductImage,
9
- ProductMetafield,
10
- DownloadFile,
11
- } from 'brainerce';
12
- import { getProductPriceInfo, getDescriptionContent } from 'brainerce';
13
- import { useCart } from '@/providers/store-provider';
14
- import { PriceDisplay } from '@/components/shared/price-display';
15
- import { LoadingSpinner } from '@/components/shared/loading-spinner';
16
- import { VariantSelector } from '@/components/products/variant-selector';
17
- import { StockBadge } from '@/components/products/stock-badge';
18
- import { RecommendationSection } from '@/components/products/recommendation-section';
19
- import { FrequentlyBoughtTogether } from '@/components/products/frequently-bought-together';
20
- import { useTranslations } from '@/lib/translations';
21
- import { cn } from '@/lib/utils';
22
- import { sanitizeProductHtml } from '@/lib/sanitize-html';
23
-
24
- /** Render a metafield value based on its type */
25
- function MetafieldValue({ field }: { field: ProductMetafield }) {
26
- const tc = useTranslations('common');
27
- switch (field.type) {
28
- case 'IMAGE': {
29
- if (!field.value) return <span className="text-muted-foreground">-</span>;
30
- return (
31
- <img
32
- src={field.value}
33
- alt={field.definitionName}
34
- className="h-16 w-16 rounded object-cover"
35
- />
36
- );
37
- }
38
- case 'GALLERY': {
39
- let urls: string[] = [];
40
- try {
41
- const parsed = JSON.parse(field.value);
42
- urls = Array.isArray(parsed)
43
- ? parsed.filter((u: unknown) => typeof u === 'string' && u)
44
- : [];
45
- } catch {
46
- urls = field.value ? [field.value] : [];
47
- }
48
- if (urls.length === 0) return <span className="text-muted-foreground">-</span>;
49
- return (
50
- <div className="flex flex-wrap gap-2">
51
- {urls.map((url, i) => (
52
- <img
53
- key={i}
54
- src={url}
55
- alt={`${field.definitionName} ${i + 1}`}
56
- className="h-16 w-16 rounded object-cover"
57
- />
58
- ))}
59
- </div>
60
- );
61
- }
62
- case 'URL':
63
- return field.value ? (
64
- <a
65
- href={field.value}
66
- target="_blank"
67
- rel="noopener noreferrer"
68
- className="text-primary break-all hover:underline"
69
- >
70
- {field.value}
71
- </a>
72
- ) : (
73
- <span className="text-muted-foreground">-</span>
74
- );
75
- case 'COLOR':
76
- return field.value ? (
77
- <span className="inline-flex items-center gap-2">
78
- <span
79
- className="border-border inline-block h-4 w-4 rounded-full border"
80
- style={{ backgroundColor: field.value }}
81
- />
82
- {field.value}
83
- </span>
84
- ) : (
85
- <span className="text-muted-foreground">-</span>
86
- );
87
- case 'BOOLEAN':
88
- return <span>{field.value === 'true' ? tc('yes') : tc('no')}</span>;
89
- case 'DATE':
90
- case 'DATETIME': {
91
- if (!field.value) return <span className="text-muted-foreground">-</span>;
92
- try {
93
- const date = new Date(field.value);
94
- return (
95
- <span>
96
- {field.type === 'DATETIME' ? date.toLocaleString() : date.toLocaleDateString()}
97
- </span>
98
- );
99
- } catch {
100
- return <span>{field.value}</span>;
101
- }
102
- }
103
- default:
104
- return <span>{field.value || '-'}</span>;
105
- }
106
- }
107
-
108
- interface ProductClientSectionProps {
109
- product: Product;
110
- }
111
-
112
- export function ProductClientSection({ product: initialProduct }: ProductClientSectionProps) {
113
- const { refreshCart } = useCart();
114
- const t = useTranslations('productDetail');
115
-
116
- const product = initialProduct;
117
- const recommendations = product?.recommendations ?? null;
118
-
119
- const [selectedVariant, setSelectedVariant] = useState<ProductVariant | null>(
120
- product.variants && product.variants.length > 0 ? product.variants[0] : null
121
- );
122
- const [selectedImageIndex, setSelectedImageIndex] = useState(0);
123
- const [quantity, setQuantity] = useState(1);
124
- const [addingToCart, setAddingToCart] = useState(false);
125
- const [addedMessage, setAddedMessage] = useState(false);
126
-
127
- // Images list - switch main image when variant changes
128
- const images: ProductImage[] = useMemo(() => {
129
- return product?.images || [];
130
- }, [product]);
131
-
132
- // When variant changes, update selected image to variant image if available
133
- useEffect(() => {
134
- if (!selectedVariant?.image || !product) return;
135
-
136
- const variantImgUrl =
137
- typeof selectedVariant.image === 'string' ? selectedVariant.image : selectedVariant.image.url;
138
-
139
- // Find if variant image exists in product images
140
- const idx = images.findIndex((img) => img.url === variantImgUrl);
141
- if (idx >= 0) {
142
- setSelectedImageIndex(idx);
143
- } else {
144
- // Variant image not in product images - select index 0 as fallback
145
- setSelectedImageIndex(-1);
146
- }
147
- }, [selectedVariant, images, product]);
148
-
149
- // Determine which image to show
150
- const mainImageUrl = useMemo(() => {
151
- if (selectedImageIndex === -1 && selectedVariant?.image) {
152
- const img = selectedVariant.image;
153
- return typeof img === 'string' ? img : img.url;
154
- }
155
- return images[selectedImageIndex]?.url || null;
156
- }, [selectedImageIndex, selectedVariant, images]);
157
-
158
- // Price info - use variant price if selected, else product price
159
- const priceInfo = useMemo(() => {
160
- if (selectedVariant?.price) {
161
- const variantBase = parseFloat(selectedVariant.price);
162
- const variantSale = selectedVariant.salePrice ? parseFloat(selectedVariant.salePrice) : null;
163
- const variantEffective =
164
- variantSale != null && variantSale < variantBase ? variantSale : variantBase;
165
-
166
- // Overlay any product-level discount rule onto the variant price using the rule's ratio
167
- if (product.discount) {
168
- const ruleOriginal = parseFloat(product.discount.originalPrice) || 0;
169
- const ruleDiscounted = parseFloat(product.discount.discountedPrice) || 0;
170
- const ratio = ruleOriginal > 0 ? ruleDiscounted / ruleOriginal : 1;
171
- const discounted = variantEffective * ratio;
172
- const amount = Math.max(0, variantEffective - discounted);
173
- return {
174
- price: discounted,
175
- originalPrice: variantEffective,
176
- isOnSale: discounted < variantEffective,
177
- discountAmount: amount,
178
- discountPercent: variantEffective > 0 ? Math.round((amount / variantEffective) * 100) : 0,
179
- };
180
- }
181
-
182
- return {
183
- price: variantEffective,
184
- originalPrice: variantBase,
185
- isOnSale: variantEffective < variantBase,
186
- discountPercent:
187
- variantEffective < variantBase && variantBase > 0
188
- ? Math.round(((variantBase - variantEffective) / variantBase) * 100)
189
- : 0,
190
- };
191
- }
192
- return getProductPriceInfo(product);
193
- }, [product, selectedVariant]);
194
-
195
- // Inventory: use variant inventory if selected, else product inventory
196
- const inventory = selectedVariant?.inventory ?? product?.inventory ?? null;
197
- const canPurchase = inventory?.canPurchase !== false;
198
-
199
- // Description
200
- const description = useMemo(() => {
201
- return product ? getDescriptionContent(product) : null;
202
- }, [product]);
203
-
204
- async function handleAddToCart() {
205
- if (!product || addingToCart) return;
206
-
207
- try {
208
- setAddingToCart(true);
209
- const { getClient } = await import('@/lib/brainerce');
210
- const client = getClient();
211
- await client.smartAddToCart({
212
- productId: product.id,
213
- variantId: selectedVariant?.id,
214
- quantity,
215
- });
216
- await refreshCart();
217
- setAddedMessage(true);
218
- setTimeout(() => setAddedMessage(false), 2000);
219
- } catch (err) {
220
- console.error('Failed to add to cart:', err);
221
- } finally {
222
- setAddingToCart(false);
223
- }
224
- }
225
-
226
- return (
227
- <div className="mx-auto max-w-7xl px-4 py-8 sm:px-6 lg:px-8">
228
- <div className="grid grid-cols-1 gap-8 lg:grid-cols-2 lg:gap-12">
229
- {/* Image Gallery */}
230
- <div className="space-y-4">
231
- {/* Main Image */}
232
- <div className="bg-muted relative aspect-square overflow-hidden rounded-lg">
233
- {mainImageUrl ? (
234
- <Image
235
- src={mainImageUrl}
236
- alt={product.name}
237
- fill
238
- sizes="(max-width: 1024px) 100vw, 50vw"
239
- className="object-contain"
240
- priority
241
- />
242
- ) : (
243
- <div className="text-muted-foreground absolute inset-0 flex items-center justify-center">
244
- <svg className="h-24 w-24" fill="none" viewBox="0 0 24 24" stroke="currentColor">
245
- <path
246
- strokeLinecap="round"
247
- strokeLinejoin="round"
248
- strokeWidth={1}
249
- 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"
250
- />
251
- </svg>
252
- </div>
253
- )}
254
- </div>
255
-
256
- {/* Thumbnails */}
257
- {images.length > 1 && (
258
- <div className="flex gap-2 overflow-x-auto pb-2">
259
- {images.map((img, idx) => (
260
- <button
261
- key={idx}
262
- type="button"
263
- onClick={() => setSelectedImageIndex(idx)}
264
- className={cn(
265
- 'relative h-16 w-16 flex-shrink-0 overflow-hidden rounded border-2 transition-colors',
266
- selectedImageIndex === idx
267
- ? 'border-primary'
268
- : 'border-border hover:border-muted-foreground'
269
- )}
270
- >
271
- <Image
272
- src={img.url}
273
- alt={img.alt || `${product.name} ${idx + 1}`}
274
- fill
275
- sizes="64px"
276
- className="object-cover"
277
- />
278
- </button>
279
- ))}
280
- </div>
281
- )}
282
- </div>
283
-
284
- {/* Product Info */}
285
- <div className="space-y-6">
286
- {/* Categories */}
287
- {product.categories && product.categories.length > 0 && (
288
- <div className="flex flex-wrap gap-2">
289
- {product.categories.map((cat) => (
290
- <span
291
- key={cat.id}
292
- className="text-muted-foreground bg-muted rounded px-2 py-1 text-xs"
293
- >
294
- {cat.name}
295
- </span>
296
- ))}
297
- </div>
298
- )}
299
-
300
- {/* Brand */}
301
- {(product as { brands?: Array<{ id: string; name: string }> }).brands &&
302
- (product as { brands: Array<{ id: string; name: string }> }).brands.length > 0 && (
303
- <div className="text-muted-foreground text-sm">
304
- {t('by')}{' '}
305
- <span className="text-foreground font-medium">
306
- {(product as { brands: Array<{ id: string; name: string }> }).brands
307
- .map((b) => b.name)
308
- .join(', ')}
309
- </span>
310
- </div>
311
- )}
312
-
313
- {/* Title */}
314
- <h1 className="text-foreground text-2xl font-bold sm:text-3xl">{product.name}</h1>
315
-
316
- {/* Tags */}
317
- {(product as { tags?: Array<{ id: string; name: string }> }).tags &&
318
- (product as { tags: Array<{ id: string; name: string }> }).tags.length > 0 && (
319
- <div className="flex flex-wrap gap-1.5">
320
- {(product as { tags: Array<{ id: string; name: string }> }).tags.map((tag) => (
321
- <span
322
- key={tag.id}
323
- className="border-border text-muted-foreground rounded-full border px-2.5 py-0.5 text-xs"
324
- >
325
- #{tag.name}
326
- </span>
327
- ))}
328
- </div>
329
- )}
330
-
331
- {/* Price */}
332
- <PriceDisplay
333
- price={priceInfo.originalPrice}
334
- salePrice={priceInfo.isOnSale ? priceInfo.price : undefined}
335
- size="lg"
336
- />
337
-
338
- {/* Stock / Digital badge */}
339
- {product.isDownloadable ? (
340
- <span className="inline-flex items-center gap-1.5 rounded-full bg-green-100 px-3 py-1 text-xs font-medium text-green-800 dark:bg-green-950/30 dark:text-green-400">
341
- <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
342
- <path
343
- strokeLinecap="round"
344
- strokeLinejoin="round"
345
- strokeWidth={2}
346
- d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"
347
- />
348
- </svg>
349
- {t('instantDownload')}
350
- </span>
351
- ) : (
352
- <StockBadge inventory={inventory} lowStockThreshold={5} />
353
- )}
354
-
355
- {/* Downloadable files info */}
356
- {product.isDownloadable && product.downloads && product.downloads.length > 0 && (
357
- <div className="bg-muted/50 rounded-lg border p-4">
358
- <p className="text-foreground mb-2 text-sm font-medium">
359
- {t('filesIncluded')} ({product.downloads.length})
360
- </p>
361
- <ul className="space-y-1.5">
362
- {product.downloads.map((file: DownloadFile) => (
363
- <li
364
- key={file.id}
365
- className="text-muted-foreground flex items-center gap-2 text-sm"
366
- >
367
- <svg
368
- className="h-4 w-4 flex-shrink-0"
369
- fill="none"
370
- viewBox="0 0 24 24"
371
- stroke="currentColor"
372
- >
373
- <path
374
- strokeLinecap="round"
375
- strokeLinejoin="round"
376
- strokeWidth={1.5}
377
- d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z"
378
- />
379
- </svg>
380
- <span className="truncate">{file.name}</span>
381
- {file.size && (
382
- <span className="flex-shrink-0 text-xs">
383
- (
384
- {file.size < 1024 * 1024
385
- ? `${(file.size / 1024).toFixed(0)} KB`
386
- : `${(file.size / (1024 * 1024)).toFixed(1)} MB`}
387
- )
388
- </span>
389
- )}
390
- </li>
391
- ))}
392
- </ul>
393
- </div>
394
- )}
395
-
396
- {/* Variant Selector */}
397
- {product.type === 'VARIABLE' && product.variants && product.variants.length > 0 && (
398
- <VariantSelector
399
- product={product}
400
- selectedVariant={selectedVariant}
401
- onVariantChange={setSelectedVariant}
402
- />
403
- )}
404
-
405
- {/* Quantity + Add to Cart */}
406
- <div className="flex items-center gap-4">
407
- <div className="border-border flex items-center rounded border">
408
- <button
409
- type="button"
410
- onClick={() => setQuantity((q) => Math.max(1, q - 1))}
411
- className="text-foreground hover:bg-muted px-3 py-2 transition-colors"
412
- aria-label={t('decreaseQuantity')}
413
- >
414
- -
415
- </button>
416
- <span className="text-foreground min-w-[3rem] px-4 py-2 text-center text-sm font-medium">
417
- {quantity}
418
- </span>
419
- <button
420
- type="button"
421
- onClick={() => setQuantity((q) => q + 1)}
422
- className="text-foreground hover:bg-muted px-3 py-2 transition-colors"
423
- aria-label={t('increaseQuantity')}
424
- >
425
- +
426
- </button>
427
- </div>
428
-
429
- <button
430
- type="button"
431
- onClick={handleAddToCart}
432
- disabled={!canPurchase || addingToCart}
433
- className={cn(
434
- 'flex-1 rounded px-6 py-3 text-sm font-medium transition-all',
435
- canPurchase
436
- ? 'bg-primary text-primary-foreground hover:opacity-90'
437
- : 'bg-muted text-muted-foreground cursor-not-allowed'
438
- )}
439
- >
440
- {addingToCart ? (
441
- <span className="inline-flex items-center gap-2">
442
- <LoadingSpinner
443
- size="sm"
444
- className="border-primary-foreground/30 border-t-primary-foreground"
445
- />
446
- {t('addingToCart')}
447
- </span>
448
- ) : addedMessage ? (
449
- t('addedToCart')
450
- ) : !canPurchase ? (
451
- t('outOfStock')
452
- ) : (
453
- t('addToCart')
454
- )}
455
- </button>
456
- </div>
457
-
458
- {/* Download after purchase note */}
459
- {product.isDownloadable && (
460
- <p className="text-muted-foreground text-sm">{t('downloadAfterPurchase')}</p>
461
- )}
462
-
463
- {/* Description */}
464
- {description && (
465
- <div className="border-border border-t pt-4">
466
- <h2 className="text-foreground mb-3 text-lg font-semibold">{t('description')}</h2>
467
- {'html' in description ? (
468
- <div
469
- className="prose prose-sm text-muted-foreground max-w-none"
470
- dangerouslySetInnerHTML={{ __html: sanitizeProductHtml(description.html) }}
471
- />
472
- ) : (
473
- <p className="text-muted-foreground whitespace-pre-wrap">{description.text}</p>
474
- )}
475
- </div>
476
- )}
477
-
478
- {/* Metafields / Specifications */}
479
- {product.metafields && product.metafields.length > 0 && (
480
- <div className="border-border border-t pt-4">
481
- <h2 className="text-foreground mb-3 text-lg font-semibold">{t('specifications')}</h2>
482
- <table className="w-full text-sm">
483
- <tbody>
484
- {product.metafields.map((field) => (
485
- <tr key={field.id} className="border-border border-b last:border-0">
486
- <td className="text-foreground whitespace-nowrap py-2 pe-4 font-medium">
487
- {field.definitionName}
488
- </td>
489
- <td className="text-muted-foreground py-2">
490
- <MetafieldValue field={field} />
491
- </td>
492
- </tr>
493
- ))}
494
- </tbody>
495
- </table>
496
- </div>
497
- )}
498
- </div>
499
- </div>
500
-
501
- {/* Frequently Bought Together (cross-sells) */}
502
- {recommendations?.crossSells && recommendations.crossSells.length > 0 && (
503
- <FrequentlyBoughtTogether
504
- items={recommendations.crossSells}
505
- currentProduct={product}
506
- className="mt-12"
507
- />
508
- )}
509
-
510
- {/* Upsells */}
511
- {recommendations?.upsells && recommendations.upsells.length > 0 && (
512
- <RecommendationSection
513
- title={t('upgradeYourChoice')}
514
- items={recommendations.upsells}
515
- className="mt-12"
516
- />
517
- )}
518
-
519
- {/* Related products */}
520
- {recommendations?.related && recommendations.related.length > 0 && (
521
- <RecommendationSection
522
- title={t('similarProducts')}
523
- items={recommendations.related}
524
- className="mt-12"
525
- />
526
- )}
527
- </div>
528
- );
529
- }
1
+ 'use client';
2
+
3
+ import { useEffect, useState, useMemo } from 'react';
4
+ import Image from 'next/image';
5
+ import type {
6
+ Product,
7
+ ProductVariant,
8
+ ProductImage,
9
+ ProductMetafield,
10
+ DownloadFile,
11
+ } from 'brainerce';
12
+ import { getProductPriceInfo, getDescriptionContent } from 'brainerce';
13
+ import { useCart } from '@/providers/store-provider';
14
+ import { PriceDisplay } from '@/components/shared/price-display';
15
+ import { LoadingSpinner } from '@/components/shared/loading-spinner';
16
+ import { VariantSelector } from '@/components/products/variant-selector';
17
+ import { StockBadge } from '@/components/products/stock-badge';
18
+ import { RecommendationSection } from '@/components/products/recommendation-section';
19
+ import { FrequentlyBoughtTogether } from '@/components/products/frequently-bought-together';
20
+ import {
21
+ CustomizationFields,
22
+ validateCustomization,
23
+ type CustomizationValues,
24
+ } from '@/components/products/customization-fields';
25
+ import { useTranslations } from '@/lib/translations';
26
+ import { cn } from '@/lib/utils';
27
+ import { sanitizeProductHtml } from '@/lib/sanitize-html';
28
+
29
+ /** Render a metafield value based on its type */
30
+ function MetafieldValue({ field }: { field: ProductMetafield }) {
31
+ const tc = useTranslations('common');
32
+ switch (field.type) {
33
+ case 'IMAGE': {
34
+ if (!field.value) return <span className="text-muted-foreground">-</span>;
35
+ return (
36
+ <img
37
+ src={field.value}
38
+ alt={field.definitionName}
39
+ className="h-16 w-16 rounded object-cover"
40
+ />
41
+ );
42
+ }
43
+ case 'GALLERY': {
44
+ let urls: string[] = [];
45
+ try {
46
+ const parsed = JSON.parse(field.value);
47
+ urls = Array.isArray(parsed)
48
+ ? parsed.filter((u: unknown) => typeof u === 'string' && u)
49
+ : [];
50
+ } catch {
51
+ urls = field.value ? [field.value] : [];
52
+ }
53
+ if (urls.length === 0) return <span className="text-muted-foreground">-</span>;
54
+ return (
55
+ <div className="flex flex-wrap gap-2">
56
+ {urls.map((url, i) => (
57
+ <img
58
+ key={i}
59
+ src={url}
60
+ alt={`${field.definitionName} ${i + 1}`}
61
+ className="h-16 w-16 rounded object-cover"
62
+ />
63
+ ))}
64
+ </div>
65
+ );
66
+ }
67
+ case 'URL':
68
+ return field.value ? (
69
+ <a
70
+ href={field.value}
71
+ target="_blank"
72
+ rel="noopener noreferrer"
73
+ className="text-primary break-all hover:underline"
74
+ >
75
+ {field.value}
76
+ </a>
77
+ ) : (
78
+ <span className="text-muted-foreground">-</span>
79
+ );
80
+ case 'COLOR':
81
+ return field.value ? (
82
+ <span className="inline-flex items-center gap-2">
83
+ <span
84
+ className="border-border inline-block h-4 w-4 rounded-full border"
85
+ style={{ backgroundColor: field.value }}
86
+ />
87
+ {field.value}
88
+ </span>
89
+ ) : (
90
+ <span className="text-muted-foreground">-</span>
91
+ );
92
+ case 'BOOLEAN':
93
+ return <span>{field.value === 'true' ? tc('yes') : tc('no')}</span>;
94
+ case 'DATE':
95
+ case 'DATETIME': {
96
+ if (!field.value) return <span className="text-muted-foreground">-</span>;
97
+ try {
98
+ const date = new Date(field.value);
99
+ return (
100
+ <span>
101
+ {field.type === 'DATETIME' ? date.toLocaleString() : date.toLocaleDateString()}
102
+ </span>
103
+ );
104
+ } catch {
105
+ return <span>{field.value}</span>;
106
+ }
107
+ }
108
+ default:
109
+ return <span>{field.value || '-'}</span>;
110
+ }
111
+ }
112
+
113
+ interface ProductClientSectionProps {
114
+ product: Product;
115
+ }
116
+
117
+ export function ProductClientSection({ product: initialProduct }: ProductClientSectionProps) {
118
+ const { refreshCart } = useCart();
119
+ const t = useTranslations('productDetail');
120
+
121
+ const product = initialProduct;
122
+ const recommendations = product?.recommendations ?? null;
123
+
124
+ const [selectedVariant, setSelectedVariant] = useState<ProductVariant | null>(
125
+ product.variants && product.variants.length > 0 ? product.variants[0] : null
126
+ );
127
+ const [selectedImageIndex, setSelectedImageIndex] = useState(0);
128
+ const [quantity, setQuantity] = useState(1);
129
+ const [addingToCart, setAddingToCart] = useState(false);
130
+ const [addedMessage, setAddedMessage] = useState(false);
131
+ const customizationFields = product.customizationFields ?? [];
132
+ const [customizationValues, setCustomizationValues] = useState<CustomizationValues>(() => {
133
+ const initial: CustomizationValues = {};
134
+ for (const field of customizationFields) {
135
+ if (field.defaultValue != null) initial[field.key] = field.defaultValue;
136
+ }
137
+ return initial;
138
+ });
139
+ const [customizationErrors, setCustomizationErrors] = useState<Record<string, string>>({});
140
+
141
+ // Images list - switch main image when variant changes
142
+ const images: ProductImage[] = useMemo(() => {
143
+ return product?.images || [];
144
+ }, [product]);
145
+
146
+ // When variant changes, update selected image to variant image if available
147
+ useEffect(() => {
148
+ if (!selectedVariant?.image || !product) return;
149
+
150
+ const variantImgUrl =
151
+ typeof selectedVariant.image === 'string' ? selectedVariant.image : selectedVariant.image.url;
152
+
153
+ // Find if variant image exists in product images
154
+ const idx = images.findIndex((img) => img.url === variantImgUrl);
155
+ if (idx >= 0) {
156
+ setSelectedImageIndex(idx);
157
+ } else {
158
+ // Variant image not in product images - select index 0 as fallback
159
+ setSelectedImageIndex(-1);
160
+ }
161
+ }, [selectedVariant, images, product]);
162
+
163
+ // Determine which image to show
164
+ const mainImageUrl = useMemo(() => {
165
+ if (selectedImageIndex === -1 && selectedVariant?.image) {
166
+ const img = selectedVariant.image;
167
+ return typeof img === 'string' ? img : img.url;
168
+ }
169
+ return images[selectedImageIndex]?.url || null;
170
+ }, [selectedImageIndex, selectedVariant, images]);
171
+
172
+ // Price info - use variant price if selected, else product price
173
+ const priceInfo = useMemo(() => {
174
+ if (selectedVariant?.price) {
175
+ const variantBase = parseFloat(selectedVariant.price);
176
+ const variantSale = selectedVariant.salePrice ? parseFloat(selectedVariant.salePrice) : null;
177
+ const variantEffective =
178
+ variantSale != null && variantSale < variantBase ? variantSale : variantBase;
179
+
180
+ // Overlay any product-level discount rule onto the variant price using the rule's ratio
181
+ if (product.discount) {
182
+ const ruleOriginal = parseFloat(product.discount.originalPrice) || 0;
183
+ const ruleDiscounted = parseFloat(product.discount.discountedPrice) || 0;
184
+ const ratio = ruleOriginal > 0 ? ruleDiscounted / ruleOriginal : 1;
185
+ const discounted = variantEffective * ratio;
186
+ const amount = Math.max(0, variantEffective - discounted);
187
+ return {
188
+ price: discounted,
189
+ originalPrice: variantEffective,
190
+ isOnSale: discounted < variantEffective,
191
+ discountAmount: amount,
192
+ discountPercent: variantEffective > 0 ? Math.round((amount / variantEffective) * 100) : 0,
193
+ };
194
+ }
195
+
196
+ return {
197
+ price: variantEffective,
198
+ originalPrice: variantBase,
199
+ isOnSale: variantEffective < variantBase,
200
+ discountPercent:
201
+ variantEffective < variantBase && variantBase > 0
202
+ ? Math.round(((variantBase - variantEffective) / variantBase) * 100)
203
+ : 0,
204
+ };
205
+ }
206
+ return getProductPriceInfo(product);
207
+ }, [product, selectedVariant]);
208
+
209
+ // Inventory: use variant inventory if selected, else product inventory
210
+ const inventory = selectedVariant?.inventory ?? product?.inventory ?? null;
211
+ const canPurchase = inventory?.canPurchase !== false;
212
+
213
+ // Description
214
+ const description = useMemo(() => {
215
+ return product ? getDescriptionContent(product) : null;
216
+ }, [product]);
217
+
218
+ async function handleAddToCart() {
219
+ if (!product || addingToCart) return;
220
+
221
+ if (customizationFields.length > 0) {
222
+ const errs = validateCustomization(customizationFields, customizationValues);
223
+ if (Object.keys(errs).length > 0) {
224
+ setCustomizationErrors(errs);
225
+ return;
226
+ }
227
+ }
228
+ setCustomizationErrors({});
229
+
230
+ try {
231
+ setAddingToCart(true);
232
+ const { getClient } = await import('@/lib/brainerce');
233
+ const client = getClient();
234
+ await client.smartAddToCart({
235
+ productId: product.id,
236
+ variantId: selectedVariant?.id,
237
+ quantity,
238
+ metadata:
239
+ customizationFields.length > 0 && Object.keys(customizationValues).length > 0
240
+ ? customizationValues
241
+ : undefined,
242
+ });
243
+ await refreshCart();
244
+ setAddedMessage(true);
245
+ setTimeout(() => setAddedMessage(false), 2000);
246
+ } catch (err) {
247
+ console.error('Failed to add to cart:', err);
248
+ } finally {
249
+ setAddingToCart(false);
250
+ }
251
+ }
252
+
253
+ return (
254
+ <div className="mx-auto max-w-7xl px-4 py-8 sm:px-6 lg:px-8">
255
+ <div className="grid grid-cols-1 gap-8 lg:grid-cols-2 lg:gap-12">
256
+ {/* Image Gallery */}
257
+ <div className="space-y-4">
258
+ {/* Main Image */}
259
+ <div className="bg-muted relative aspect-square overflow-hidden rounded-lg">
260
+ {mainImageUrl ? (
261
+ <Image
262
+ src={mainImageUrl}
263
+ alt={product.name}
264
+ fill
265
+ sizes="(max-width: 1024px) 100vw, 50vw"
266
+ className="object-contain"
267
+ priority
268
+ />
269
+ ) : (
270
+ <div className="text-muted-foreground absolute inset-0 flex items-center justify-center">
271
+ <svg className="h-24 w-24" fill="none" viewBox="0 0 24 24" stroke="currentColor">
272
+ <path
273
+ strokeLinecap="round"
274
+ strokeLinejoin="round"
275
+ strokeWidth={1}
276
+ 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"
277
+ />
278
+ </svg>
279
+ </div>
280
+ )}
281
+ </div>
282
+
283
+ {/* Thumbnails */}
284
+ {images.length > 1 && (
285
+ <div className="flex gap-2 overflow-x-auto pb-2">
286
+ {images.map((img, idx) => (
287
+ <button
288
+ key={idx}
289
+ type="button"
290
+ onClick={() => setSelectedImageIndex(idx)}
291
+ className={cn(
292
+ 'relative h-16 w-16 flex-shrink-0 overflow-hidden rounded border-2 transition-colors',
293
+ selectedImageIndex === idx
294
+ ? 'border-primary'
295
+ : 'border-border hover:border-muted-foreground'
296
+ )}
297
+ >
298
+ <Image
299
+ src={img.url}
300
+ alt={img.alt || `${product.name} ${idx + 1}`}
301
+ fill
302
+ sizes="64px"
303
+ className="object-cover"
304
+ />
305
+ </button>
306
+ ))}
307
+ </div>
308
+ )}
309
+ </div>
310
+
311
+ {/* Product Info */}
312
+ <div className="space-y-6">
313
+ {/* Categories */}
314
+ {product.categories && product.categories.length > 0 && (
315
+ <div className="flex flex-wrap gap-2">
316
+ {product.categories.map((cat) => (
317
+ <span
318
+ key={cat.id}
319
+ className="text-muted-foreground bg-muted rounded px-2 py-1 text-xs"
320
+ >
321
+ {cat.name}
322
+ </span>
323
+ ))}
324
+ </div>
325
+ )}
326
+
327
+ {/* Brand */}
328
+ {(product as { brands?: Array<{ id: string; name: string }> }).brands &&
329
+ (product as { brands: Array<{ id: string; name: string }> }).brands.length > 0 && (
330
+ <div className="text-muted-foreground text-sm">
331
+ {t('by')}{' '}
332
+ <span className="text-foreground font-medium">
333
+ {(product as { brands: Array<{ id: string; name: string }> }).brands
334
+ .map((b) => b.name)
335
+ .join(', ')}
336
+ </span>
337
+ </div>
338
+ )}
339
+
340
+ {/* Title */}
341
+ <h1 className="text-foreground text-2xl font-bold sm:text-3xl">{product.name}</h1>
342
+
343
+ {/* Tags */}
344
+ {(product as { tags?: Array<{ id: string; name: string }> }).tags &&
345
+ (product as { tags: Array<{ id: string; name: string }> }).tags.length > 0 && (
346
+ <div className="flex flex-wrap gap-1.5">
347
+ {(product as { tags: Array<{ id: string; name: string }> }).tags.map((tag) => (
348
+ <span
349
+ key={tag.id}
350
+ className="border-border text-muted-foreground rounded-full border px-2.5 py-0.5 text-xs"
351
+ >
352
+ #{tag.name}
353
+ </span>
354
+ ))}
355
+ </div>
356
+ )}
357
+
358
+ {/* Price */}
359
+ <PriceDisplay
360
+ price={priceInfo.originalPrice}
361
+ salePrice={priceInfo.isOnSale ? priceInfo.price : undefined}
362
+ size="lg"
363
+ />
364
+
365
+ {/* Stock / Digital badge */}
366
+ {product.isDownloadable ? (
367
+ <span className="inline-flex items-center gap-1.5 rounded-full bg-green-100 px-3 py-1 text-xs font-medium text-green-800 dark:bg-green-950/30 dark:text-green-400">
368
+ <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
369
+ <path
370
+ strokeLinecap="round"
371
+ strokeLinejoin="round"
372
+ strokeWidth={2}
373
+ d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"
374
+ />
375
+ </svg>
376
+ {t('instantDownload')}
377
+ </span>
378
+ ) : (
379
+ <StockBadge inventory={inventory} lowStockThreshold={5} />
380
+ )}
381
+
382
+ {/* Downloadable files info */}
383
+ {product.isDownloadable && product.downloads && product.downloads.length > 0 && (
384
+ <div className="bg-muted/50 rounded-lg border p-4">
385
+ <p className="text-foreground mb-2 text-sm font-medium">
386
+ {t('filesIncluded')} ({product.downloads.length})
387
+ </p>
388
+ <ul className="space-y-1.5">
389
+ {product.downloads.map((file: DownloadFile) => (
390
+ <li
391
+ key={file.id}
392
+ className="text-muted-foreground flex items-center gap-2 text-sm"
393
+ >
394
+ <svg
395
+ className="h-4 w-4 flex-shrink-0"
396
+ fill="none"
397
+ viewBox="0 0 24 24"
398
+ stroke="currentColor"
399
+ >
400
+ <path
401
+ strokeLinecap="round"
402
+ strokeLinejoin="round"
403
+ strokeWidth={1.5}
404
+ d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z"
405
+ />
406
+ </svg>
407
+ <span className="truncate">{file.name}</span>
408
+ {file.size && (
409
+ <span className="flex-shrink-0 text-xs">
410
+ (
411
+ {file.size < 1024 * 1024
412
+ ? `${(file.size / 1024).toFixed(0)} KB`
413
+ : `${(file.size / (1024 * 1024)).toFixed(1)} MB`}
414
+ )
415
+ </span>
416
+ )}
417
+ </li>
418
+ ))}
419
+ </ul>
420
+ </div>
421
+ )}
422
+
423
+ {/* Variant Selector */}
424
+ {product.type === 'VARIABLE' && product.variants && product.variants.length > 0 && (
425
+ <VariantSelector
426
+ product={product}
427
+ selectedVariant={selectedVariant}
428
+ onVariantChange={setSelectedVariant}
429
+ />
430
+ )}
431
+
432
+ {/* Customization Fields (buyer input) */}
433
+ {customizationFields.length > 0 && (
434
+ <CustomizationFields
435
+ fields={customizationFields}
436
+ values={customizationValues}
437
+ onChange={setCustomizationValues}
438
+ errors={customizationErrors}
439
+ />
440
+ )}
441
+
442
+ {/* Quantity + Add to Cart */}
443
+ <div className="flex items-center gap-4">
444
+ <div className="border-border flex items-center rounded border">
445
+ <button
446
+ type="button"
447
+ onClick={() => setQuantity((q) => Math.max(1, q - 1))}
448
+ className="text-foreground hover:bg-muted px-3 py-2 transition-colors"
449
+ aria-label={t('decreaseQuantity')}
450
+ >
451
+ -
452
+ </button>
453
+ <span className="text-foreground min-w-[3rem] px-4 py-2 text-center text-sm font-medium">
454
+ {quantity}
455
+ </span>
456
+ <button
457
+ type="button"
458
+ onClick={() => setQuantity((q) => q + 1)}
459
+ className="text-foreground hover:bg-muted px-3 py-2 transition-colors"
460
+ aria-label={t('increaseQuantity')}
461
+ >
462
+ +
463
+ </button>
464
+ </div>
465
+
466
+ <button
467
+ type="button"
468
+ onClick={handleAddToCart}
469
+ disabled={!canPurchase || addingToCart}
470
+ className={cn(
471
+ 'flex-1 rounded px-6 py-3 text-sm font-medium transition-all',
472
+ canPurchase
473
+ ? 'bg-primary text-primary-foreground hover:opacity-90'
474
+ : 'bg-muted text-muted-foreground cursor-not-allowed'
475
+ )}
476
+ >
477
+ {addingToCart ? (
478
+ <span className="inline-flex items-center gap-2">
479
+ <LoadingSpinner
480
+ size="sm"
481
+ className="border-primary-foreground/30 border-t-primary-foreground"
482
+ />
483
+ {t('addingToCart')}
484
+ </span>
485
+ ) : addedMessage ? (
486
+ t('addedToCart')
487
+ ) : !canPurchase ? (
488
+ t('outOfStock')
489
+ ) : (
490
+ t('addToCart')
491
+ )}
492
+ </button>
493
+ </div>
494
+
495
+ {/* Download after purchase note */}
496
+ {product.isDownloadable && (
497
+ <p className="text-muted-foreground text-sm">{t('downloadAfterPurchase')}</p>
498
+ )}
499
+
500
+ {/* Description */}
501
+ {description && (
502
+ <div className="border-border border-t pt-4">
503
+ <h2 className="text-foreground mb-3 text-lg font-semibold">{t('description')}</h2>
504
+ {'html' in description ? (
505
+ <div
506
+ className="prose prose-sm text-muted-foreground max-w-none"
507
+ dangerouslySetInnerHTML={{ __html: sanitizeProductHtml(description.html) }}
508
+ />
509
+ ) : (
510
+ <p className="text-muted-foreground whitespace-pre-wrap">{description.text}</p>
511
+ )}
512
+ </div>
513
+ )}
514
+
515
+ {/* Metafields / Specifications */}
516
+ {product.metafields && product.metafields.length > 0 && (
517
+ <div className="border-border border-t pt-4">
518
+ <h2 className="text-foreground mb-3 text-lg font-semibold">{t('specifications')}</h2>
519
+ <table className="w-full text-sm">
520
+ <tbody>
521
+ {product.metafields.map((field) => (
522
+ <tr key={field.id} className="border-border border-b last:border-0">
523
+ <td className="text-foreground whitespace-nowrap py-2 pe-4 font-medium">
524
+ {field.definitionName}
525
+ </td>
526
+ <td className="text-muted-foreground py-2">
527
+ <MetafieldValue field={field} />
528
+ </td>
529
+ </tr>
530
+ ))}
531
+ </tbody>
532
+ </table>
533
+ </div>
534
+ )}
535
+ </div>
536
+ </div>
537
+
538
+ {/* Frequently Bought Together (cross-sells) */}
539
+ {recommendations?.crossSells && recommendations.crossSells.length > 0 && (
540
+ <FrequentlyBoughtTogether
541
+ items={recommendations.crossSells}
542
+ currentProduct={product}
543
+ className="mt-12"
544
+ />
545
+ )}
546
+
547
+ {/* Upsells */}
548
+ {recommendations?.upsells && recommendations.upsells.length > 0 && (
549
+ <RecommendationSection
550
+ title={t('upgradeYourChoice')}
551
+ items={recommendations.upsells}
552
+ className="mt-12"
553
+ />
554
+ )}
555
+
556
+ {/* Related products */}
557
+ {recommendations?.related && recommendations.related.length > 0 && (
558
+ <RecommendationSection
559
+ title={t('similarProducts')}
560
+ items={recommendations.related}
561
+ className="mt-12"
562
+ />
563
+ )}
564
+ </div>
565
+ );
566
+ }