import { create } from 'zustand';
import { persist } from 'zustand/middleware';

// 1. Define what a single item in the cart looks like
export interface CartItem {
  id: string;
  name: string;
  price: number;
  quantity: number;
  image?: string;
}

// 2. Define the actions our cart can perform
interface CartState {
  // Cart Items State
  items: CartItem[];
  addItem: (item: CartItem) => void;
  removeItem: (id: string) => void;
  updateQuantity: (id: string, quantity: number) => void;
  clearCart: () => void;
  getCartTotal: () => number;
  
  // UI State for the Drawer
  isCartOpen: boolean;
  openCart: () => void;
  closeCart: () => void;
}

// 3. Create the actual store
export const useCartStore = create<CartState>()(
  persist(
    (set, get) => ({
      // --- Initial State ---
      items: [],
      isCartOpen: false,

      // --- UI Actions ---
      openCart: () => set({ isCartOpen: true }),
      closeCart: () => set({ isCartOpen: false }),

      // --- Cart Logic Actions ---
      // Add item: Check if it exists first. If yes, increase quantity. If no, add as new.
      addItem: (item) => {
        const currentItems = get().items;
        const existingItem = currentItems.find((i) => i.id === item.id);
        
        if (existingItem) {
          set({
            items: currentItems.map((i) =>
              i.id === item.id ? { ...i, quantity: i.quantity + item.quantity } : i
            ),
          });
        } else {
          set({ items: [...currentItems, item] });
        }
      },

      // Remove item entirely from the cart
      removeItem: (id) => {
        set({ items: get().items.filter((i) => i.id !== id) });
      },

      // Update quantity (e.g., when a user clicks "+" or "-" in the cart)
      updateQuantity: (id, quantity) => {
        set({
          items: get().items.map((i) =>
            i.id === id ? { ...i, quantity: Math.max(1, quantity) } : i
          ),
        });
      },

      // Empty the cart completely (used after a successful checkout)
      clearCart: () => set({ items: [] }),

      // Calculate total price
      getCartTotal: () => {
        return get().items.reduce((total, item) => total + item.price * item.quantity, 0);
      },
    }),
    {
      name: 'wowwear-cart', // This is the key name used in localStorage to save their items
    }
  )
);