"use client"; import { useState, MouseEvent, useEffect, useRef } from "react"; import { Heart } from "lucide-react"; import { toast } from "sonner"; import { Carousel, CarouselContent, CarouselItem, CarouselNext, CarouselPrevious, type CarouselApi, } from "@/components/ui/carousel"; import { Card, CardContent } from "@/components/ui/card"; import { Badge } from "@/components/ui/badge"; import { useToggleFavorite, useIsFavorite } from "@/lib/hooks"; type ProductCardProps = { id: number; name: string; price: number | null; struct_price_text: string; discount?: number | null; discount_text?: string | null; images: string[]; labels?: { text: string; bg_color: string }[]; price_color?: string; height?: number; width?: number; }; export default function ProductCard({ id, name, price, struct_price_text, discount, discount_text, images, labels = [], price_color = "#005bff", height = 360, width = 280, }: ProductCardProps) { const { isFavorite, isLoading: isFavoriteLoading } = useIsFavorite(id); const { mutate: toggleFavorite, isPending } = useToggleFavorite(); const [api, setApi] = useState(); const [current, setCurrent] = useState(0); const autoplayRef = useRef(null); const hasMultipleImages = images.length > 1; useEffect(() => { if (!api) return; setCurrent(api.selectedScrollSnap()); api.on("select", () => { setCurrent(api.selectedScrollSnap()); }); }, [api]); useEffect(() => { if (!api || !hasMultipleImages) return; const startAutoplay = () => { autoplayRef.current = setInterval(() => { if (api.canScrollNext()) { api.scrollNext(); } else { api.scrollTo(0); } }, 3000); }; const stopAutoplay = () => { if (autoplayRef.current) { clearInterval(autoplayRef.current); autoplayRef.current = null; } }; startAutoplay(); return () => stopAutoplay(); }, [api, hasMultipleImages]); const handleFavorite = (e: MouseEvent) => { e.preventDefault(); e.stopPropagation(); toggleFavorite( { productId: id, isFavorite }, { onSuccess: (data) => { toast.success( data.wasAdded ? "Товар добавлен в избранное" : "Товар удален из избранного" ); }, onError: () => { toast.error("Ошибка. Попробуйте снова"); }, } ); }; const handleCardClick = (e: MouseEvent) => { const target = e.target as HTMLElement; if ( target.closest("button") || target.closest('[data-carousel-control="true"]') ) { e.preventDefault(); } }; const handleNavClick = (e: MouseEvent, action: () => void) => { e.preventDefault(); e.stopPropagation(); action(); }; return (
{images.map((image, index) => (
{`${name}
))}
{hasMultipleImages && ( <> handleNavClick(e, () => api?.scrollPrev())} /> handleNavClick(e, () => api?.scrollNext())} /> )}
{/* Favorite button - show skeleton while loading favorites */} {hasMultipleImages && (
{images.map((_, index) => (
)} {labels?.length > 0 && (
{labels.map((label, idx) => ( {label.text} ))}
)}

{struct_price_text}

{name}

); }