import {createContext, useContext, useState} from 'react';

export const CartContext = createContext(undefined);

export const CartProvider = ({children}) => {
  const [cart, setCart] = useState([]);

  const addToCart = (product, quantity) => {
    // Add a product to the cart
    const item = {product, quantity};
    setCart([...cart, item]);
  };

  const removeFromCart = product => {
    // Remove a product from the cart
    const updatedCart = cart.filter(item => item.product.id !== product.id);
    setCart(updatedCart);
  };

  const updateQuantity = (product, quantity) => {
    // Update the quantity of a product in the cart
    const updatedCart = cart.map(item => {
      if (item.product.id === product.id) {
        return {...item, quantity};
      } else {
        return item;
      }
    });
    setCart(updatedCart);
  };

  return (
    // Make the cart data and functions available to child components
    <CartContext.Provider
      value={{cart, addToCart, removeFromCart, updateQuantity}}>
      {children}
    </CartContext.Provider>
  );
};

// A custom hook to access the cart context
// export const useCart = () => useContext(CartContext);
export default CartProvider;

