Initial commit

This commit is contained in:
Rami Bitar
2026-04-19 11:17:41 -04:00
commit b5a79b6475
77 changed files with 10416 additions and 0 deletions

View File

@@ -0,0 +1,240 @@
"use client";
import React, { useState, useEffect } from 'react';
import { getProduct } from '@/hooks/use-shopify-products';
import { useShopifyCart } from '@/hooks/use-shopify-cart';
import ProductDetailGallery from './ProductDetailGallery';
import ProductDetailInfo from './ProductDetailInfo';
import { Button } from '../ui/button';
interface ProductImage {
url: string;
altText?: string;
}
interface ProductPrice {
amount: string;
currencyCode: string;
}
export interface ProductVariant {
id: string;
title: string;
price: ProductPrice;
availableForSale: boolean;
selectedOptions: Array<{
name: string;
value: string;
}>;
image?: {
url: string;
altText?: string;
};
}
interface ProductOption {
id: string;
name: string;
values: string[];
}
export interface Product {
id: string;
title: string;
description?: string;
descriptionHtml?: string;
handle: string;
images: {
edges: Array<{
node: ProductImage;
}>;
};
priceRange: {
minVariantPrice: ProductPrice;
};
compareAtPriceRange?: {
minVariantPrice: ProductPrice;
};
variants: {
edges: Array<{
node: ProductVariant;
}>;
};
options: ProductOption[];
}
type ProductDetailProps = {
handle: string;
onAddToCart?: () => void;
}
const ProductDetail: React.FC<ProductDetailProps> = ({ handle, onAddToCart: onAddToCartCallback }) => {
const { addItem, openCart } = useShopifyCart();
const [product, setProduct] = useState<Product | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [selectedVariant, setSelectedVariant] = useState<ProductVariant | null>(null);
const [selectedOptions, setSelectedOptions] = useState<Record<string, string>>({});
const [quantity, setQuantity] = useState(1);
const [selectedImageIndex, setSelectedImageIndex] = useState(0);
const [isAddingToCart, setIsAddingToCart] = useState(false);
useEffect(() => {
if (!handle) return;
const fetchProduct = async () => {
try {
setLoading(true);
setError(null);
const productData = await getProduct(handle);
if (!productData) {
setError('Product not found');
return;
}
setProduct(productData);
// Set default variant
const firstVariant = productData.variants.edges[0]?.node;
if (firstVariant) {
setSelectedVariant(firstVariant);
// Initialize selected options
const initialOptions: Record<string, string> = {};
firstVariant.selectedOptions.forEach(option => {
initialOptions[option.name] = option.value;
});
setSelectedOptions(initialOptions);
}
} catch (err) {
console.error('Error fetching product:', err);
setError(err instanceof Error ? err.message : 'Failed to load product');
} finally {
setLoading(false);
}
};
fetchProduct();
}, [handle]);
const handleOptionChange = (optionName: string, value: string) => {
const newOptions = { ...selectedOptions, [optionName]: value };
setSelectedOptions(newOptions);
// Find matching variant
const matchingVariant = product?.variants.edges.find(({ node }) => {
return node.selectedOptions.every(option =>
newOptions[option.name] === option.value
);
});
if (matchingVariant) {
setSelectedVariant(matchingVariant.node);
// Update image if variant has an associated image
if (matchingVariant.node.image && product) {
const imageIndex = product.images.edges.findIndex(
({ node }) => node.url === matchingVariant.node.image?.url
);
if (imageIndex !== -1) {
setSelectedImageIndex(imageIndex);
}
}
}
};
const handleAddToCart = async () => {
if (!selectedVariant || !product) return;
setIsAddingToCart(true);
try {
await addItem(selectedVariant.id, quantity);
openCart();
if (onAddToCartCallback) {
onAddToCartCallback();
}
} catch (error) {
console.error('Failed to add item to cart:', error);
} finally {
setIsAddingToCart(false);
}
};
if (loading) {
return (
<div className="container mx-auto px-4 py-8">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
{/* Image Gallery Skeleton */}
<div>
<div className="aspect-square bg-gray-200 rounded-lg animate-pulse mb-4"></div>
<div className="grid grid-cols-4 gap-2">
{Array.from({ length: 4 }).map((_, i) => (
<div key={i} className="aspect-square bg-gray-200 rounded animate-pulse"></div>
))}
</div>
</div>
{/* Product Info Skeleton */}
<div>
<div className="h-8 bg-gray-200 rounded mb-4 animate-pulse"></div>
<div className="h-6 bg-gray-200 rounded mb-6 w-1/3 animate-pulse"></div>
<div className="h-24 bg-gray-200 rounded mb-6 animate-pulse"></div>
<div className="h-12 bg-gray-200 rounded mb-4 animate-pulse"></div>
<div className="h-12 bg-gray-200 rounded animate-pulse"></div>
</div>
</div>
</div>
);
}
if (error || !product) {
return (
<div className="container mx-auto px-4 py-8 text-center">
<div className="bg-red-50 border border-red-200 rounded-lg p-8 max-w-md mx-auto">
<i className="ri-error-warning-line text-4xl text-red-500 mb-4"></i>
<h3 className="text-lg font-semibold text-red-800 mb-2">
Product Not Found
</h3>
<p className="text-red-600 mb-4">
{error || 'The requested product could not be found.'}
</p>
<Button
onClick={() => window.history.back()}
variant="destructive"
>
Go Back
</Button>
</div>
</div>
);
}
return (
<div className="bg-white">
<div className="container mx-auto px-4 py-8">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
<ProductDetailGallery
images={product.images.edges.map(edge => edge.node)}
selectedImageIndex={selectedImageIndex}
onImageChange={setSelectedImageIndex}
/>
<ProductDetailInfo
product={product}
selectedVariant={selectedVariant}
selectedOptions={selectedOptions}
quantity={quantity}
setQuantity={setQuantity}
handleAddToCart={handleAddToCart}
onOptionChange={handleOptionChange}
isAddingToCart={isAddingToCart}
/>
</div>
</div>
</div>
);
};
export default ProductDetail;

