import { create } from 'zustand'; const useCartStore = create((set, get) => ({ items: [], addItem: (product) => { const items = get().items; const existing = items.find((i) => i.product_id === product.id); if (existing) { set({ items: items.map((i) => i.product_id === product.id ? { ...i, quantity: i.quantity + 1 } : i ), }); } else { set({ items: [...items, { product_id: product.id, name: product.name, price: product.price, quantity: 1, }], }); } }, removeItem: (productId) => { set({ items: get().items.filter((i) => i.product_id !== productId) }); }, updateQuantity: (productId, quantity) => { if (quantity <= 0) { get().removeItem(productId); return; } set({ items: get().items.map((i) => i.product_id === productId ? { ...i, quantity } : i ), }); }, getTotal: () => { return get().items.reduce((sum, i) => sum + i.price * i.quantity, 0); }, getItemCount: () => { return get().items.reduce((sum, i) => sum + i.quantity, 0); }, clearCart: () => set({ items: [] }), setItems: (newItems) => set({ items: newItems }), })); export default useCartStore;