move to gitea

This commit is contained in:
Mamadou Sall
2025-08-24 22:41:31 +02:00
commit 032b1d9452
122 changed files with 28723 additions and 0 deletions

View File

@@ -0,0 +1,258 @@
// src/components/product/ProductCard.tsx
'use client';
import { useState } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { WooCommerceProduct } from '@/types/woocommerce';
import { useCartActions } from '@/hooks/useCartSync';import { formatPrice, isOnSale, getDiscountPercentage } from '@/lib/woocommerce';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Eye, ShoppingBag, Heart } from 'lucide-react';
import { cn } from '@/lib/utils';
interface ProductCardProps {
product: WooCommerceProduct;
className?: string;
showQuickView?: boolean;
}
interface ColorOption {
name: string;
hex: string;
}
export default function ProductCard({
product,
className = '',
showQuickView = true
}: ProductCardProps): JSX.Element {
const { addToCart, isInCart } = useCart();
const [isHovered, setIsHovered] = useState(false);
const [selectedColor, setSelectedColor] = useState<string | null>(null);
const [isAddingToCart, setIsAddingToCart] = useState(false);
const primaryImage = product.images?.[0]?.src || '/placeholder-product.jpg';
const secondaryImage = product.images?.[1]?.src || primaryImage;
const discountPercentage = getDiscountPercentage(product);
// Extraire les couleurs des attributs du produit
const colorAttribute = product.attributes?.find(attr =>
attr.name.toLowerCase().includes('couleur') ||
attr.name.toLowerCase().includes('color')
);
const colorOptions: ColorOption[] = colorAttribute?.options.map(color => ({
name: color,
hex: getColorHex(color), // Fonction helper pour obtenir le hex
})) || [];
const handleAddToCart = async (): Promise<void> => {
if (isAddingToCart) return;
setIsAddingToCart(true);
try {
addToCart({
id: product.id,
name: product.name,
price: product.sale_price || product.regular_price,
image: primaryImage,
});
// Simulation d'une petite attente pour l'UX
await new Promise(resolve => setTimeout(resolve, 300));
} finally {
setIsAddingToCart(false);
}
};
return (
<div
className={cn(
"group relative bg-white transition-all duration-300 hover:shadow-lg",
className
)}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
{/* Image Container */}
<div className="relative aspect-[3/4] overflow-hidden bg-gray-100">
<Link href={`/produit/${product.slug}`}>
<Image
src={isHovered && secondaryImage !== primaryImage ? secondaryImage : primaryImage}
alt={product.name}
fill
className="object-cover transition-all duration-500 group-hover:scale-105"
sizes="(max-width: 768px) 50vw, (max-width: 1200px) 33vw, 25vw"
/>
</Link>
{/* Badges */}
<div className="absolute top-4 left-4 flex flex-col gap-2">
{isOnSale(product) && (
<Badge className="bg-red-500 text-white text-xs px-2 py-1">
-{discountPercentage}%
</Badge>
)}
{product.featured && (
<Badge className="bg-black text-white text-xs px-2 py-1">
Nouvelle Collection
</Badge>
)}
</div>
{/* Quick Actions Overlay */}
{showQuickView && (
<div
className={cn(
"absolute inset-0 bg-black/10 flex items-center justify-center transition-opacity duration-300",
isHovered ? "opacity-100" : "opacity-0"
)}
>
<div className="flex gap-2">
<Button
variant="secondary"
size="sm"
className="bg-white hover:bg-gray-100 shadow-md"
asChild
>
<Link href={`/produit/${product.slug}`}>
<Eye className="w-4 h-4 mr-2" />
Aperçu rapide
</Link>
</Button>
</div>
</div>
)}
{/* Wishlist Button */}
<Button
variant="ghost"
size="sm"
className={cn(
"absolute top-4 right-4 w-8 h-8 p-0 bg-white/80 hover:bg-white transition-all duration-300",
isHovered ? "opacity-100 scale-100" : "opacity-0 scale-75"
)}
>
<Heart className="w-4 h-4" />
</Button>
</div>
{/* Product Info */}
<div className="p-4 space-y-3">
<div>
<Link
href={`/produit/${product.slug}`}
className="group"
>
<h3 className="text-sm font-medium text-black group-hover:opacity-70 transition-opacity tracking-wide uppercase">
{product.name}
</h3>
</Link>
{/* Prix */}
<div className="flex items-center gap-2 mt-1">
{isOnSale(product) ? (
<>
<span className="text-base font-medium text-black">
{formatPrice(product.sale_price)}
</span>
<span className="text-sm text-gray-500 line-through">
{formatPrice(product.regular_price)}
</span>
</>
) : (
<span className="text-base font-medium text-black">
{formatPrice(product.price)}
</span>
)}
</div>
</div>
{/* Couleurs disponibles */}
{colorOptions.length > 0 && (
<div className="flex items-center gap-2">
{colorOptions.slice(0, 4).map((color, index) => (
<button
key={index}
onClick={() => setSelectedColor(color.name)}
className={cn(
"w-4 h-4 rounded-full border-2 transition-all duration-200 hover:scale-110",
selectedColor === color.name
? "border-black shadow-md"
: "border-gray-200"
)}
style={{ backgroundColor: color.hex }}
title={color.name}
/>
))}
{colorOptions.length > 4 && (
<span className="text-xs text-gray-500 ml-1">
+{colorOptions.length - 4}
</span>
)}
</div>
)}
{/* Add to Cart Button */}
<Button
onClick={handleAddToCart}
disabled={isAddingToCart || !product.purchasable}
className={cn(
"w-full bg-black text-white hover:bg-gray-800 text-xs uppercase tracking-wide transition-all duration-300",
isInCart(product.id) && "bg-green-600 hover:bg-green-700"
)}
>
{isAddingToCart ? (
"Ajout..."
) : isInCart(product.id) ? (
<>
<ShoppingBag className="w-4 h-4 mr-2" />
Dans le panier
</>
) : (
"Ajouter au panier"
)}
</Button>
</div>
</div>
);
}
// Fonction helper pour obtenir la couleur hex à partir du nom
function getColorHex(colorName: string): string {
const colorMap: { [key: string]: string } = {
'noir': '#000000',
'black': '#000000',
'blanc': '#ffffff',
'white': '#ffffff',
'rouge': '#e74c3c',
'red': '#e74c3c',
'bleu': '#3498db',
'blue': '#3498db',
'vert': '#27ae60',
'green': '#27ae60',
'jaune': '#f1c40f',
'yellow': '#f1c40f',
'orange': '#e67e22',
'violet': '#8e44ad',
'purple': '#8e44ad',
'rose': '#e91e63',
'pink': '#e91e63',
'gris': '#95a5a6',
'gray': '#95a5a6',
'grey': '#95a5a6',
'marron': '#8B4513',
'brown': '#8B4513',
'beige': '#F5F5DC',
'doré': '#FFD700',
'gold': '#FFD700',
'argenté': '#C0C0C0',
'silver': '#C0C0C0',
};
const normalizedName = colorName.toLowerCase().trim();
return colorMap[normalizedName] || '#9CA3AF'; // Couleur par défaut
}

