create-brainerce-store 1.28.13 → 1.28.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (24) hide show
  1. package/dist/index.js +1 -1
  2. package/messages/en.json +390 -389
  3. package/messages/he.json +390 -389
  4. package/package.json +46 -46
  5. package/templates/nextjs/base/next.config.ts +47 -47
  6. package/templates/nextjs/base/src/app/api/auth/logout/route.ts +15 -15
  7. package/templates/nextjs/base/src/app/api/auth/oauth-callback/route.ts +66 -66
  8. package/templates/nextjs/base/src/app/api/auth/reset-password/route.ts +76 -76
  9. package/templates/nextjs/base/src/app/api/store/[...path]/route.ts +235 -229
  10. package/templates/nextjs/base/src/app/checkout/page.tsx +975 -975
  11. package/templates/nextjs/base/src/app/products/[slug]/page.tsx +73 -76
  12. package/templates/nextjs/base/src/app/products/[slug]/product-client-section.tsx +529 -501
  13. package/templates/nextjs/base/src/app/products/page.tsx +475 -482
  14. package/templates/nextjs/base/src/app/reset-password/page.tsx +138 -138
  15. package/templates/nextjs/base/src/components/auth/register-form.tsx +245 -245
  16. package/templates/nextjs/base/src/components/checkout/checkout-form.tsx +416 -416
  17. package/templates/nextjs/base/src/components/checkout/payment-step.tsx +656 -656
  18. package/templates/nextjs/base/src/components/seo/product-json-ld.tsx +88 -88
  19. package/templates/nextjs/base/src/lib/brainerce.ts.ejs +6 -2
  20. package/templates/nextjs/base/src/lib/csrf.ts +11 -11
  21. package/templates/nextjs/base/src/lib/nonce.ts +10 -10
  22. package/templates/nextjs/base/src/lib/safe-redirect.ts +45 -45
  23. package/templates/nextjs/base/src/lib/sanitize-html.ts +93 -93
  24. package/templates/nextjs/base/src/lib/validation.ts +37 -37
