import React, { useState, useContext, useEffect, useRef } from 'react'; import { useNavigate } from 'react-router-dom'; import styles from '../../css/ShoppingCartCss/shopping-cart-style.module.css'; import { FaShoppingCart } from "react-icons/fa"; import { CartContext } from './CartContext'; import { OrderContext } from './OrderContext'; import ErrorModal from './ErrorModal'; const ShoppingCart = ({ ingredients, hideIngredients }) => { const { cart, setCart, addToCart, removeFromCart } = useContext(CartContext); const { isOrderInProgress } = useContext(OrderContext); const [showCart, setShowCart] = useState(false); const [showIngredients, setShowIngredients] = useState(false); const [showModal, setShowModal] = useState(false); const navigate = useNavigate(); const cartRef = useRef(null); useEffect(() => { if (isOrderInProgress) { const storedCart = localStorage.getItem('cart'); if (storedCart) { const parsedCart = JSON.parse(storedCart); setCart(parsedCart); } } }, [isOrderInProgress, setCart]); const toggleCart = () => { setShowCart(!showCart); if (!hideIngredients) { setShowIngredients(true); } }; const toggleIngredients = () => { setShowIngredients(!showIngredients); }; const handleCheckboxChange = (ingredient) => { if (isOrderInProgress) return; const isInCart = cart.some(item => item.id === ingredient.id); if (isInCart) { removeFromCart(ingredient); } else { addToCart(ingredient); } }; const handleProceedToCheckout = () => { const token = localStorage.getItem('token'); if (!token) { setShowModal(true); } else { navigate("/checkout"); } }; const closeModal = () => { setShowModal(false); }; const handleLoginRedirect = () => { navigate('/login'); }; const isIngredientInCart = (ingredient) => { return cart.some(item => item.id === ingredient.id); }; useEffect(() => { const handleClickOutside = (event) => { if (cartRef.current && !cartRef.current.contains(event.target)) { setShowCart(false); } }; if (showCart) { document.addEventListener('mousedown', handleClickOutside); } else { document.removeEventListener('mousedown', handleClickOutside); } return () => { document.removeEventListener('mousedown', handleClickOutside); }; }, [showCart]); return (
{cart.length > 0 && {cart.length}}
{showCart && (

Shopping Cart

{cart.length === 0 ? (

No items in cart

) : (
{cart.map((item, index) => (

{item.name}

{item.grams > 0 ? `${item.grams} grams` : ''}

{item.grams <= 0 && ( )}
))}
)}
)} {!hideIngredients && (

{showIngredients ? 'Get Them Delivered' : 'Missing Ingredients?'}

    {ingredients.map((ingredient, index) => (
  • ))}
)} {showModal && ( )}
); }; export default ShoppingCart;