create-brainerce-store 1.11.0 → 1.11.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,434 +1,430 @@
1
- 'use client';
2
-
3
- import { Suspense, useEffect, useState, useCallback, useRef } from 'react';
4
- import { useSearchParams, useRouter } from 'next/navigation';
5
- import type { Product } from 'brainerce';
6
- import type { ProductQueryParams } from 'brainerce';
7
- import { getClient } from '@/lib/brainerce';
8
- import { ProductGrid } from '@/components/products/product-grid';
9
- import { LoadingSpinner } from '@/components/shared/loading-spinner';
10
- import { useTranslations } from '@/lib/translations';
11
- import { cn } from '@/lib/utils';
12
-
13
- const PAGE_SIZE = 20;
14
-
15
- type SortOption = {
16
- labelKey: 'sortNewest' | 'sortNameAZ' | 'sortNameZA' | 'sortPriceLow' | 'sortPriceHigh';
17
- sortBy: ProductQueryParams['sortBy'];
18
- sortOrder: ProductQueryParams['sortOrder'];
19
- };
20
-
21
- const sortOptions: SortOption[] = [
22
- { labelKey: 'sortNewest', sortBy: 'createdAt', sortOrder: 'desc' },
23
- { labelKey: 'sortNameAZ', sortBy: 'name', sortOrder: 'asc' },
24
- { labelKey: 'sortNameZA', sortBy: 'name', sortOrder: 'desc' },
25
- { labelKey: 'sortPriceLow', sortBy: 'price', sortOrder: 'asc' },
26
- { labelKey: 'sortPriceHigh', sortBy: 'price', sortOrder: 'desc' },
27
- ];
28
-
29
- interface CategoryNode {
30
- id: string;
31
- name: string;
32
- parentId?: string | null;
33
- children: CategoryNode[];
34
- }
35
-
36
- /** Collect all descendant IDs (including self) */
37
- function getAllDescendantIds(node: CategoryNode): string[] {
38
- const ids = [node.id];
39
- for (const child of node.children) {
40
- ids.push(...getAllDescendantIds(child));
41
- }
42
- return ids;
43
- }
44
-
45
- /** Check if a category or any of its descendants matches the selected ID */
46
- function isActiveInTree(node: CategoryNode, selectedId: string): boolean {
47
- if (node.id === selectedId) return true;
48
- return node.children.some((child) => isActiveInTree(child, selectedId));
49
- }
50
-
51
- /** Chevron down SVG */
52
- function ChevronDown({ className }: { className?: string }) {
53
- return (
54
- <svg
55
- className={className}
56
- width="12"
57
- height="12"
58
- viewBox="0 0 12 12"
59
- fill="none"
60
- stroke="currentColor"
61
- strokeWidth="2"
62
- strokeLinecap="round"
63
- strokeLinejoin="round"
64
- >
65
- <path d="M3 4.5L6 7.5L9 4.5" />
66
- </svg>
67
- );
68
- }
69
-
70
- /** Recursive dropdown items for nested categories */
71
- function CategoryDropdownItems({
72
- children,
73
- depth,
74
- selectedId,
75
- onSelect,
76
- }: {
77
- children: CategoryNode[];
78
- depth: number;
79
- selectedId: string;
80
- onSelect: (id: string) => void;
81
- }) {
82
- return (
83
- <>
84
- {children.map((child) => (
85
- <div key={child.id}>
86
- <button
87
- onClick={() => onSelect(child.id)}
88
- className={cn(
89
- 'w-full text-start px-4 py-2 text-sm transition-colors hover:bg-muted',
90
- selectedId === child.id && 'bg-primary/10 text-primary font-medium'
91
- )}
92
- style={{ paddingInlineStart: `${(depth + 1) * 16}px` }}
93
- >
94
- {child.name}
95
- </button>
96
- {child.children.length > 0 && (
97
- <CategoryDropdownItems
98
- children={child.children}
99
- depth={depth + 1}
100
- selectedId={selectedId}
101
- onSelect={onSelect}
102
- />
103
- )}
104
- </div>
105
- ))}
106
- </>
107
- );
108
- }
109
-
110
- /** Category chip with dropdown for subcategories */
111
- function CategoryChip({
112
- category,
113
- selectedId,
114
- onSelect,
115
- tc,
116
- }: {
117
- category: CategoryNode;
118
- selectedId: string;
119
- onSelect: (id: string) => void;
120
- tc: (key: string) => string;
121
- }) {
122
- const [open, setOpen] = useState(false);
123
- const ref = useRef<HTMLDivElement>(null);
124
- const hasChildren = category.children.length > 0;
125
- const isActive = isActiveInTree(category, selectedId);
126
-
127
- // Find the display name for the selected subcategory
128
- function findName(nodes: CategoryNode[], id: string): string | null {
129
- for (const n of nodes) {
130
- if (n.id === id) return n.name;
131
- const found = findName(n.children, id);
132
- if (found) return found;
133
- }
134
- return null;
135
- }
136
-
137
- const selectedChildName =
138
- isActive && selectedId !== category.id ? findName(category.children, selectedId) : null;
139
-
140
- // Close dropdown on outside click
141
- useEffect(() => {
142
- if (!open) return;
143
- function handleClick(e: MouseEvent) {
144
- if (ref.current && !ref.current.contains(e.target as Node)) {
145
- setOpen(false);
146
- }
147
- }
148
- document.addEventListener('mousedown', handleClick);
149
- return () => document.removeEventListener('mousedown', handleClick);
150
- }, [open]);
151
-
152
- if (!hasChildren) {
153
- return (
154
- <button
155
- onClick={() => onSelect(category.id)}
156
- className={cn(
157
- 'rounded-full border px-3 py-1.5 text-sm transition-colors',
158
- selectedId === category.id
159
- ? 'bg-primary text-primary-foreground border-primary'
160
- : 'border-border text-muted-foreground hover:border-primary hover:text-foreground'
161
- )}
162
- >
163
- {category.name}
164
- </button>
165
- );
166
- }
167
-
168
- return (
169
- <div ref={ref} className="relative">
170
- <button
171
- onClick={() => setOpen((prev) => !prev)}
172
- className={cn(
173
- 'inline-flex items-center gap-1 rounded-full border px-3 py-1.5 text-sm transition-colors',
174
- isActive
175
- ? 'bg-primary text-primary-foreground border-primary'
176
- : 'border-border text-muted-foreground hover:border-primary hover:text-foreground'
177
- )}
178
- >
179
- {category.name}
180
- {selectedChildName && (
181
- <span className="opacity-80">
182
- {'·'} {selectedChildName}
183
- </span>
184
- )}
185
- <ChevronDown
186
- className={cn('transition-transform ms-0.5', open && 'rotate-180')}
187
- />
188
- </button>
189
-
190
- {open && (
191
- <div className="bg-background border-border absolute start-0 top-full z-50 mt-1 min-w-[180px] overflow-hidden rounded-lg border shadow-lg">
192
- {/* "All in [category]" option */}
193
- <button
194
- onClick={() => {
195
- onSelect(category.id);
196
- setOpen(false);
197
- }}
198
- className={cn(
199
- 'w-full text-start px-4 py-2 text-sm font-medium transition-colors hover:bg-muted',
200
- selectedId === category.id && 'bg-primary/10 text-primary'
201
- )}
202
- >
203
- {tc('all')} {category.name}
204
- </button>
205
- <div className="bg-border mx-2 h-px" />
206
- {/* Recursive children */}
207
- <div
208
- onClick={() => setOpen(false)}
209
- >
210
- <CategoryDropdownItems
211
- children={category.children}
212
- depth={0}
213
- selectedId={selectedId}
214
- onSelect={onSelect}
215
- />
216
- </div>
217
- </div>
218
- )}
219
- </div>
220
- );
221
- }
222
-
223
- function ProductsContent() {
224
- const searchParams = useSearchParams();
225
- const router = useRouter();
226
- const t = useTranslations('products');
227
- const tc = useTranslations('common');
228
-
229
- const searchQuery = searchParams.get('search') || '';
230
- const categoryId = searchParams.get('category') || '';
231
- const sortParam = searchParams.get('sort') || '0';
232
-
233
- const [products, setProducts] = useState<Product[]>([]);
234
- const [loading, setLoading] = useState(true);
235
- const [loadingMore, setLoadingMore] = useState(false);
236
- const [page, setPage] = useState(1);
237
- const [totalPages, setTotalPages] = useState(1);
238
- const [total, setTotal] = useState(0);
239
- const [categories, setCategories] = useState<CategoryNode[]>([]);
240
-
241
- const sortIndex = parseInt(sortParam, 10) || 0;
242
- const currentSort = sortOptions[sortIndex] || sortOptions[0];
243
-
244
- // Load categories (keep tree structure)
245
- useEffect(() => {
246
- async function loadCategories() {
247
- try {
248
- const client = getClient();
249
- const result = await client.getCategories();
250
- setCategories(result.categories as CategoryNode[]);
251
- } catch {
252
- // Categories endpoint may not be available in all modes
253
- }
254
- }
255
- loadCategories();
256
- }, []);
257
-
258
- // Load products when filters change
259
- const loadProducts = useCallback(
260
- async (pageNum: number, append: boolean) => {
261
- try {
262
- if (append) {
263
- setLoadingMore(true);
264
- } else {
265
- setLoading(true);
266
- }
267
-
268
- const client = getClient();
269
- const params: ProductQueryParams = {
270
- page: pageNum,
271
- limit: PAGE_SIZE,
272
- sortBy: currentSort.sortBy,
273
- sortOrder: currentSort.sortOrder,
274
- };
275
-
276
- if (searchQuery) params.search = searchQuery;
277
- if (categoryId) params.categories = categoryId;
278
-
279
- const result = await client.getProducts(params);
280
-
281
- if (append) {
282
- setProducts((prev) => [...prev, ...result.data]);
283
- } else {
284
- setProducts(result.data);
285
- }
286
- setTotalPages(result.meta.totalPages);
287
- setTotal(result.meta.total);
288
- setPage(pageNum);
289
- } catch (err) {
290
- console.error('Failed to load products:', err);
291
- } finally {
292
- setLoading(false);
293
- setLoadingMore(false);
294
- }
295
- },
296
- [searchQuery, categoryId, currentSort.sortBy, currentSort.sortOrder]
297
- );
298
-
299
- useEffect(() => {
300
- loadProducts(1, false);
301
- }, [loadProducts]);
302
-
303
- function handleLoadMore() {
304
- if (page < totalPages && !loadingMore) {
305
- loadProducts(page + 1, true);
306
- }
307
- }
308
-
309
- function updateParam(key: string, value: string) {
310
- const params = new URLSearchParams(searchParams.toString());
311
- if (value) {
312
- params.set(key, value);
313
- } else {
314
- params.delete(key);
315
- }
316
- router.push(`/products?${params.toString()}`);
317
- }
318
-
319
- function handleCategorySelect(id: string) {
320
- updateParam('category', id);
321
- }
322
-
323
- return (
324
- <div className="mx-auto max-w-7xl px-4 py-8 sm:px-6 lg:px-8">
325
- {/* Page Header */}
326
- <div className="mb-8">
327
- <h1 className="text-foreground text-3xl font-bold">
328
- {searchQuery ? `${t('searchPrefix')} "${searchQuery}"` : t('allProducts')}
329
- </h1>
330
- {!loading && (
331
- <p className="text-muted-foreground mt-1 text-sm">
332
- {total} {total === 1 ? tc('product') : tc('products')} {tc('found')}
333
- </p>
334
- )}
335
- </div>
336
-
337
- {/* Filters and Sort */}
338
- <div className="mb-6 flex flex-col items-start gap-4 sm:flex-row sm:items-center">
339
- {/* Category Filter */}
340
- {categories.length > 0 && (
341
- <div className="flex flex-wrap gap-2">
342
- <button
343
- onClick={() => updateParam('category', '')}
344
- className={cn(
345
- 'rounded-full border px-3 py-1.5 text-sm transition-colors',
346
- !categoryId
347
- ? 'bg-primary text-primary-foreground border-primary'
348
- : 'border-border text-muted-foreground hover:border-primary hover:text-foreground'
349
- )}
350
- >
351
- {tc('all')}
352
- </button>
353
- {categories.map((cat) => (
354
- <CategoryChip
355
- key={cat.id}
356
- category={cat}
357
- selectedId={categoryId}
358
- onSelect={handleCategorySelect}
359
- tc={tc as (key: string) => string}
360
- />
361
- ))}
362
- </div>
363
- )}
364
-
365
- {/* Sort */}
366
- <div className="flex items-center gap-2 sm:ms-auto">
367
- <label htmlFor="sort" className="text-muted-foreground whitespace-nowrap text-sm">
368
- {tc('sortBy')}
369
- </label>
370
- <select
371
- id="sort"
372
- value={sortIndex}
373
- onChange={(e) => updateParam('sort', e.target.value)}
374
- className="border-border bg-background text-foreground focus:ring-primary/20 focus:border-primary h-9 rounded border px-3 text-sm focus:outline-none focus:ring-2"
375
- >
376
- {sortOptions.map((opt, idx) => (
377
- <option key={idx} value={idx}>
378
- {t(opt.labelKey)}
379
- </option>
380
- ))}
381
- </select>
382
- </div>
383
- </div>
384
-
385
- {/* Products Grid */}
386
- {loading ? (
387
- <div className="flex items-center justify-center py-20">
388
- <LoadingSpinner size="lg" />
389
- </div>
390
- ) : (
391
- <>
392
- <ProductGrid products={products} />
393
-
394
- {/* Load More */}
395
- {page < totalPages && (
396
- <div className="mt-10 flex justify-center">
397
- <button
398
- onClick={handleLoadMore}
399
- disabled={loadingMore}
400
- className="bg-primary text-primary-foreground inline-flex items-center gap-2 rounded px-6 py-2.5 font-medium transition-opacity hover:opacity-90 disabled:opacity-50"
401
- >
402
- {loadingMore ? (
403
- <>
404
- <LoadingSpinner
405
- size="sm"
406
- className="border-primary-foreground/30 border-t-primary-foreground"
407
- />
408
- {tc('loading')}
409
- </>
410
- ) : (
411
- t('loadMore')
412
- )}
413
- </button>
414
- </div>
415
- )}
416
- </>
417
- )}
418
- </div>
419
- );
420
- }
421
-
422
- export default function ProductsPage() {
423
- return (
424
- <Suspense
425
- fallback={
426
- <div className="flex min-h-[60vh] items-center justify-center">
427
- <LoadingSpinner size="lg" />
428
- </div>
429
- }
430
- >
431
- <ProductsContent />
432
- </Suspense>
433
- );
434
- }
1
+ 'use client';
2
+
3
+ import { Suspense, useEffect, useState, useCallback, useRef } from 'react';
4
+ import { useSearchParams, useRouter } from 'next/navigation';
5
+ import type { Product } from 'brainerce';
6
+ import type { ProductQueryParams } from 'brainerce';
7
+ import { getClient } from '@/lib/brainerce';
8
+ import { ProductGrid } from '@/components/products/product-grid';
9
+ import { LoadingSpinner } from '@/components/shared/loading-spinner';
10
+ import { useTranslations } from '@/lib/translations';
11
+ import { cn } from '@/lib/utils';
12
+
13
+ const PAGE_SIZE = 20;
14
+
15
+ type SortOption = {
16
+ labelKey: 'sortNewest' | 'sortNameAZ' | 'sortNameZA' | 'sortPriceLow' | 'sortPriceHigh';
17
+ sortBy: ProductQueryParams['sortBy'];
18
+ sortOrder: ProductQueryParams['sortOrder'];
19
+ };
20
+
21
+ const sortOptions: SortOption[] = [
22
+ { labelKey: 'sortNewest', sortBy: 'createdAt', sortOrder: 'desc' },
23
+ { labelKey: 'sortNameAZ', sortBy: 'name', sortOrder: 'asc' },
24
+ { labelKey: 'sortNameZA', sortBy: 'name', sortOrder: 'desc' },
25
+ { labelKey: 'sortPriceLow', sortBy: 'price', sortOrder: 'asc' },
26
+ { labelKey: 'sortPriceHigh', sortBy: 'price', sortOrder: 'desc' },
27
+ ];
28
+
29
+ interface CategoryNode {
30
+ id: string;
31
+ name: string;
32
+ parentId?: string | null;
33
+ children: CategoryNode[];
34
+ }
35
+
36
+ /** Collect all descendant IDs (including self) */
37
+ function getAllDescendantIds(node: CategoryNode): string[] {
38
+ const ids = [node.id];
39
+ for (const child of node.children) {
40
+ ids.push(...getAllDescendantIds(child));
41
+ }
42
+ return ids;
43
+ }
44
+
45
+ /** Check if a category or any of its descendants matches the selected ID */
46
+ function isActiveInTree(node: CategoryNode, selectedId: string): boolean {
47
+ if (node.id === selectedId) return true;
48
+ return node.children.some((child) => isActiveInTree(child, selectedId));
49
+ }
50
+
51
+ /** Chevron down SVG */
52
+ function ChevronDown({ className }: { className?: string }) {
53
+ return (
54
+ <svg
55
+ className={className}
56
+ width="12"
57
+ height="12"
58
+ viewBox="0 0 12 12"
59
+ fill="none"
60
+ stroke="currentColor"
61
+ strokeWidth="2"
62
+ strokeLinecap="round"
63
+ strokeLinejoin="round"
64
+ >
65
+ <path d="M3 4.5L6 7.5L9 4.5" />
66
+ </svg>
67
+ );
68
+ }
69
+
70
+ /** Recursive dropdown items for nested categories */
71
+ function CategoryDropdownItems({
72
+ children,
73
+ depth,
74
+ selectedId,
75
+ onSelect,
76
+ }: {
77
+ children: CategoryNode[];
78
+ depth: number;
79
+ selectedId: string;
80
+ onSelect: (id: string) => void;
81
+ }) {
82
+ return (
83
+ <>
84
+ {children.map((child) => (
85
+ <div key={child.id}>
86
+ <button
87
+ onClick={() => onSelect(child.id)}
88
+ className={cn(
89
+ 'hover:bg-muted w-full px-4 py-2 text-start text-sm transition-colors',
90
+ selectedId === child.id && 'bg-primary/10 text-primary font-medium'
91
+ )}
92
+ style={{ paddingInlineStart: `${(depth + 1) * 16}px` }}
93
+ >
94
+ {child.name}
95
+ </button>
96
+ {child.children.length > 0 && (
97
+ <CategoryDropdownItems
98
+ children={child.children}
99
+ depth={depth + 1}
100
+ selectedId={selectedId}
101
+ onSelect={onSelect}
102
+ />
103
+ )}
104
+ </div>
105
+ ))}
106
+ </>
107
+ );
108
+ }
109
+
110
+ /** Category chip with dropdown for subcategories */
111
+ function CategoryChip({
112
+ category,
113
+ selectedId,
114
+ onSelect,
115
+ tc,
116
+ }: {
117
+ category: CategoryNode;
118
+ selectedId: string;
119
+ onSelect: (id: string) => void;
120
+ tc: (key: string) => string;
121
+ }) {
122
+ const [open, setOpen] = useState(false);
123
+ const ref = useRef<HTMLDivElement>(null);
124
+ const hasChildren = category.children.length > 0;
125
+ const isActive = isActiveInTree(category, selectedId);
126
+
127
+ // Find the display name for the selected subcategory
128
+ function findName(nodes: CategoryNode[], id: string): string | null {
129
+ for (const n of nodes) {
130
+ if (n.id === id) return n.name;
131
+ const found = findName(n.children, id);
132
+ if (found) return found;
133
+ }
134
+ return null;
135
+ }
136
+
137
+ const selectedChildName =
138
+ isActive && selectedId !== category.id ? findName(category.children, selectedId) : null;
139
+
140
+ // Close dropdown on outside click
141
+ useEffect(() => {
142
+ if (!open) return;
143
+ function handleClick(e: MouseEvent) {
144
+ if (ref.current && !ref.current.contains(e.target as Node)) {
145
+ setOpen(false);
146
+ }
147
+ }
148
+ document.addEventListener('mousedown', handleClick);
149
+ return () => document.removeEventListener('mousedown', handleClick);
150
+ }, [open]);
151
+
152
+ if (!hasChildren) {
153
+ return (
154
+ <button
155
+ onClick={() => onSelect(category.id)}
156
+ className={cn(
157
+ 'rounded-full border px-3 py-1.5 text-sm transition-colors',
158
+ selectedId === category.id
159
+ ? 'bg-primary text-primary-foreground border-primary'
160
+ : 'border-border text-muted-foreground hover:border-primary hover:text-foreground'
161
+ )}
162
+ >
163
+ {category.name}
164
+ </button>
165
+ );
166
+ }
167
+
168
+ return (
169
+ <div ref={ref} className="relative">
170
+ <button
171
+ onClick={() => setOpen((prev) => !prev)}
172
+ className={cn(
173
+ 'inline-flex items-center gap-1 rounded-full border px-3 py-1.5 text-sm transition-colors',
174
+ isActive
175
+ ? 'bg-primary text-primary-foreground border-primary'
176
+ : 'border-border text-muted-foreground hover:border-primary hover:text-foreground'
177
+ )}
178
+ >
179
+ {category.name}
180
+ {selectedChildName && (
181
+ <span className="opacity-80">
182
+ {'·'} {selectedChildName}
183
+ </span>
184
+ )}
185
+ <ChevronDown className={cn('ms-0.5 transition-transform', open && 'rotate-180')} />
186
+ </button>
187
+
188
+ {open && (
189
+ <div className="bg-background border-border absolute start-0 top-full z-50 mt-1 min-w-[180px] overflow-hidden rounded-lg border shadow-lg">
190
+ {/* "All in [category]" option */}
191
+ <button
192
+ onClick={() => {
193
+ onSelect(category.id);
194
+ setOpen(false);
195
+ }}
196
+ className={cn(
197
+ 'hover:bg-muted w-full px-4 py-2 text-start text-sm font-medium transition-colors',
198
+ selectedId === category.id && 'bg-primary/10 text-primary'
199
+ )}
200
+ >
201
+ {tc('all')} {category.name}
202
+ </button>
203
+ <div className="bg-border mx-2 h-px" />
204
+ {/* Recursive children */}
205
+ <div onClick={() => setOpen(false)}>
206
+ <CategoryDropdownItems
207
+ children={category.children}
208
+ depth={0}
209
+ selectedId={selectedId}
210
+ onSelect={onSelect}
211
+ />
212
+ </div>
213
+ </div>
214
+ )}
215
+ </div>
216
+ );
217
+ }
218
+
219
+ function ProductsContent() {
220
+ const searchParams = useSearchParams();
221
+ const router = useRouter();
222
+ const t = useTranslations('products');
223
+ const tc = useTranslations('common');
224
+
225
+ const searchQuery = searchParams.get('search') || '';
226
+ const categoryId = searchParams.get('category') || '';
227
+ const sortParam = searchParams.get('sort') || '0';
228
+
229
+ const [products, setProducts] = useState<Product[]>([]);
230
+ const [loading, setLoading] = useState(true);
231
+ const [loadingMore, setLoadingMore] = useState(false);
232
+ const [page, setPage] = useState(1);
233
+ const [totalPages, setTotalPages] = useState(1);
234
+ const [total, setTotal] = useState(0);
235
+ const [categories, setCategories] = useState<CategoryNode[]>([]);
236
+
237
+ const sortIndex = parseInt(sortParam, 10) || 0;
238
+ const currentSort = sortOptions[sortIndex] || sortOptions[0];
239
+
240
+ // Load categories (keep tree structure)
241
+ useEffect(() => {
242
+ async function loadCategories() {
243
+ try {
244
+ const client = getClient();
245
+ const result = await client.getCategories();
246
+ setCategories(result.categories as CategoryNode[]);
247
+ } catch {
248
+ // Categories endpoint may not be available in all modes
249
+ }
250
+ }
251
+ loadCategories();
252
+ }, []);
253
+
254
+ // Load products when filters change
255
+ const loadProducts = useCallback(
256
+ async (pageNum: number, append: boolean) => {
257
+ try {
258
+ if (append) {
259
+ setLoadingMore(true);
260
+ } else {
261
+ setLoading(true);
262
+ }
263
+
264
+ const client = getClient();
265
+ const params: ProductQueryParams = {
266
+ page: pageNum,
267
+ limit: PAGE_SIZE,
268
+ sortBy: currentSort.sortBy,
269
+ sortOrder: currentSort.sortOrder,
270
+ };
271
+
272
+ if (searchQuery) params.search = searchQuery;
273
+ if (categoryId) params.categories = categoryId;
274
+
275
+ const result = await client.getProducts(params);
276
+
277
+ if (append) {
278
+ setProducts((prev) => [...prev, ...result.data]);
279
+ } else {
280
+ setProducts(result.data);
281
+ }
282
+ setTotalPages(result.meta.totalPages);
283
+ setTotal(result.meta.total);
284
+ setPage(pageNum);
285
+ } catch (err) {
286
+ console.error('Failed to load products:', err);
287
+ } finally {
288
+ setLoading(false);
289
+ setLoadingMore(false);
290
+ }
291
+ },
292
+ [searchQuery, categoryId, currentSort.sortBy, currentSort.sortOrder]
293
+ );
294
+
295
+ useEffect(() => {
296
+ loadProducts(1, false);
297
+ }, [loadProducts]);
298
+
299
+ function handleLoadMore() {
300
+ if (page < totalPages && !loadingMore) {
301
+ loadProducts(page + 1, true);
302
+ }
303
+ }
304
+
305
+ function updateParam(key: string, value: string) {
306
+ const params = new URLSearchParams(searchParams.toString());
307
+ if (value) {
308
+ params.set(key, value);
309
+ } else {
310
+ params.delete(key);
311
+ }
312
+ router.push(`/products?${params.toString()}`);
313
+ }
314
+
315
+ function handleCategorySelect(id: string) {
316
+ updateParam('category', id);
317
+ }
318
+
319
+ return (
320
+ <div className="mx-auto max-w-7xl px-4 py-8 sm:px-6 lg:px-8">
321
+ {/* Page Header */}
322
+ <div className="mb-8">
323
+ <h1 className="text-foreground text-3xl font-bold">
324
+ {searchQuery ? `${t('searchPrefix')} "${searchQuery}"` : t('allProducts')}
325
+ </h1>
326
+ {!loading && (
327
+ <p className="text-muted-foreground mt-1 text-sm">
328
+ {total} {total === 1 ? tc('product') : tc('products')} {tc('found')}
329
+ </p>
330
+ )}
331
+ </div>
332
+
333
+ {/* Filters and Sort */}
334
+ <div className="mb-6 flex flex-col items-start gap-4 sm:flex-row sm:items-center">
335
+ {/* Category Filter */}
336
+ {categories.length > 0 && (
337
+ <div className="flex flex-wrap gap-2">
338
+ <button
339
+ onClick={() => updateParam('category', '')}
340
+ className={cn(
341
+ 'rounded-full border px-3 py-1.5 text-sm transition-colors',
342
+ !categoryId
343
+ ? 'bg-primary text-primary-foreground border-primary'
344
+ : 'border-border text-muted-foreground hover:border-primary hover:text-foreground'
345
+ )}
346
+ >
347
+ {tc('all')}
348
+ </button>
349
+ {categories.map((cat) => (
350
+ <CategoryChip
351
+ key={cat.id}
352
+ category={cat}
353
+ selectedId={categoryId}
354
+ onSelect={handleCategorySelect}
355
+ tc={tc as (key: string) => string}
356
+ />
357
+ ))}
358
+ </div>
359
+ )}
360
+
361
+ {/* Sort */}
362
+ <div className="flex items-center gap-2 sm:ms-auto">
363
+ <label htmlFor="sort" className="text-muted-foreground whitespace-nowrap text-sm">
364
+ {tc('sortBy')}
365
+ </label>
366
+ <select
367
+ id="sort"
368
+ value={sortIndex}
369
+ onChange={(e) => updateParam('sort', e.target.value)}
370
+ className="border-border bg-background text-foreground focus:ring-primary/20 focus:border-primary h-9 rounded border px-3 text-sm focus:outline-none focus:ring-2"
371
+ >
372
+ {sortOptions.map((opt, idx) => (
373
+ <option key={idx} value={idx}>
374
+ {t(opt.labelKey)}
375
+ </option>
376
+ ))}
377
+ </select>
378
+ </div>
379
+ </div>
380
+
381
+ {/* Products Grid */}
382
+ {loading ? (
383
+ <div className="flex items-center justify-center py-20">
384
+ <LoadingSpinner size="lg" />
385
+ </div>
386
+ ) : (
387
+ <>
388
+ <ProductGrid products={products} />
389
+
390
+ {/* Load More */}
391
+ {page < totalPages && (
392
+ <div className="mt-10 flex justify-center">
393
+ <button
394
+ onClick={handleLoadMore}
395
+ disabled={loadingMore}
396
+ className="bg-primary text-primary-foreground inline-flex items-center gap-2 rounded px-6 py-2.5 font-medium transition-opacity hover:opacity-90 disabled:opacity-50"
397
+ >
398
+ {loadingMore ? (
399
+ <>
400
+ <LoadingSpinner
401
+ size="sm"
402
+ className="border-primary-foreground/30 border-t-primary-foreground"
403
+ />
404
+ {tc('loading')}
405
+ </>
406
+ ) : (
407
+ t('loadMore')
408
+ )}
409
+ </button>
410
+ </div>
411
+ )}
412
+ </>
413
+ )}
414
+ </div>
415
+ );
416
+ }
417
+
418
+ export default function ProductsPage() {
419
+ return (
420
+ <Suspense
421
+ fallback={
422
+ <div className="flex min-h-[60vh] items-center justify-center">
423
+ <LoadingSpinner size="lg" />
424
+ </div>
425
+ }
426
+ >
427
+ <ProductsContent />
428
+ </Suspense>
429
+ );
430
+ }