// GUEST CART FIX - Copy this handleAddToCart function
// Replace lines 49-88 in src/components/Product/Product.tsx

const handleAddToCart = async () => {
    const token = localStorage.getItem("token"); // check login
    const productId = data._id || data.id; // Handle both _id and id
    
    const payload = {
        productId: data._id,
        quantity: data.quantityPurchase || 1,
        color: activeColor ? activeColor : data?.variation[0]?.color,
        size: activeSize ? activeSize : data?.sizes[0],
    };

    // Create cart item with proper structure
    const cartItem = {
        ...data,
        id: productId, // Ensure ID is set for localStorage
        quantity: payload.quantity,
        selectedColor: payload.color,
        selectedSize: payload.size
    };

    console.log("🛒 Adding to cart:", cartItem);
    console.log("📦 Current cart:", cartState.cartArray);

    // ✅ Always update Redux (works for both guest + logged-in users)
    const existingItem = cartState.cartArray.find((item) => 
        (item.id === productId || item._id === productId)
    );

    if (!existingItem) {
        console.log("➕ Adding new item to cart");
        addToCart(cartItem);
    } else {
        console.log("🔄 Updating existing item");
        updateCart(productId, payload.quantity, payload.size, payload.color);
    }

    // ✅ If logged in → also sync with API
    if (token) {
        try {
            const response = await axios.post(`${BaseURL}/cart`, payload, {
                headers: {
                    Authorization: `Bearer ${token}`,
                },
            });

            if (response.status === 200) {
                console.log("✅ Cart synced with API");
            }
        } catch (error: any) {
            console.error(
                "❌ Error syncing cart:",
                error.response?.data?.message || error.message
            );
        }
    } else {
        console.log("🛒 Guest mode: cart stored in localStorage via Redux");
    }

    openModalCart();
};
