'use client'; import { useCart } from "@/components/context/cartcontext"; import Image from "next/image"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { useState, useEffect, useRef } from "react"; import { Trash2, ShoppingBag, ChevronLeft, ShieldCheck, Truck, CreditCard } from "lucide-react"; import NotLogin from "@/components/Notlogin"; import { getCartApi, addToCartApi, clearServerCartApi } from "@/public/src/services/cart/api"; import CartControls from "@/components/CartControls"; export default function CartPage() { const { cart, clearCart, } = useCart(); const router = useRouter(); const [showNotLogin, setShowNotLogin] = useState(false); // --- استیت‌های مربوط به دریافت اطلاعات سرور --- const [isLoggedIn, setIsLoggedIn] = useState(false); const [serverCartItems, setServerCartItems] = useState([]); const [serverSummary, setServerSummary] = useState(null); const [isLoading, setIsLoading] = useState(true); const handleClearAll = async () => { clearCart(); setServerCartItems([]); setServerSummary(null); const token = typeof window !== 'undefined' ? localStorage.getItem('refreshToken') : null; if (token) { try { await clearServerCartApi(); window.dispatchEvent(new Event('cartUpdated')); } catch (error) { console.error("خطا در پاک کردن سبد خرید سرور:", error); } } }; // ۱. ایجاد قفل برای جلوگیری از اجرای تکراری const isSyncingRef = useRef(false); const hasFetchedRef = useRef(false); // --- منطق ادغام (Merge) و دریافت اطلاعات سرور --- useEffect(() => { const fetchAndMergeCart = async () => { const token = typeof window !== 'undefined' ? localStorage.getItem('refreshToken') : null; if (!token) { setIsLoggedIn(false); setIsLoading(false); return; } setIsLoggedIn(true); // ۲. بررسی قفل: اگر توکن داریم، سبد لوکال پر است و قبلا در حال سینک نبودیم if (cart.length > 0 && !isSyncingRef.current) { isSyncingRef.current = true; setIsLoading(true); try { await Promise.all( cart.map(item => addToCartApi(item.id, item.quantity)) ); clearCart(); window.dispatchEvent(new Event('cartUpdated')); } catch (error) { console.error("خطا در انتقال محصولات لوکال به سرور:", error); } } // ۳. دریافت اطلاعات از سرور if (cart.length === 0 && !hasFetchedRef.current || isSyncingRef.current) { try { const data = await getCartApi(); if (data) { setServerCartItems(data.items || []); setServerSummary(data.summary || null); hasFetchedRef.current = true; } } catch (error) { console.error("خطا در دریافت اطلاعات سبد خرید:", error); } finally { setIsLoading(false); } } else { setIsLoading(false); } }; fetchAndMergeCart(); }, [cart.length, clearCart]); // --- لیسنر برای آپدیت لحظه‌ای وقتی CartControls مقادیر را تغییر می‌دهد --- useEffect(() => { const updateServerData = async () => { const token = typeof window !== 'undefined' ? localStorage.getItem('refreshToken') : null; if (token) { try { const data = await getCartApi(); if (data) { setServerCartItems(data.items || []); setServerSummary(data.summary || null); } } catch (error) { console.error("خطا در آپدیت سبد خرید سرور:", error); } } }; // هر بار CartControls رویداد را فایر کرد، استیت‌های این صفحه رفرش می‌شوند window.addEventListener('cartUpdated', updateServerData); return () => { window.removeEventListener('cartUpdated', updateServerData); }; }, []); const handleCheckoutNavigation = () => { const token = typeof window !== 'undefined' ? localStorage.getItem('refreshToken') : null; if (token) { router.push('/checkout'); } else { setShowNotLogin(true); } }; const parsePrice = (priceStr?: number | string | null) => { if (!priceStr) return 0; return Number(priceStr.toString().replace(/,/g, '')); }; // آماده‌سازی لیست سبد خرید برای نمایش + اضافه کردن کلید product برای کامپوننت CartControls const displayCart = isLoggedIn ? serverCartItems.map(item => ({ id: item.id, productId: item.product?.id || item.productId, product: item.product, // <-- اضافه شد برای پاس دادن به CartControls title: item.product?.title || "بدون نام", brand: item.product?.brand || "متفرقه", price: item.unitPrice || item.product?.price || 0, quantity: item.quantity || 1, image: item.product?.mainImageUrl || item.product?.image || "/placeholder.png" })) : cart.map(item => ({ id: item.id, productId: item.id, product: item, // <-- در حالت لوکال، خود آیتم همان محصول است title: item.title, brand: item.brand, price: item.price, quantity: item.quantity, image: item.image || "/placeholder.png" })); const totalPrice = isLoggedIn && serverSummary ? serverSummary.totalPrice || serverSummary.total || 0 : cart.reduce((total, item) => total + (parsePrice(item.price) * item.quantity), 0); const totalItems = isLoggedIn && serverSummary ? serverSummary.totalQuantity || serverSummary.itemsCount || 0 : cart.reduce((total, item) => total + item.quantity, 0); // دیزاین حالت سبد خرید خالی if (displayCart.length === 0) { return (

سبد خرید شما خالی است!

هنوز هیچ محصولی به سبد خرید خود اضافه نکرده‌اید. برای مشاهده محصولات به صفحه اصلی برگردید.

بازگشت به فروشگاه
); } return (
{showNotLogin && ( setShowNotLogin(false)} /> )}

سبد خرید {totalItems} کالا

سبد خرید
اطلاعات ارسال
پرداخت

محصولات انتخاب شده

{displayCart.map((item) => { const itemTotal = parsePrice(item.price) * item.quantity; return (
{item.title}

{item.brand}

{item.title}

{item.price ? `${itemTotal.toLocaleString('fa-IR')} ت` : 'استعلام'}
); })}

خلاصه صورتحساب

تعداد کالاها {totalItems} عدد
هزینه ارسال در مرحله بعد
مبلغ قابل پرداخت {totalPrice > 0 ? `${totalPrice.toLocaleString('fa-IR')}` : 'استعلام'} {totalPrice > 0 && تومان}
پرداخت امن
ارسال سریع
); }