@@ -1,501 +1,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 { 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
- {/* Title */}
301
- <h1 className="text-foreground text-2xl font-bold sm:text-3xl">{product.name}</h1>
302
-
303
- {/* Price */}
304
- <PriceDisplay
305
- price={priceInfo.originalPrice}
306
- salePrice={priceInfo.isOnSale ? priceInfo.price : undefined}
307
- size="lg"
308
- />
309
-
310
- {/* Stock / Digital badge */}
311
- {product.isDownloadable ? (
312
- <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">
313
- <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
314
- <path
315
- strokeLinecap="round"
316
- strokeLinejoin="round"
317
- strokeWidth={2}
318
- d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"
319
- />
320
- </svg>
321
- {t('instantDownload')}
322
- </span>
323
- ) : (
324
- <StockBadge inventory={inventory} lowStockThreshold={5} />
325
- )}
326
-
327
- {/* Downloadable files info */}
328
- {product.isDownloadable && product.downloads && product.downloads.length > 0 && (
329
- <div className="bg-muted/50 rounded-lg border p-4">
330
- <p className="text-foreground mb-2 text-sm font-medium">
331
- {t('filesIncluded')} ({product.downloads.length})
332
- </p>
333
- <ul className="space-y-1.5">
334
- {product.downloads.map((file: DownloadFile) => (
335
- <li
336
- key={file.id}
337
- className="text-muted-foreground flex items-center gap-2 text-sm"
338
- >
339
- <svg
340
- className="h-4 w-4 flex-shrink-0"
341
- fill="none"
342
- viewBox="0 0 24 24"
343
- stroke="currentColor"
344
- >
345
- <path
346
- strokeLinecap="round"
347
- strokeLinejoin="round"
348
- strokeWidth={1.5}
349
- 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"
350
- />
351
- </svg>
352
- <span className="truncate">{file.name}</span>
353
- {file.size && (
354
- <span className="flex-shrink-0 text-xs">
355
- (
356
- {file.size < 1024 * 1024
357
- ? `${(file.size / 1024).toFixed(0)} KB`
358
- : `${(file.size / (1024 * 1024)).toFixed(1)} MB`}
359
- )
360
- </span>
361
- )}
362
- </li>
363
- ))}
364
- </ul>
365
- </div>
366
- )}
367
-
368
- {/* Variant Selector */}
369
- {product.type === 'VARIABLE' && product.variants && product.variants.length > 0 && (
370
- <VariantSelector
371
- product={product}
372
- selectedVariant={selectedVariant}
373
- onVariantChange={setSelectedVariant}
374
- />
375
- )}
376
-
377
- {/* Quantity + Add to Cart */}
378
- <div className="flex items-center gap-4">
379
- <div className="border-border flex items-center rounded border">
380
- <button
381
- type="button"
382
- onClick={() => setQuantity((q) => Math.max(1, q - 1))}
383
- className="text-foreground hover:bg-muted px-3 py-2 transition-colors"
384
- aria-label={t('decreaseQuantity')}
385
- >
386
- -
387
- </button>
388
- <span className="text-foreground min-w-[3rem] px-4 py-2 text-center text-sm font-medium">
389
- {quantity}
390
- </span>
391
- <button
392
- type="button"
393
- onClick={() => setQuantity((q) => q + 1)}
394
- className="text-foreground hover:bg-muted px-3 py-2 transition-colors"
395
- aria-label={t('increaseQuantity')}
396
- >
397
- +
398
- </button>
399
- </div>
400
-
401
- <button
402
- type="button"
403
- onClick={handleAddToCart}
404
- disabled={!canPurchase || addingToCart}
405
- className={cn(
406
- 'flex-1 rounded px-6 py-3 text-sm font-medium transition-all',
407
- canPurchase
408
- ? 'bg-primary text-primary-foreground hover:opacity-90'
409
- : 'bg-muted text-muted-foreground cursor-not-allowed'
410
- )}
411
- >
412
- {addingToCart ? (
413
- <span className="inline-flex items-center gap-2">
414
- <LoadingSpinner
415
- size="sm"
416
- className="border-primary-foreground/30 border-t-primary-foreground"
417
- />
418
- {t('addingToCart')}
419
- </span>
420
- ) : addedMessage ? (
421
- t('addedToCart')
422
- ) : !canPurchase ? (
423
- t('outOfStock')
424
- ) : (
425
- t('addToCart')
426
- )}
427
- </button>
428
- </div>
429
-
430
- {/* Download after purchase note */}
431
- {product.isDownloadable && (
432
- <p className="text-muted-foreground text-sm">{t('downloadAfterPurchase')}</p>
433
- )}
434
-
435
- {/* Description */}
436
- {description && (
437
- <div className="border-border border-t pt-4">
438
- <h2 className="text-foreground mb-3 text-lg font-semibold">{t('description')}</h2>
439
- {'html' in description ? (
440
- <div
441
- className="prose prose-sm text-muted-foreground max-w-none"
442
- dangerouslySetInnerHTML={{ __html: sanitizeProductHtml(description.html) }}
443
- />
444
- ) : (
445
- <p className="text-muted-foreground whitespace-pre-wrap">{description.text}</p>
446
- )}
447
- </div>
448
- )}
449
-
450
- {/* Metafields / Specifications */}
451
- {product.metafields && product.metafields.length > 0 && (
452
- <div className="border-border border-t pt-4">
453
- <h2 className="text-foreground mb-3 text-lg font-semibold">{t('specifications')}</h2>
454
- <table className="w-full text-sm">
455
- <tbody>
456
- {product.metafields.map((field) => (
457
- <tr key={field.id} className="border-border border-b last:border-0">
458
- <td className="text-foreground whitespace-nowrap py-2 pe-4 font-medium">
459
- {field.definitionName}
460
- </td>
461
- <td className="text-muted-foreground py-2">
462
- <MetafieldValue field={field} />
463
- </td>
464
- </tr>
465
- ))}
466
- </tbody>
467
- </table>
468
- </div>
469
- )}
470
- </div>
471
- </div>
472
-
473
- {/* Frequently Bought Together (cross-sells) */}
474
- {recommendations?.crossSells && recommendations.crossSells.length > 0 && (
475
- <FrequentlyBoughtTogether
476
- items={recommendations.crossSells}
477
- currentProduct={product}
478
- className="mt-12"
479
- />
480
- )}
481
-
482
- {/* Upsells */}
483
- {recommendations?.upsells && recommendations.upsells.length > 0 && (
484
- <RecommendationSection
485
- title={t('upgradeYourChoice')}
486
- items={recommendations.upsells}
487
- className="mt-12"
488
- />
489
- )}
490
-
491
- {/* Related products */}
492
- {recommendations?.related && recommendations.related.length > 0 && (
493
- <RecommendationSection
494
- title={t('similarProducts')}
495
- items={recommendations.related}
496
- className="mt-12"
497
- />
498
- )}
499
- </div>
500
- );
501
- }
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
+ }