create-brainerce-store 1.11.0 → 1.11.2

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