View File

@@ -0,0 +1,354 @@
// src/components/product/ProductFilters.tsx
'use client';
import { useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { Slider } from '@/components/ui/slider';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from '@/components/ui/select';
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from '@/components/ui/accordion';
import { X, Filter } from 'lucide-react';
import { cn } from '@/lib/utils';
interface Category {
id: number;
name: string;
slug: string;
count: number;
}
interface ProductFiltersProps {
categories: Category[];
currentCategory?: string;
currentFilter?: string;
currentSort?: string;
}
interface ColorOption {
name: string;
value: string;
hex: string;
}
interface SizeOption {
name: string;
value: string;
}
const colorOptions: ColorOption[] = [
{ name: 'Noir', value: 'noir', hex: '#000000' },
{ name: 'Blanc', value: 'blanc', hex: '#FFFFFF' },
{ name: 'Rouge', value: 'rouge', hex: '#DC2626' },
{ name: 'Bleu', value: 'bleu', hex: '#2563EB' },
{ name: 'Vert', value: 'vert', hex: '#059669' },
{ name: 'Jaune', value: 'jaune', hex: '#D97706' },
{ name: 'Violet', value: 'violet', hex: '#7C3AED' },
{ name: 'Rose', value: 'rose', hex: '#EC4899' },
];
const sizeOptions: SizeOption[] = [
{ name: 'Standard', value: 'standard' },
{ name: 'Grande taille', value: 'grande' },
{ name: 'Petite taille', value: 'petite' },
{ name: 'Sur mesure', value: 'sur-mesure' },
];
const sortOptions = [
{ label: 'Plus récent', value: 'date-desc' },
{ label: 'Prix croissant', value: 'price-asc' },
{ label: 'Prix décroissant', value: 'price-desc' },
{ label: 'Nom A-Z', value: 'name-asc' },
{ label: 'Nom Z-A', value: 'name-desc' },
];
export default function ProductFilters({
categories,
currentCategory,
currentFilter,
currentSort = 'date-desc'
}: ProductFiltersProps): JSX.Element {
const router = useRouter();
const searchParams = useSearchParams();
const [priceRange, setPriceRange] = useState<number[]>([0, 100000]);
const [selectedColors, setSelectedColors] = useState<string[]>([]);
const [selectedSizes, setSelectedSizes] = useState<string[]>([]);
const [selectedCategories, setSelectedCategories] = useState<string[]>(
currentCategory ? [currentCategory] : []
);
const updateFilters = (newParams: Record<string, string | string[] | null>): void => {
const params = new URLSearchParams(searchParams.toString());
Object.entries(newParams).forEach(([key, value]) => {
if (value === null || value === '' || (Array.isArray(value) && value.length === 0)) {
params.delete(key);
} else if (Array.isArray(value)) {
params.delete(key);
value.forEach(v => params.append(key, v));
} else {
params.set(key, value);
}
});
// Reset page to 1 when filters change
params.set('page', '1');
router.push(`/boutique?${params.toString()}`);
};
const handleSortChange = (value: string): void => {
updateFilters({ sort: value });
};
const handleCategoryChange = (categorySlug: string, checked: boolean): void => {
const newCategories = checked
? [...selectedCategories, categorySlug]
: selectedCategories.filter(c => c !== categorySlug);
setSelectedCategories(newCategories);
updateFilters({ category: newCategories.length > 0 ? newCategories : null });
};
const handleColorChange = (colorValue: string, checked: boolean): void => {
const newColors = checked
? [...selectedColors, colorValue]
: selectedColors.filter(c => c !== colorValue);
setSelectedColors(newColors);
updateFilters({ color: newColors.length > 0 ? newColors : null });
};
const handleSizeChange = (sizeValue: string, checked: boolean): void => {
const newSizes = checked
? [...selectedSizes, sizeValue]
: selectedSizes.filter(s => s !== sizeValue);
setSelectedSizes(newSizes);
updateFilters({ size: newSizes.length > 0 ? newSizes : null });
};
const clearAllFilters = (): void => {
setPriceRange([0, 100000]);
setSelectedColors([]);
setSelectedSizes([]);
setSelectedCategories([]);
router.push('/boutique');
};
const hasActiveFilters =
selectedCategories.length > 0 ||
selectedColors.length > 0 ||
selectedSizes.length > 0 ||
priceRange[0] > 0 ||
priceRange[1] < 100000;
return (
<div className="space-y-6">
{/* Header */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Filter className="w-4 h-4" />
<h2 className="font-medium text-sm uppercase tracking-wide">Filtres</h2>
</div>
{hasActiveFilters && (
<Button
variant="ghost"
size="sm"
onClick={clearAllFilters}
className="text-xs text-gray-500 hover:text-black p-0 h-auto"
>
<X className="w-3 h-3 mr-1" />
Effacer
</Button>
)}
</div>
{/* Sort */}
<div className="space-y-3">
<Label className="text-xs font-medium uppercase tracking-wide">
Trier par
</Label>
<Select value={currentSort} onValueChange={handleSortChange}>
<SelectTrigger className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
{sortOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Filters Accordion */}
<Accordion type="multiple" defaultValue={['categories', 'colors', 'sizes', 'price']}>
{/* Categories */}
{categories.length > 0 && (
<AccordionItem value="categories">
<AccordionTrigger className="text-xs font-medium uppercase tracking-wide py-3">
Catégories
</AccordionTrigger>
<AccordionContent className="space-y-3 pt-1">
{categories.map((category) => (
<div key={category.id} className="flex items-center space-x-2">
<Checkbox
id={`category-${category.id}`}
checked={selectedCategories.includes(category.slug)}
onCheckedChange={(checked) =>
handleCategoryChange(category.slug, checked as boolean)
}
/>
<Label
htmlFor={`category-${category.id}`}
className="text-sm cursor-pointer flex-1 flex justify-between"
>
<span>{category.name}</span>
<span className="text-gray-400">({category.count})</span>
</Label>
</div>
))}
</AccordionContent>
</AccordionItem>
)}
{/* Colors */}
<AccordionItem value="colors">
<AccordionTrigger className="text-xs font-medium uppercase tracking-wide py-3">
Couleurs
</AccordionTrigger>
<AccordionContent className="space-y-3 pt-1">
<div className="grid grid-cols-4 gap-3">
{colorOptions.map((color) => (
<div key={color.value} className="flex flex-col items-center space-y-1">
<button
onClick={() => handleColorChange(color.value, !selectedColors.includes(color.value))}
className={cn(
"w-8 h-8 rounded-full border-2 transition-all duration-200",
selectedColors.includes(color.value)
? "border-black scale-110 shadow-md"
: "border-gray-200 hover:scale-105",
color.hex === '#FFFFFF' && "border-gray-300"
)}
style={{ backgroundColor: color.hex }}
title={color.name}
/>
<span className="text-xs text-gray-600">{color.name}</span>
</div>
))}
</div>
</AccordionContent>
</AccordionItem>
{/* Sizes */}
<AccordionItem value="sizes">
<AccordionTrigger className="text-xs font-medium uppercase tracking-wide py-3">
Tailles
</AccordionTrigger>
<AccordionContent className="space-y-3 pt-1">
{sizeOptions.map((size) => (
<div key={size.value} className="flex items-center space-x-2">
<Checkbox
id={`size-${size.value}`}
checked={selectedSizes.includes(size.value)}
onCheckedChange={(checked) =>
handleSizeChange(size.value, checked as boolean)
}
/>
<Label
htmlFor={`size-${size.value}`}
className="text-sm cursor-pointer"
>
{size.name}
</Label>
</div>
))}
</AccordionContent>
</AccordionItem>
{/* Price Range */}
<AccordionItem value="price">
<AccordionTrigger className="text-xs font-medium uppercase tracking-wide py-3">
Prix (MRU)
</AccordionTrigger>
<AccordionContent className="space-y-4 pt-1">
<Slider
value={priceRange}
onValueChange={setPriceRange}
max={100000}
min={0}
step={1000}
className="w-full"
/>
<div className="flex justify-between text-sm text-gray-600">
<span>{priceRange[0].toLocaleString()} MRU</span>
<span>{priceRange[1].toLocaleString()} MRU</span>
</div>
<Button
variant="outline"
size="sm"
className="w-full"
onClick={() => updateFilters({
price_min: priceRange[0].toString(),
price_max: priceRange[1].toString()
})}
>
Appliquer
</Button>
</AccordionContent>
</AccordionItem>
</Accordion>
{/* Quick Filters */}
<div className="pt-4 border-t border-gray-200 space-y-3">
<Label className="text-xs font-medium uppercase tracking-wide">
Filtres rapides
</Label>
<div className="space-y-2">
<Button
variant={currentFilter === 'sale' ? 'default' : 'outline'}
size="sm"
className="w-full justify-start text-xs"
onClick={() => updateFilters({ filter: currentFilter === 'sale' ? null : 'sale' })}
>
En promotion
</Button>
<Button
variant={currentFilter === 'featured' ? 'default' : 'outline'}
size="sm"
className="w-full justify-start text-xs"
onClick={() => updateFilters({ filter: currentFilter === 'featured' ? null : 'featured' })}
>
Produits vedettes
</Button>
<Button
variant={currentFilter === 'new' ? 'default' : 'outline'}
size="sm"
className="w-full justify-start text-xs"
onClick={() => updateFilters({ filter: currentFilter === 'new' ? null : 'new' })}
>
Nouvelles arrivées
</Button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,94 @@
// src/components/product/ProductGrid.tsx
'use client';
import { WooCommerceProduct } from '@/types/woocommerce';
import ProductCard from './ProductCard';
import { cn } from '@/lib/utils';
interface ProductGridProps {
products: WooCommerceProduct[];
currentPage?: number;
hasMore?: boolean;
className?: string;
viewMode?: 'grid' | 'list';
}
export default function ProductGrid({
products,
currentPage = 1,
hasMore = false,
className = '',
viewMode = 'grid'
}: ProductGridProps): JSX.Element {
if (products.length === 0) {
return (
<div className="text-center py-16">
<div className="max-w-md mx-auto space-y-4">
<div className="w-24 h-24 bg-gray-100 rounded-full mx-auto flex items-center justify-center">
<svg
className="w-12 h-12 text-gray-400"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={1.5}
d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"
/>
</svg>
</div>
<h3 className="text-lg font-medium text-gray-900">
Aucun produit trouvé
</h3>
<p className="text-gray-600">
Aucun produit ne correspond à vos critères de recherche.
Essayez de modifier vos filtres.
</p>
</div>
</div>
);
}
return (
<div className={cn('space-y-8', className)}>
{/* Grid de produits */}
<div
className={cn(
'grid gap-6',
viewMode === 'grid'
? 'grid-cols-2 md:grid-cols-3 lg:grid-cols-4'
: 'grid-cols-1 md:grid-cols-2 gap-8'
)}
>
{products.map((product, index) => (
<div
key={product.id}
className="animate-fade-in-up"
style={{
animationDelay: `${index * 100}ms`,
animationFillMode: 'both'
}}
>
<ProductCard
product={product}
className={cn(
viewMode === 'list' && 'flex-row h-48'
)}
/>
</div>
))}
</div>
{/* Informations de pagination */}
{currentPage > 1 && (
<div className="text-center text-sm text-gray-600">
Page {currentPage} {products.length} produits affichés
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,215 @@
// src/components/product/ProductImageGallery.tsx
'use client';
import { useState } from 'react';
import Image from 'next/image';
import { WooCommerceImage } from '@/types/woocommerce';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { ChevronLeft, ChevronRight, Expand, Heart } from 'lucide-react';
import { cn } from '@/lib/utils';
import {
Dialog,
DialogContent,
DialogTrigger,
} from '@/components/ui/dialog';
interface ProductImageGalleryProps {
images: WooCommerceImage[];
productName: string;
isOnSale?: boolean;
discountPercentage?: number;
isFeatured?: boolean;
}
export default function ProductImageGallery({
images,
productName,
isOnSale = false,
discountPercentage = 0,
isFeatured = false,
}: ProductImageGalleryProps): JSX.Element {
const [currentImageIndex, setCurrentImageIndex] = useState(0);
const [isWishlisted, setIsWishlisted] = useState(false);
const hasMultipleImages = images.length > 1;
const currentImage = images[currentImageIndex] || images[0];
const goToPrevious = (): void => {
setCurrentImageIndex((prev) =>
prev === 0 ? images.length - 1 : prev - 1
);
};
const goToNext = (): void => {
setCurrentImageIndex((prev) =>
prev === images.length - 1 ? 0 : prev + 1
);
};
const goToImage = (index: number): void => {
setCurrentImageIndex(index);
};
const toggleWishlist = (): void => {
setIsWishlisted(!isWishlisted);
};
if (!currentImage) {
return (
<div className="aspect-[3/4] bg-gray-200 rounded-lg flex items-center justify-center">
<span className="text-gray-400">Aucune image disponible</span>
</div>
);
}
return (
<div className="space-y-4">
{/* Main Image */}
<div className="relative group">
<div className="aspect-[3/4] relative overflow-hidden rounded-lg bg-gray-100">
<Image
src={currentImage.src}
alt={currentImage.alt || productName}
fill
className="object-cover transition-transform duration-700 group-hover:scale-105"
sizes="(max-width: 768px) 100vw, 50vw"
priority
/>
{/* Badges */}
<div className="absolute top-4 left-4 flex flex-col gap-2 z-10">
{isOnSale && discountPercentage > 0 && (
<Badge className="bg-red-500 text-white">
-{discountPercentage}%
</Badge>
)}
{isFeatured && (
<Badge className="bg-black text-white">
Nouveauté
</Badge>
)}
</div>
{/* Wishlist Button */}
<Button
variant="ghost"
size="sm"
onClick={toggleWishlist}
className={cn(
"absolute top-4 right-4 w-10 h-10 p-0 rounded-full z-10 transition-all duration-300",
"bg-white/80 hover:bg-white backdrop-blur-sm",
isWishlisted && "bg-red-50 text-red-500 hover:bg-red-100"
)}
>
<Heart
className={cn(
"w-5 h-5 transition-all duration-300",
isWishlisted && "fill-current"
)}
/>
</Button>
{/* Navigation Arrows */}
{hasMultipleImages && (
<>
<Button
variant="ghost"
size="sm"
onClick={goToPrevious}
className="absolute left-4 top-1/2 -translate-y-1/2 w-10 h-10 p-0 rounded-full bg-white/80 hover:bg-white backdrop-blur-sm opacity-0 group-hover:opacity-100 transition-opacity duration-300 z-10"
>
<ChevronLeft className="w-5 h-5" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={goToNext}
className="absolute right-4 top-1/2 -translate-y-1/2 w-10 h-10 p-0 rounded-full bg-white/80 hover:bg-white backdrop-blur-sm opacity-0 group-hover:opacity-100 transition-opacity duration-300 z-10"
>
<ChevronRight className="w-5 h-5" />
</Button>
</>
)}
{/* Expand Button */}
<Dialog>
<DialogTrigger asChild>
<Button
variant="ghost"
size="sm"
className="absolute bottom-4 right-4 w-10 h-10 p-0 rounded-full bg-white/80 hover:bg-white backdrop-blur-sm opacity-0 group-hover:opacity-100 transition-opacity duration-300 z-10"
>
<Expand className="w-5 h-5" />
</Button>
</DialogTrigger>
<DialogContent className="max-w-4xl w-full h-full max-h-[90vh] p-0">
<div className="relative w-full h-full">
<Image
src={currentImage.src}
alt={currentImage.alt || productName}
fill
className="object-contain"
sizes="90vw"
/>
</div>
</DialogContent>
</Dialog>
{/* Image Counter */}
{hasMultipleImages && (
<div className="absolute bottom-4 left-4 bg-black/60 text-white px-3 py-1 rounded-full text-sm backdrop-blur-sm">
{currentImageIndex + 1} / {images.length}
</div>
)}
</div>
</div>
{/* Thumbnail Navigation */}
{hasMultipleImages && (
<div className="flex gap-3 overflow-x-auto pb-2">
{images.map((image, index) => (
<button
key={image.id}
onClick={() => goToImage(index)}
className={cn(
"relative flex-shrink-0 w-20 h-20 rounded-lg overflow-hidden border-2 transition-all duration-300",
currentImageIndex === index
? "border-black shadow-md"
: "border-gray-200 hover:border-gray-400"
)}
>
<Image
src={image.src}
alt={image.alt || `${productName} - Image ${index + 1}`}
fill
className="object-cover"
sizes="80px"
/>
</button>
))}
</div>
)}
{/* Mobile Dots Indicator */}
{hasMultipleImages && (
<div className="flex justify-center gap-2 md:hidden">
{images.map((_, index) => (
<button
key={index}
onClick={() => goToImage(index)}
className={cn(
"w-2 h-2 rounded-full transition-all duration-300",
currentImageIndex === index
? "bg-black"
: "bg-gray-300"
)}
/>
))}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,385 @@
// src/components/product/ProductInfo.tsx
'use client';
import { useState } from 'react';
import { WooCommerceProduct } from '@/types/woocommerce';
import { useCartActions } from '@/hooks/useCartSync';import { formatPrice, isOnSale, getDiscountPercentage } from '@/lib/woocommerce';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
import {
ShoppingBag,
Heart,
Share2,
Truck,
Shield,
RotateCcw,
Star,
Plus,
Minus
} from 'lucide-react';
import { cn } from '@/lib/utils';
interface ProductInfoProps {
product: WooCommerceProduct;
}
interface ColorOption {
name: string;
value: string;
hex: string;
}
interface SizeOption {
name: string;
value: string;
available: boolean;
}
export default function ProductInfo({ product }: ProductInfoProps): JSX.Element {
const { addToCart, isInCart, getItemQuantity } = useCart();
const [selectedColor, setSelectedColor] = useState<string>('');
const [selectedSize, setSelectedSize] = useState<string>('');
const [quantity, setQuantity] = useState(1);
const [isAddingToCart, setIsAddingToCart] = useState(false);
const [isWishlisted, setIsWishlisted] = useState(false);
const discountPercentage = getDiscountPercentage(product);
const productInCart = isInCart(product.id);
const cartQuantity = getItemQuantity(product.id);
// Extraire les couleurs des attributs du produit
const colorAttribute = product.attributes?.find(attr =>
attr.name.toLowerCase().includes('couleur') ||
attr.name.toLowerCase().includes('color')
);
const sizeAttribute = product.attributes?.find(attr =>
attr.name.toLowerCase().includes('taille') ||
attr.name.toLowerCase().includes('size')
);
const colorOptions: ColorOption[] = colorAttribute?.options.map(color => ({
name: color,
value: color.toLowerCase(),
hex: getColorHex(color),
})) || [];
const sizeOptions: SizeOption[] = sizeAttribute?.options.map(size => ({
name: size,
value: size.toLowerCase(),
available: true, // Vous pouvez ajouter la logique de disponibilité ici
})) || [];
const handleAddToCart = async (): Promise<void> => {
if (isAddingToCart) return;
setIsAddingToCart(true);
try {
addToCart({
id: product.id,
name: product.name,
price: product.sale_price || product.regular_price,
image: product.images[0]?.src || '/placeholder-product.jpg',
}, quantity);
// Simulation d'une petite attente pour l'UX
await new Promise(resolve => setTimeout(resolve, 500));
} finally {
setIsAddingToCart(false);
}
};
const increaseQuantity = (): void => {
setQuantity(prev => prev + 1);
};
const decreaseQuantity = (): void => {
setQuantity(prev => Math.max(1, prev - 1));
};
const toggleWishlist = (): void => {
setIsWishlisted(!isWishlisted);
};
const shareProduct = (): void => {
if (navigator.share) {
navigator.share({
title: product.name,
text: product.short_description,
url: window.location.href,
});
} else {
// Fallback: copier l'URL dans le presse-papiers
navigator.clipboard.writeText(window.location.href);
}
};
return (
<div className="space-y-8">
{/* Product Header */}
<div className="space-y-4">
{/* Categories */}
{product.categories.length > 0 && (
<div className="flex flex-wrap gap-2">
{product.categories.map((category) => (
<Badge key={category.id} variant="outline" className="text-xs">
{category.name}
</Badge>
))}
</div>
)}
{/* Title */}
<h1 className="text-3xl md:text-4xl font-light tracking-wide text-black">
{product.name}
</h1>
{/* Ratings */}
{product.rating_count > 0 && (
<div className="flex items-center gap-2">
<div className="flex items-center">
{[...Array(5)].map((_, i) => (
<Star
key={i}
className={cn(
"w-4 h-4",
i < Math.floor(parseFloat(product.average_rating))
? "fill-yellow-400 text-yellow-400"
: "text-gray-300"
)}
/>
))}
</div>
<span className="text-sm text-gray-600">
{product.average_rating} ({product.rating_count} avis)
</span>
</div>
)}
{/* Price */}
<div className="flex items-center gap-4">
{isOnSale(product) ? (
<>
<span className="text-3xl font-medium text-black">
{formatPrice(product.sale_price)}
</span>
<span className="text-xl text-gray-500 line-through">
{formatPrice(product.regular_price)}
</span>
{discountPercentage > 0 && (
<Badge className="bg-red-500 text-white">
-{discountPercentage}%
</Badge>
)}
</>
) : (
<span className="text-3xl font-medium text-black">
{formatPrice(product.price)}
</span>
)}
</div>
{/* Short Description */}
{product.short_description && (
<div
className="text-gray-600 leading-relaxed"
dangerouslySetInnerHTML={{ __html: product.short_description }}
/>
)}
</div>
<Separator />
{/* Product Options */}
<div className="space-y-6">
{/* Colors */}
{colorOptions.length > 0 && (
<div className="space-y-3">
<Label className="text-sm font-medium">
Couleur: {selectedColor && <span className="font-normal">{selectedColor}</span>}
</Label>
<div className="flex flex-wrap gap-3">
{colorOptions.map((color) => (
<button
key={color.value}
onClick={() => setSelectedColor(color.name)}
className={cn(
"w-8 h-8 rounded-full border-2 transition-all duration-200 hover:scale-110",
selectedColor === color.name
? "border-black shadow-md scale-110"
: "border-gray-200"
)}
style={{ backgroundColor: color.hex }}
title={color.name}
/>
))}
</div>
</div>
)}
{/* Sizes */}
{sizeOptions.length > 0 && (
<div className="space-y-3">
<Label className="text-sm font-medium">Taille</Label>
<Select value={selectedSize} onValueChange={setSelectedSize}>
<SelectTrigger>
<SelectValue placeholder="Choisir une taille" />
</SelectTrigger>
<SelectContent>
{sizeOptions.map((size) => (
<SelectItem
key={size.value}
value={size.value}
disabled={!size.available}
>
{size.name} {!size.available && '(Rupture de stock)'}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
{/* Quantity */}
<div className="space-y-3">
<Label className="text-sm font-medium">Quantité</Label>
<div className="flex items-center gap-4">
<div className="flex items-center border border-gray-300 rounded-lg">
<Button
variant="ghost"
size="sm"
onClick={decreaseQuantity}
disabled={quantity <= 1}
className="px-3 h-10 hover:bg-gray-100"
>
<Minus className="w-4 h-4" />
</Button>
<span className="px-4 py-2 min-w-[3rem] text-center">{quantity}</span>
<Button
variant="ghost"
size="sm"
onClick={increaseQuantity}
className="px-3 h-10 hover:bg-gray-100"
>
<Plus className="w-4 h-4" />
</Button>
</div>
{cartQuantity > 0 && (
<span className="text-sm text-gray-600">
{cartQuantity} déjà dans le panier
</span>
)}
</div>
</div>
</div>
<Separator />
{/* Action Buttons */}
<div className="space-y-4">
<Button
onClick={handleAddToCart}
disabled={isAddingToCart || !product.purchasable || product.stock_status === 'outofstock'}
className="w-full bg-black text-white hover:bg-gray-800 py-4 text-base uppercase tracking-wide transition-all duration-300"
size="lg"
>
{isAddingToCart ? (
<div className="flex items-center gap-2">
<div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
Ajout en cours...
</div>
) : product.stock_status === 'outofstock' ? (
'Rupture de stock'
) : productInCart ? (
<>
<ShoppingBag className="w-5 h-5 mr-2" />
Ajouter encore ({cartQuantity} dans le panier)
</>
) : (
<>
<ShoppingBag className="w-5 h-5 mr-2" />
Ajouter au panier
</>
)}
</Button>
<div className="flex gap-3">
<Button
variant="outline"
onClick={toggleWishlist}
className={cn(
"flex-1 transition-all duration-300",
isWishlisted && "border-red-500 text-red-500 hover:bg-red-50"
)}
>
<Heart className={cn("w-5 h-5 mr-2", isWishlisted && "fill-current")} />
{isWishlisted ? 'Retiré des favoris' : 'Ajouter aux favoris'}
</Button>
<Button variant="outline" onClick={shareProduct}>
<Share2 className="w-5 h-5 mr-2" />
Partager
</Button>
</div>
</div>
<Separator />
{/* Product Features */}
<div className="space-y-4">
<div className="flex items-center gap-3 text-sm">
<Truck className="w-5 h-5 text-gray-600" />
<span>Livraison gratuite à partir de 50.000 MRU</span>
</div>
<div className="flex items-center gap-3 text-sm">
<Shield className="w-5 h-5 text-gray-600" />
<span>Garantie qualité - Retour sous 30 jours</span>
</div>
<div className="flex items-center gap-3 text-sm">
<RotateCcw className="w-5 h-5 text-gray-600" />
<span>Échange gratuit en magasin</span>
</div>
</div>
</div>
);
}
// Helper function pour les couleurs
function getColorHex(colorName: string): string {
const colorMap: { [key: string]: string } = {
'noir': '#000000',
'blanc': '#ffffff',
'rouge': '#dc2626',
'bleu': '#2563eb',
'vert': '#059669',
'jaune': '#d97706',
'violet': '#7c3aed',
'rose': '#ec4899',
'gris': '#6b7280',
'marron': '#92400e',
'beige': '#d6d3d1',
'doré': '#f59e0b',
'argenté': '#9ca3af',
};
return colorMap[colorName.toLowerCase()] || '#9ca3af';
}
function Label({ children, className = '' }: { children: React.ReactNode; className?: string }): JSX.Element {
return (
<label className={cn('block text-sm font-medium text-gray-900', className)}>
{children}
</label>
);
}

View File

@@ -0,0 +1,153 @@
// src/components/product/ProductTabs.tsx
'use client';
import { WooCommerceProduct } from '@/types/woocommerce';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import {
Star,
Truck,
RotateCcw,
Shield
} from 'lucide-react';
interface ProductTabsProps {
product: WooCommerceProduct;
}
export default function ProductTabs({ product }: ProductTabsProps) {
const hasDescription = product.description && product.description.trim() !== '';
const hasAttributes = product.attributes && product.attributes.length > 0;
return (
<div className="w-full">
<Tabs defaultValue="description" className="w-full">
<TabsList className="grid w-full grid-cols-3">
<TabsTrigger value="description">Description</TabsTrigger>
<TabsTrigger value="specifications">Caractéristiques</TabsTrigger>
<TabsTrigger value="shipping">Livraison</TabsTrigger>
</TabsList>
<TabsContent value="description" className="mt-6">
<Card>
<CardContent className="p-6">
{hasDescription ? (
<div
className="prose prose-gray max-w-none"
dangerouslySetInnerHTML={{ __html: product.description }}
/>
) : (
<div className="text-center py-8 text-gray-500">
<p>Aucune description disponible pour ce produit.</p>
</div>
)}
</CardContent>
</Card>
</TabsContent>
<TabsContent value="specifications" className="mt-6">
<Card>
<CardContent className="p-6">
<h3 className="text-lg font-medium mb-6">Caractéristiques techniques</h3>
<div className="space-y-6">
<div>
<h4 className="font-medium text-sm mb-3 text-gray-900">Informations générales</h4>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="flex justify-between py-2 border-b border-gray-100">
<span className="text-sm text-gray-600">SKU</span>
<span className="text-sm font-medium">{product.sku || 'N/A'}</span>
</div>
<div className="flex justify-between py-2 border-b border-gray-100">
<span className="text-sm text-gray-600">Stock</span>
<Badge
variant={product.stock_status === 'instock' ? 'secondary' : 'destructive'}
className="text-xs"
>
{product.stock_status === 'instock' ? 'En stock' : 'Rupture de stock'}
</Badge>
</div>
</div>
</div>
{hasAttributes && (
<div>
<h4 className="font-medium text-sm mb-3 text-gray-900">Attributs</h4>
<div className="space-y-3">
{product.attributes.map((attribute) => (
<div key={attribute.id} className="flex justify-between py-2 border-b border-gray-100">
<span className="text-sm text-gray-600">{attribute.name}</span>
<span className="text-sm font-medium">
{attribute.options.join(', ')}
</span>
</div>
))}
</div>
</div>
)}
</div>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="shipping" className="mt-6">
<Card>
<CardContent className="p-6">
<h3 className="text-lg font-medium mb-6">Livraison et retours</h3>
<div className="space-y-8">
<div>
<h4 className="font-medium text-sm mb-4 flex items-center gap-2">
<Truck className="w-5 h-5" />
Options de livraison
</h4>
<div className="space-y-4">
<div className="flex justify-between items-center p-4 border border-gray-200 rounded-lg">
<div>
<h5 className="font-medium text-sm">Livraison standard</h5>
<p className="text-xs text-gray-600">3-5 jours ouvrés</p>
</div>
<div className="text-right">
<p className="font-medium">5.000 MRU</p>
<p className="text-xs text-gray-600">Gratuite dès 50.000 MRU</p>
</div>
</div>
</div>
</div>
<div>
<h4 className="font-medium text-sm mb-4 flex items-center gap-2">
<RotateCcw className="w-5 h-5" />
Retours et échanges
</h4>
<div className="space-y-3 text-sm">
<p> <strong>30 jours</strong> pour retourner votre article</p>
<p> Retour <strong>gratuit</strong> en magasin ou par courrier</p>
<p> Article en <strong>parfait état</strong> avec étiquettes</p>
</div>
</div>
<div>
<h4 className="font-medium text-sm mb-4 flex items-center gap-2">
<Shield className="w-5 h-5" />
Garantie qualité
</h4>
<div className="space-y-3 text-sm">
<p> Garantie <strong>2 ans</strong> contre les défauts de fabrication</p>
<p> Service client dédié pour toute réclamation</p>
<p> Engagement qualité artisanale mauritanienne</p>
</div>
</div>
</div>
</CardContent>
</Card>
</TabsContent>
</Tabs>
</div>
);
}

View File

@@ -0,0 +1,154 @@
// src/components/product/RelatedProducts.tsx
'use client';
import { WooCommerceProduct } from '@/types/woocommerce';
import ProductCard from './ProductCard';
import { Button } from '@/components/ui/button';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { useRef, useState } from 'react';
import { cn } from '@/lib/utils';
interface RelatedProductsProps {
products: WooCommerceProduct[];
title?: string;
className?: string;
}
export default function RelatedProducts({
products,
title = "Produits similaires",
className = ''
}: RelatedProductsProps): JSX.Element {
const scrollContainerRef = useRef<HTMLDivElement>(null);
const [canScrollLeft, setCanScrollLeft] = useState(false);
const [canScrollRight, setCanScrollRight] = useState(true);
const checkScrollButtons = (): void => {
if (scrollContainerRef.current) {
const { scrollLeft, scrollWidth, clientWidth } = scrollContainerRef.current;
setCanScrollLeft(scrollLeft > 0);
setCanScrollRight(scrollLeft < scrollWidth - clientWidth - 1);
}
};
const scrollLeft = (): void => {
if (scrollContainerRef.current) {
scrollContainerRef.current.scrollBy({
left: -320, // Largeur d'une carte + gap
behavior: 'smooth'
});
}
};
const scrollRight = (): void => {
if (scrollContainerRef.current) {
scrollContainerRef.current.scrollBy({
left: 320, // Largeur d'une carte + gap
behavior: 'smooth'
});
}
};
if (products.length === 0) {
return <></>;
}
return (
<section className={cn('space-y-8', className)}>
{/* Header */}
<div className="flex items-center justify-between">
<h2 className="text-2xl md:text-3xl font-light tracking-wide">
{title}
</h2>
{/* Navigation Buttons - Desktop */}
<div className="hidden md:flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={scrollLeft}
disabled={!canScrollLeft}
className="p-2 h-9 w-9"
>
<ChevronLeft className="w-4 h-4" />
</Button>
<Button
variant="outline"
size="sm"
onClick={scrollRight}
disabled={!canScrollRight}
className="p-2 h-9 w-9"
>
<ChevronRight className="w-4 h-4" />
</Button>
</div>
</div>
{/* Products Scroll Container */}
<div className="relative">
<div
ref={scrollContainerRef}
className="flex gap-6 overflow-x-auto hide-scrollbar pb-4"
onScroll={checkScrollButtons}
style={{ scrollSnapType: 'x mandatory' }}
>
{products.map((product, index) => (
<div
key={product.id}
className="flex-none w-72 md:w-80"
style={{ scrollSnapAlign: 'start' }}
>
<ProductCard
product={product}
className="h-full animate-fade-in-up"
style={{
animationDelay: `${index * 100}ms`,
animationFillMode: 'both'
}}
/>
</div>
))}
</div>
{/* Gradient Overlays */}
<div className="absolute left-0 top-0 bottom-4 w-8 bg-gradient-to-r from-gray-50 to-transparent pointer-events-none" />
<div className="absolute right-0 top-0 bottom-4 w-8 bg-gradient-to-l from-gray-50 to-transparent pointer-events-none" />
</div>
{/* Mobile Navigation Dots */}
<div className="flex justify-center gap-2 md:hidden">
{products.map((_, index) => (
<button
key={index}
className={cn(
"w-2 h-2 rounded-full transition-all duration-300",
index === 0 ? "bg-black" : "bg-gray-300" // En production, calculer l'index actuel
)}
onClick={() => {
if (scrollContainerRef.current) {
scrollContainerRef.current.scrollTo({
left: index * 320,
behavior: 'smooth'
});
}
}}
/>
))}
</div>
{/* Alternative: Grid Layout for smaller screens */}
<div className="md:hidden">
<div className="grid grid-cols-2 gap-4 mt-8">
{products.slice(0, 4).map((product) => (
<ProductCard
key={product.id}
product={product}
className="w-full"
/>
))}
</div>
</div>
</section>
);
}

View File

@@ -0,0 +1,181 @@
// src/app/produit/[slug]/page.tsx
import { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { WooCommerceService, formatPrice, isOnSale, getDiscountPercentage } from '@/lib/woocommerce';
import ProductImageGallery from '@/components/product/ProductImageGallery';
import ProductInfo from '@/components/product/ProductInfo';
import RelatedProducts from '@/components/product/RelatedProducts';
import ProductTabs from '@/components/product/ProductTabs';
import Breadcrumb from '@/components/ui/breadcrumb';
interface ProductPageProps {
params: {
slug: string;
};
}
export async function generateMetadata({ params }: ProductPageProps): Promise<Metadata> {
const response = await WooCommerceService.getProductBySlug(params.slug);
if (!response.success || !response.data) {
return {
title: 'Produit non trouvé',
};
}
const product = response.data;
const discountPercentage = getDiscountPercentage(product);
return {
title: `${product.name} - MELHFA`,
description: product.short_description || product.description,
openGraph: {
title: product.name,
description: product.short_description || product.description,
images: product.images.map(img => ({
url: img.src,
width: 800,
height: 1200,
alt: img.alt || product.name,
})),
type: 'product',
},
twitter: {
card: 'summary_large_image',
title: product.name,
description: product.short_description || product.description,
images: [product.images[0]?.src || ''],
},
alternates: {
canonical: `/produit/${product.slug}`,
},
other: {
'product:price:amount': product.price,
'product:price:currency': 'MRU',
'product:availability': product.stock_status === 'instock' ? 'in stock' : 'out of stock',
'product:condition': 'new',
...(isOnSale(product) && {
'product:sale_price:amount': product.sale_price,
'product:sale_price:currency': 'MRU',
}),
},
};
}
export default async function ProductPage({ params }: ProductPageProps): Promise<JSX.Element> {
// Récupérer le produit
const response = await WooCommerceService.getProductBySlug(params.slug);
if (!response.success || !response.data) {
notFound();
}
const product = response.data;
// Récupérer les produits liés
const relatedProductsResponse = await WooCommerceService.getProducts({
per_page: 4,
exclude: [product.id],
category: product.categories[0]?.slug,
});
const relatedProducts = relatedProductsResponse.data || [];
// Breadcrumb items
const breadcrumbItems = [
{ label: 'Accueil', href: '/' },
{ label: 'Boutique', href: '/boutique' },
...(product.categories.length > 0 ? [{
label: product.categories[0].name,
href: `/boutique?category=${product.categories[0].slug}`
}] : []),
{ label: product.name, href: `/produit/${product.slug}` },
];
return (
<div className="min-h-screen bg-white">
{/* Breadcrumb */}
<div className="max-w-[1400px] mx-auto px-6 pt-20 pb-6">
<Breadcrumb items={breadcrumbItems} />
</div>
{/* Product Details */}
<div className="max-w-[1400px] mx-auto px-6 pb-16">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-12 lg:gap-16">
{/* Image Gallery */}
<div className="space-y-4">
<ProductImageGallery
images={product.images}
productName={product.name}
isOnSale={isOnSale(product)}
discountPercentage={getDiscountPercentage(product)}
isFeatured={product.featured}
/>
</div>
{/* Product Info */}
<div className="space-y-8">
<ProductInfo product={product} />
</div>
</div>
</div>
{/* Product Tabs */}
<div className="max-w-[1400px] mx-auto px-6 pb-16">
<ProductTabs product={product} />
</div>
{/* Related Products */}
{relatedProducts.length > 0 && (
<div className="bg-gray-50 py-16">
<div className="max-w-[1400px] mx-auto px-6">
<RelatedProducts products={relatedProducts} />
</div>
</div>
)}
{/* Structured Data for SEO */}
<script
type="application/ld+json"
dangerouslySetInnerHTML={{
__html: JSON.stringify({
'@context': 'https://schema.org',
'@type': 'Product',
name: product.name,
description: product.description,
image: product.images.map(img => img.src),
sku: product.sku,
mpn: product.sku,
brand: {
'@type': 'Brand',
name: 'MELHFA'
},
offers: {
'@type': 'Offer',
price: product.price,
priceCurrency: 'MRU',
availability: product.stock_status === 'instock'
? 'https://schema.org/InStock'
: 'https://schema.org/OutOfStock',
url: `${process.env.NEXT_PUBLIC_SITE_URL}/produit/${product.slug}`,
seller: {
'@type': 'Organization',
name: 'MELHFA'
},
...(isOnSale(product) && {
priceValidUntil: product.date_on_sale_to || '2024-12-31'
})
},
aggregateRating: product.rating_count > 0 ? {
'@type': 'AggregateRating',
ratingValue: product.average_rating,
reviewCount: product.rating_count
} : undefined,
category: product.categories.map(cat => cat.name).join(', '),
})
}}
/>
</div>
);
}