'use client'; import React, { useState, useEffect } from 'react'; import ProductCard from './product-card'; import { getProductsPage } from '@/hooks/use-shopify-products'; import { Button } from '@/components/ui/button'; import { Loader } from '@/components/ui/loader'; interface ProductImage { url: string; altText?: string | null; } interface ProductPrice { amount: string; currencyCode: string; } interface ProductVariant { id: string; title: string; price: ProductPrice; availableForSale: boolean; } interface Product { id: string; title: string; description?: string; handle: string; images: { edges: Array<{ node: ProductImage; }>; }; priceRange: { minVariantPrice: ProductPrice; }; compareAtPriceRange?: { minVariantPrice: ProductPrice; }; variants: { edges: Array<{ node: ProductVariant; }>; }; } interface ProductsProps { title?: string; subtitle?: string; limit?: number; showLoadMore?: boolean; } const Products: React.FC = ({ title = 'Shopify Hydrogen Storefront', subtitle = 'An agent-friendly Shopify storefront built with Next.js and Hydrogen.', limit = 12, showLoadMore = true, }) => { const [products, setProducts] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [loadingMore, setLoadingMore] = useState(false); const [hasMoreProducts, setHasMoreProducts] = useState(true); const [cursor, setCursor] = useState(null); // Paging is cursor-based: without `after`, Shopify returns the same first // page every time and "load more" appends nothing. const fetchProducts = async (loadMore = false) => { try { if (loadMore) { setLoadingMore(true); } else { setLoading(true); setError(null); } const page = await getProductsPage({ first: limit, after: loadMore ? cursor : null, sortKey: 'CREATED_AT', reverse: true, }); setProducts((prev) => { if (!loadMore) return page.products; const existingIds = new Set(prev.map((p) => p.id)); return [ ...prev, ...page.products.filter((p) => !existingIds.has(p.id)), ]; }); setCursor(page.endCursor); setHasMoreProducts(page.hasNextPage); } catch (err) { console.error('Error fetching products:', err); setError(err instanceof Error ? err.message : 'Failed to load products'); } finally { setLoading(false); setLoadingMore(false); } }; useEffect(() => { fetchProducts(); }, [limit]); const handleLoadMore = () => { if (!loadingMore && hasMoreProducts) { fetchProducts(true); } }; if (loading) { return (

{title}

{subtitle}

{Array.from({ length: 8 }).map((_, index) => (
))}
); } if (error || products.length === 0) { return (

{title}

{subtitle}

{error || 'Our curated collection is being prepared. Please check back shortly.'}

{error && ( )}
); } return (

{title}

{subtitle}

{products.map((product) => ( ))}
{showLoadMore && hasMoreProducts && (
)}
); }; export default Products;