import React, { useState, useEffect } from "react"; import { useCart } from "@/contexts/CartContext"; import toast from "react-hot-toast"; import CartIcon from "./CartIcon"; interface BestPriceCardProps { bestOfferType: string; title: string; description: string; price: string; delivery: string; stock: string; offer?: any; // Добавляем полный объект предложения для корзины } const BestPriceCard: React.FC = ({ bestOfferType, title, description, price, delivery, stock, offer }) => { const { addItem } = useCart(); // Парсим stock в число, если возможно const parsedStock = parseInt(stock.replace(/[^\d]/g, ""), 10); const maxCount = isNaN(parsedStock) ? undefined : parsedStock; const [count, setCount] = useState(1); const [inputValue, setInputValue] = useState("1"); useEffect(() => { setInputValue(count.toString()); }, [count]); const handleMinus = () => setCount(prev => Math.max(1, prev - 1)); const handlePlus = () => { if (maxCount !== undefined) { setCount(prev => (prev < maxCount ? prev + 1 : prev)); } else { setCount(prev => prev + 1); } }; const handleInput = (e: React.ChangeEvent) => { const val = e.target.value; setInputValue(val); if (val === "") { // Не обновляем count, пока не будет blur return; } let value = parseInt(val, 10); if (isNaN(value) || value < 1) value = 1; if (maxCount !== undefined && value > maxCount) { toast.error(`Максимум ${maxCount} шт.`); return; } setCount(value); }; const handleInputBlur = () => { if (inputValue === "") { setInputValue("1"); setCount(1); } }; // Функция для парсинга цены из строки const parsePrice = (priceStr: string): number => { const cleanPrice = priceStr.replace(/[^\d.,]/g, '').replace(',', '.'); return parseFloat(cleanPrice) || 0; }; // Обработчик добавления в корзину const handleAddToCart = async (e: React.MouseEvent) => { e.preventDefault(); e.stopPropagation(); if (!offer) { toast.error('Информация о товаре недоступна'); return; } const numericPrice = parsePrice(price); if (numericPrice <= 0) { toast.error('Цена товара не найдена'); return; } try { const result = await addItem({ productId: offer.productId, offerKey: offer.offerKey, name: description, description: `${offer.brand} ${offer.articleNumber} - ${description}`, brand: offer.brand, article: offer.articleNumber, price: numericPrice, currency: offer.currency || 'RUB', quantity: count, stock: maxCount, // передаем информацию о наличии deliveryTime: delivery, warehouse: offer.warehouse || 'Склад', supplier: offer.supplier || (offer.isExternal ? 'AutoEuro' : 'Protek'), isExternal: offer.isExternal || false, image: offer.image, }); if (result.success) { // Показываем тоастер об успешном добавлении toast.success(
Товар добавлен в корзину!
{`${offer.brand} ${offer.articleNumber} (${count} шт.)`}
, { duration: 3000, icon: , } ); } else { // Показываем ошибку toast.error(result.error || 'Ошибка при добавлении товара в корзину'); } } catch (error) { console.error('Ошибка добавления в корзину:', error); toast.error('Ошибка добавления товара в корзину'); } }; return (

{bestOfferType}

{title}

{description}
{price}
Срок
{delivery}
Наличие
{stock}
); }; export default BestPriceCard;