diff --git a/src/context/cartContext.tsx b/src/context/cartContext.tsx new file mode 100644 index 0000000..94c9029 --- /dev/null +++ b/src/context/cartContext.tsx @@ -0,0 +1,91 @@ +import React, { createContext, useContext, useState, ReactNode, useEffect } from 'react'; + +interface CartItem { + id: string; + name: string; + price: string; // Storing as string for display, will parse for calculations + quantity: number; + imageSrc: string; + imageAlt?: string; + variant?: string; +} + +interface CartContextType { + cartItems: CartItem[]; + addToCart: (item: Omit) => void; + removeFromCart: (id: string) => void; + updateQuantity: (id: string, quantity: number) => void; + getTotalPrice: () => string; +} + +const CartContext = createContext(undefined); + +export const CartProvider = ({ children }: { children: ReactNode }) => { + const [cartItems, setCartItems] = useState(() => { + if (typeof window !== 'undefined') { + const savedCart = localStorage.getItem('cart'); + return savedCart ? JSON.parse(savedCart) : []; + } + return []; + }); + + useEffect(() => { + if (typeof window !== 'undefined') { + localStorage.setItem('cart', JSON.stringify(cartItems)); + } + }, [cartItems]); + + const addToCart = (item: Omit) => { + setCartItems((prevItems) => { + const existingItem = prevItems.find((cartItem) => cartItem.id === item.id); + if (existingItem) { + return prevItems.map((cartItem) => + cartItem.id === item.id + ? { ...cartItem, quantity: cartItem.quantity + 1 } + : cartItem + ); + } else { + return [...prevItems, { ...item, quantity: 1 }]; + } + }); + }; + + const removeFromCart = (id: string) => { + setCartItems((prevItems) => prevItems.filter((item) => item.id !== id)); + }; + + const updateQuantity = (id: string, quantity: number) => { + setCartItems((prevItems) => { + if (quantity <= 0) { + return prevItems.filter((item) => item.id !== id); + } + return prevItems.map((item) => + item.id === id ? { ...item, quantity: quantity } : item + ); + }); + }; + + const getTotalPrice = () => { + const total = cartItems.reduce((sum, item) => { + const priceValue = parseFloat(item.price.replace(/[^0-9.-]+/g, "")); + return sum + priceValue * item.quantity; + }, 0); + return `$${total.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; + }; + + return ( + + {children} + + ); +}; + +export const useCart = () => { + const context = useContext(CartContext); + if (context === undefined) { + throw new Error('useCart must be used within a CartProvider'); + } + return context; +};