'use client'; import { useState, useEffect, useMemo, useRef } from 'react'; import Link from 'next/link'; import Image from 'next/image'; import { useRouter } from 'next/navigation'; import { catalogService, ProductResponse, CategoryResponse, BrandResponse, } from '@/services/api/catalogService'; import { formatCurrency, getCatalogPriceInfo, getImageUrl } from '@/lib/utils'; import { applyCatalogFilters, CATALOG_API_LIMIT, CATALOG_MAX_API_PAGES, CATALOG_PAGE_SIZE, CATALOG_PRICE_RANGES, getDisplayStarCount, productMatchesRating, type CatalogHighlight, } from '@/lib/catalogFilters'; import { LayoutGrid, List, Minus, Plus, Heart, Eye, GitCompare, ShoppingCart, Star, ChevronDown, ChevronRight, SlidersHorizontal, X, } from 'lucide-react'; import { useCartStore } from '@/store/cartStore'; import { AnnouncementBar } from '@/layout/AnnouncementBar'; import { Header } from '@/layout/Header'; import { Navbar } from '@/layout/Navbar'; import { Footer } from '@/layout/Footer'; import { StickyHeaderSpacer } from '@/components/StickyHeaderSpacer'; import { FloatingButtons } from '@/components/FloatingButtons'; import { ProductCardSkeleton } from '@/components/ui/Skeleton'; import { mapProductCardToProductResponse } from '@/utils/productMapper'; import { addToCompareAndNavigate } from '@/lib/compare'; import BlurHashImage from '@/components/ui/BlurHashImage'; interface StandardCatalogProps { initialCategory?: CategoryResponse | null; categoryParam?: string | null; brandParam?: string | null; searchQuery?: string | null; } const HIGHLIGHTS: CatalogHighlight[] = [ 'All Products', 'Best Seller', 'New Arrivals', 'Sale', 'Hot Items', ]; type CollapseKey = 'categories' | 'brands' | 'highlight' | 'price'; function mapApiProduct(p: any): ProductResponse { return mapProductCardToProductResponse(p); } function CatalogProductCard({ product, viewMode, }: { product: ProductResponse; viewMode: 'grid' | 'list'; }) { const addToCart = useCartStore((s) => s.addToCart); const toggleWishlist = useCartStore((s) => s.toggleWishlist); const setQuickViewProduct = useCartStore((s) => s.setQuickViewProduct); const router = useRouter(); const wishlist = useCartStore((s) => s.wishlist) || []; const compareList = useCartStore((s) => s.compareList) || []; const variant = product.variants?.[0]; const productUrl = product.variant_url || `/products/${product.slug}`; const { price, oldPrice, discount: mappedDiscount } = getCatalogPriceInfo(product); const compare = oldPrice || 0; const discount = mappedDiscount || (compare > price ? Math.round(((compare - price) / compare) * 100) : 0); const image = getImageUrl((product as any).thumbnail_url || product.images?.[0]?.image_url); const rating = getDisplayStarCount(product); const isWishlisted = wishlist.some((i) => i.product_id === product.product_id); const isCompared = compareList.some((i) => i.product_id === product.product_id); const hasOptions = (product.variants?.length || 0) > 1; const ctaLabel = hasOptions ? 'Select Options' : 'Add To Cart'; const handleCart = (e: React.MouseEvent) => { e.preventDefault(); e.stopPropagation(); if (!variant) return; if (hasOptions) { window.location.href = productUrl; return; } void addToCart(product, variant, 1); }; if (viewMode === 'list') { return (
{discount > 0 && ( -{discount}% )} {image ? ( ) : (
)}
{product.name}
{Array.from({ length: 5 }).map((_, i) => ( ))}
{formatCurrency(price)} {compare > price && ( {formatCurrency(compare)} )}
); } return (
{discount > 0 && ( -{discount}% )}
{image ? ( ) : (
)}
{product.name}
{Array.from({ length: 5 }).map((_, i) => ( ))}
{formatCurrency(price)} {compare > price && ( {formatCurrency(compare)} )}
); } function FilterCard({ title, open, onToggle, children, }: { title: string; open: boolean; onToggle: () => void; children: React.ReactNode; }) { return (
{open &&
{children}
}
); } export function StandardCatalog({ initialCategory, categoryParam, brandParam, searchQuery, }: StandardCatalogProps) { const router = useRouter(); const [productPool, setProductPool] = useState([]); const [categories, setCategories] = useState([]); const [brands, setBrands] = useState([]); const [selectedCategory, setSelectedCategory] = useState( categoryParam || initialCategory?.category_id || 'all' ); const [selectedBrand, setSelectedBrand] = useState(brandParam || 'all'); const [highlight, setHighlight] = useState('All Products'); const [priceRangeId, setPriceRangeId] = useState('all'); const [sortBy, setSortBy] = useState('default'); const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid'); const [page, setPage] = useState(1); const [isLoading, setIsLoading] = useState(true); const [loadingMore, setLoadingMore] = useState(false); const [isMobileFilterOpen, setIsMobileFilterOpen] = useState(false); const [expandedCategoryIds, setExpandedCategoryIds] = useState>({}); const fetchIdRef = useRef(0); const [collapsed, setCollapsed] = useState>({ categories: false, brands: false, highlight: false, price: false, }); const [allProductsTotal, setAllProductsTotal] = useState(0); const [categoryCounts, setCategoryCounts] = useState>({}); useEffect(() => { catalogService.getProductsPaginated({ limit: 1 }).then((res) => { if (res && typeof res.total === 'number') { setAllProductsTotal(res.total); } }).catch(() => {}); }, []); const toggleCollapse = (key: CollapseKey) => setCollapsed((prev) => ({ ...prev, [key]: !prev[key] })); // Synchronize URL search params seamlessly const syncUrlParams = (catId: string, brandId: string) => { if (typeof window === 'undefined') return; const currentParams = new URLSearchParams(window.location.search); if (catId && catId !== 'all') { const cat = categories.find( (c) => c.category_id === catId || c.slug.toLowerCase() === catId.toLowerCase() ); currentParams.set('category', cat?.slug || catId); } else { currentParams.delete('category'); } if (brandId && brandId !== 'all') { const b = brands.find( (br) => br.brand_id === brandId || br.slug.toLowerCase() === brandId.toLowerCase() ); currentParams.set('brand', b?.slug || brandId); } else { currentParams.delete('brand'); } const qs = currentParams.toString(); router.replace(`/shop${qs ? `?${qs}` : ''}`, { scroll: false }); }; const handleCategorySelect = (catId: string) => { const nextCat = selectedCategory === catId ? 'all' : catId; setSelectedCategory(nextCat); syncUrlParams(nextCat, selectedBrand); }; const handleBrandSelect = (brandId: string) => { const nextBrand = selectedBrand === brandId ? 'all' : brandId; setSelectedBrand(nextBrand); syncUrlParams(selectedCategory, nextBrand); }; useEffect(() => { catalogService.getCategories().then((catData) => { setCategories(catData); const counts: Record = {}; for (const c of catData) { if (c.product_count != null) { counts[c.category_id] = c.product_count; counts[c.slug] = c.product_count; } } setCategoryCounts(counts); if (categoryParam) { const found = catData.find( (c) => c.slug.toLowerCase() === categoryParam.toLowerCase() || c.category_id === categoryParam ); setSelectedCategory(found?.category_id || categoryParam); } else if (initialCategory) { setSelectedCategory(initialCategory.category_id); } }); }, [categoryParam, initialCategory]); // Group root categories and their child subcategories const rootCategories = useMemo(() => { return categories.filter((c) => !c.parent_category_id); }, [categories]); const subCategoriesMap = useMemo(() => { const map: Record = {}; for (const cat of categories) { if (cat.parent_category_id) { if (!map[cat.parent_category_id]) map[cat.parent_category_id] = []; map[cat.parent_category_id].push(cat); } } return map; }, [categories]); // Auto-expand active category parent in accordion useEffect(() => { if (selectedCategory && selectedCategory !== 'all') { const found = categories.find( (c) => c.category_id === selectedCategory || c.slug.toLowerCase() === selectedCategory.toLowerCase() ); if (found?.parent_category_id) { setExpandedCategoryIds((prev) => ({ ...prev, [found.parent_category_id!]: true })); } else if (found?.category_id) { setExpandedCategoryIds((prev) => ({ ...prev, [found.category_id]: true })); } } }, [selectedCategory, categories]); useEffect(() => { const activeCatId = selectedCategory === 'all' ? undefined : selectedCategory; catalogService.getBrands(activeCatId).then((brandData) => { setBrands(brandData); if (brandParam) { const found = brandData.find( (b) => b.slug.toLowerCase() === brandParam.toLowerCase() || b.brand_id === brandParam ); setSelectedBrand(found?.brand_id || brandParam); } else { setSelectedBrand('all'); } }); }, [selectedCategory, brandParam]); useEffect(() => { setPage(1); }, [ selectedCategory, selectedBrand, searchQuery, highlight, priceRangeId, sortBy, ]); useEffect(() => { const fetchId = ++fetchIdRef.current; setIsLoading(true); setProductPool([]); const loadAll = async () => { const paramsBase: Record = { limit: CATALOG_API_LIMIT, }; if (selectedCategory !== 'all') paramsBase.category = selectedCategory; if (selectedBrand !== 'all') paramsBase.brand = selectedBrand; if (searchQuery) { paramsBase.search = searchQuery; // Sunsky-style: keyword searches expand each active variant into its own card paramsBase.expand_variants = 'true'; } const accumulated: ProductResponse[] = []; const seen = new Set(); let apiPage = 1; let total = Number.POSITIVE_INFINITY; while (apiPage <= CATALOG_MAX_API_PAGES && accumulated.length < total) { try { const res = await catalogService.getProductsPaginated({ ...paramsBase, page: apiPage, }); if (fetchId !== fetchIdRef.current) return; total = typeof res.total === 'number' ? res.total : accumulated.length; const mapped = (res.products || []).map(mapApiProduct); if (mapped.length === 0) break; let added = 0; for (const product of mapped) { // Variant-expanded cards share the same product_id — dedupe per variant const dedupeKey = product.variant_url || product.product_id; if (seen.has(dedupeKey)) continue; seen.add(dedupeKey); accumulated.push(product); added += 1; } if (added > 0) { setProductPool([...accumulated]); if (apiPage === 1) setIsLoading(false); } if (accumulated.length >= total || mapped.length < CATALOG_API_LIMIT) break; apiPage += 1; } catch { break; } } if (fetchId !== fetchIdRef.current) return; setProductPool([...accumulated]); setIsLoading(false); }; void loadAll(); }, [selectedCategory, selectedBrand, searchQuery]); const filteredProducts = useMemo(() => { return applyCatalogFilters(productPool, { priceRangeId, selectedRating: null, highlight, sortBy, }); }, [productPool, priceRangeId, highlight, sortBy]); const displayed = useMemo( () => filteredProducts.slice(0, page * CATALOG_PAGE_SIZE), [filteredProducts, page] ); const totalProducts = filteredProducts.length; const showingFrom = displayed.length === 0 ? 0 : 1; const showingTo = displayed.length; const hasMore = displayed.length < totalProducts; const resetFilters = () => { setSelectedCategory('all'); setSelectedBrand('all'); setHighlight('All Products'); setPriceRangeId('all'); setSortBy('default'); setPage(1); if (typeof window !== 'undefined') { const currentParams = new URLSearchParams(window.location.search); currentParams.delete('category'); currentParams.delete('brand'); currentParams.delete('search'); const qs = currentParams.toString(); router.replace(`/shop${qs ? `?${qs}` : ''}`, { scroll: false }); } }; const handleLoadMore = () => { setLoadingMore(true); setPage((p) => p + 1); requestAnimationFrame(() => setLoadingMore(false)); }; const activeFiltersCount = useMemo(() => { let count = 0; if (selectedCategory !== 'all') count++; if (selectedBrand !== 'all') count++; if (highlight !== 'All Products') count++; if (priceRangeId !== 'all') count++; return count; }, [selectedCategory, selectedBrand, highlight, priceRangeId]); // Reusable Filter Cards Component (used in both desktop sidebar & mobile drawer) const renderFiltersContent = () => (
{/* 1. Categories Accordion */} toggleCollapse('categories')} >
{rootCategories.map((parent) => { const isParentActive = selectedCategory === parent.category_id || selectedCategory.toLowerCase() === parent.slug.toLowerCase(); const parentCount = categoryCounts[parent.category_id] ?? categoryCounts[parent.slug] ?? parent.product_count ?? 0; const subs = subCategoriesMap[parent.category_id] || parent.sub_categories || []; const hasSubs = subs.length > 0; const isExpanded = !!expandedCategoryIds[parent.category_id]; return (
({parentCount}) {hasSubs && ( )}
{hasSubs && isExpanded && (
{subs.map((sub) => { const isSubActive = selectedCategory === sub.category_id || selectedCategory.toLowerCase() === sub.slug.toLowerCase(); const subCount = categoryCounts[sub.category_id] ?? categoryCounts[sub.slug] ?? sub.product_count ?? 0; return ( ); })}
)}
); })}
{/* 2. Brands */} toggleCollapse('brands')}>
{brands.map((brand) => { const checked = selectedBrand === brand.brand_id; return ( ); })}
{/* 3. Highlight */} toggleCollapse('highlight')} >
{HIGHLIGHTS.map((item) => ( ))}
{/* 4. Price Filter */} toggleCollapse('price')}>
{CATALOG_PRICE_RANGES.map((range) => ( ))}
); return (
{/* Mobile Filter & Sort Bar (Visible on mobile/tablet < lg) */}
Sort:
{/* Active Filter Chips */} {activeFiltersCount > 0 && (
Active: {selectedCategory !== 'all' && ( )} {selectedBrand !== 'all' && ( )} {priceRangeId !== 'all' && ( )} {highlight !== 'All Products' && ( )}
)}
{/* Desktop Sidebar: hidden on mobile (< lg), shown on lg+ */}

Showing{' '} {showingFrom}–{showingTo} {' '} of {totalProducts} results

{isLoading ? (
{Array.from({ length: 8 }).map((_, i) => (
))}
) : displayed.length === 0 ? (

No products found matching your filters.

) : viewMode === 'grid' ? (
{displayed.map((p) => ( ))}
) : (
{displayed.map((p) => ( ))}
)} {hasMore && !isLoading && (
)}
{/* Slide-over Mobile Filter Drawer */} {isMobileFilterOpen && (
{/* Backdrop */}
setIsMobileFilterOpen(false)} /> {/* Drawer Sheet */}
{/* Header */}

Filters

{activeFiltersCount > 0 && ( {activeFiltersCount} )}
{/* Scrollable Body */}
{renderFiltersContent()}
{/* Sticky Footer */}
)}
); }