// context/CartContext.tsx
import React, { createContext, useState, useContext, ReactNode } from 'react';

type CartItem = {
  productName: string;
  quantity: number;
};

type CartState = {
  items: CartItem[];
  total: number;
};

type CartContextType = {
  cart: CartState;
  addItem: (item: CartItem) => void;
  clearCart: () => void;
};

const CartContext = createContext<CartContextType | undefined>(undefined);

export const CartProvider = ({ children }: { children: ReactNode }) => {
  const [cart, setCart] = useState<CartState>({ items: [], total: 0 });

  const addItem = (item: CartItem) => {
    setCart(prev => {
      const existing = prev.items.find(i => i.productName === item.productName);
      let updatedItems;
      if (existing) {
        updatedItems = prev.items.map(i =>
          i.productName === item.productName
            ? { ...i, quantity: i.quantity + item.quantity }
            : i
        );
      } else {
        updatedItems = [...prev.items, item];
      }
      const updatedTotal = updatedItems.reduce((sum, i) => sum + i.quantity, 0);
      return { items: updatedItems, total: updatedTotal };
    });
  };

  const clearCart = () => setCart({ items: [], total: 0 });

  return (
    <CartContext.Provider value={{ cart, addItem, clearCart }}>
      {children}
    </CartContext.Provider>
  );
};

export const useCart = () => {
    const context = useContext(CartContext);
    if (!context) {
      throw new Error('useCart must be used within a CartProvider');
    }
    return context;
  };
  