View File

@@ -0,0 +1,59 @@
import React from 'react';
interface ProductImage {
url: string;
altText?: string;
}
interface ProductDetailGalleryProps {
images: ProductImage[];
selectedImageIndex: number;
onImageChange: (index: number) => void;
}
const ProductDetailGallery: React.FC<ProductDetailGalleryProps> = ({ images, selectedImageIndex, onImageChange }) => {
return (
<div>
{/* Main Image */}
<div className="aspect-square bg-gray-100 rounded-lg overflow-hidden mb-4">
{images.length > 0 ? (
<img
src={images[selectedImageIndex].url}
alt={images[selectedImageIndex].altText || 'Product image'}
className="w-full h-full object-cover"
/>
) : (
<div className="w-full h-full flex items-center justify-center text-gray-400">
<i className="ri-image-line text-6xl"></i>
</div>
)}
</div>
{/* Image Thumbnails */}
{images.length > 1 && (
<div className="grid grid-cols-4 gap-2">
{images.map((image, index) => (
<button
key={index}
onClick={() => onImageChange(index)}
className={`aspect-square rounded-lg overflow-hidden border-2 transition-colors ${
selectedImageIndex === index
? 'border-black'
: 'border-gray-200 hover:border-gray-300'
}`}
>
<img
src={image.url}
alt={image.altText || 'Product thumbnail'}
className="w-full h-full object-cover"
/>
</button>
))}
</div>
)}
</div>
);
};
export default ProductDetailGallery;

View File

@@ -0,0 +1,166 @@
import React from 'react';
import { Product, ProductVariant } from './ProductDetail.tsx';
import { Button } from '../ui/button';
import {
RiSubtractLine,
RiAddLine,
RiTruckLine,
RiArrowGoBackLine,
RiSecurePaymentLine,
RiLoader4Line,
} from '@remixicon/react';
interface ProductDetailInfoProps {
product: Product;
selectedVariant: ProductVariant | null;
selectedOptions: Record<string, string>;
quantity: number;
setQuantity: (quantity: number) => void;
handleAddToCart: () => void;
onOptionChange: (optionName: string, value: string) => void;
isAddingToCart?: boolean;
}
const ProductDetailInfo: React.FC<ProductDetailInfoProps> = ({
product,
selectedVariant,
selectedOptions,
quantity,
setQuantity,
handleAddToCart,
onOptionChange,
isAddingToCart = false
}) => {
const formatPrice = (price: { amount: string; currencyCode: string }) => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
}).format(parseFloat(price.amount));
};
const price = selectedVariant?.price || product.priceRange.minVariantPrice;
const compareAtPrice = product.compareAtPriceRange?.minVariantPrice;
const hasDiscount = compareAtPrice && parseFloat(compareAtPrice.amount) > parseFloat(price.amount);
return (
<div>
<h1 className="text-4xl font-bold text-gray-900 mb-4 font-heading">
{product.title}
</h1>
{/* Price */}
<div className="flex items-center space-x-4 mb-6">
<span className="text-2xl font-bold text-gray-900">
{formatPrice(price)}
</span>
{hasDiscount && compareAtPrice && (
<>
<span className="text-xl text-gray-500 line-through">
{formatPrice(compareAtPrice)}
</span>
<div className="bg-red-100 text-red-800 text-sm font-semibold px-3 py-1 rounded">
{Math.round(((parseFloat(compareAtPrice.amount) - parseFloat(price.amount)) / parseFloat(compareAtPrice.amount)) * 100)}% OFF
</div>
</>
)}
</div>
{/* Description */}
{product.description && (
<div className="text-gray-600 mb-8 text-lg leading-relaxed">
{product.descriptionHtml ? (
<div dangerouslySetInnerHTML={{ __html: product.descriptionHtml }} />
) : (
<p>{product.description}</p>
)}
</div>
)}
{/* Product Options */}
{product.options
.filter(option => option.name !== 'Title')
.map(option => (
<div key={option.id} className="mb-6">
<label className="block text-sm font-semibold text-gray-700 mb-2">
{option.name}
</label>
<div className="flex flex-wrap gap-2">
{option.values.map(value => (
<Button
key={value}
onClick={() => onOptionChange(option.name, value)}
variant={selectedOptions[option.name] === value ? 'default' : 'outline'}
>
{value}
</Button>
))}
</div>
</div>
))}
{/* Quantity Selector */}
<div className="mb-8">
<label className="block text-sm font-semibold text-gray-700 mb-2">
Quantity
</label>
<div className="flex items-center border border-gray-300 rounded-lg w-32">
<Button
onClick={() => setQuantity(Math.max(1, quantity - 1))}
variant="ghost"
size="icon-sm"
disabled={quantity <= 1}
>
<RiSubtractLine size={16} />
</Button>
<span className="flex-1 text-center font-semibold text-sm">{quantity}</span>
<Button
onClick={() => setQuantity(quantity + 1)}
variant="ghost"
size="icon-sm"
>
<RiAddLine size={16} />
</Button>
</div>
</div>
{/* Add to Cart Button */}
<Button
onClick={handleAddToCart}
disabled={!selectedVariant?.availableForSale || isAddingToCart}
size="lg"
className="w-full py-4 text-lg"
>
{isAddingToCart ? (
<span className="flex items-center justify-center gap-2">
<RiLoader4Line className="animate-spin" />
Adding...
</span>
) : selectedVariant?.availableForSale ? (
'Add to Cart'
) : (
'Out of Stock'
)}
</Button>
{/* Additional Info */}
<div className="mt-8 pt-8 border-t border-gray-200">
<div className="space-y-3 text-sm text-gray-600">
<div className="flex items-center space-x-2">
<RiTruckLine size={16} />
<span>Free shipping on orders over $100</span>
</div>
<div className="flex items-center space-x-2">
<RiArrowGoBackLine size={16} />
<span>30-day return policy</span>
</div>
<div className="flex items-center space-x-2">
<RiSecurePaymentLine size={16} />
<span>Secure payment</span>
</div>
</div>
</div>
</div>
);
};
export default ProductDetailInfo;

View File

@@ -0,0 +1,85 @@
"use client";
import React, { useState, useEffect } from 'react';
import { getProductRecommendations } from '@/hooks/use-shopify-products';
import ProductCard from '../ProductCard';
interface ProductRecommendationsProps {
productId: string;
}
const ProductRecommendations: React.FC<ProductRecommendationsProps> = ({ productId }) => {
const [recommendedProducts, setRecommendedProducts] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const fetchRecommendations = async () => {
if (!productId) return;
try {
setLoading(true);
setError(null);
const recommendations = await getProductRecommendations(productId);
setRecommendedProducts(recommendations);
} catch (err) {
console.error('Error fetching product recommendations:', err);
setError(err instanceof Error ? err.message : 'Failed to load recommendations');
} finally {
setLoading(false);
}
};
fetchRecommendations();
}, [productId]);
// Don't show section if we're not loading and have no recommendations
if (!loading && (!recommendedProducts || recommendedProducts.length === 0)) {
return null;
}
return (
<div className="bg-gray-50 py-16">
<div className="container mx-auto px-4">
<h2
className="text-4xl font-bold text-center mb-12 text-gray-900"
style={{ fontFamily: 'Space Grotesk, sans-serif' }}
>
You Might Also Like
</h2>
{loading ? (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
{Array.from({ length: 4 }).map((_, index) => (
<div key={index} className="bg-white rounded-lg shadow-md overflow-hidden animate-pulse">
<div className="aspect-square bg-gray-200"></div>
<div className="p-6">
<div className="h-6 bg-gray-200 rounded mb-2"></div>
<div className="h-4 bg-gray-200 rounded mb-4"></div>
<div className="h-8 bg-gray-200 rounded mb-4"></div>
<div className="h-12 bg-gray-200 rounded"></div>
</div>
</div>
))}
</div>
) : error ? (
<div className="text-center py-8">
<p className="text-gray-500">Recommendations could not be loaded</p>
</div>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
{recommendedProducts.slice(0, 4).map((recommendedProduct) => (
<ProductCard
key={recommendedProduct.id}
product={recommendedProduct}
/>
))}
</div>
)}
</div>
</div>
);
};
export default ProductRecommendations;