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

export interface CartItem {
  id: string;
  productId: string;
  name: string;
  price: number;
  image: string;
  quantity: number;
  variant?: { id: string; name: string };
}

interface CartStore {
  items: CartItem[];
  isOpen: boolean;
  addItem: (item: Omit<CartItem, 'id'>) => void;
  removeItem: (id: string) => void;
  updateQuantity: (id: string, quantity: number) => void;
  clearCart: () => void;
  toggleCart: () => void;
  setCartOpen: (open: boolean) => void;
  getTotal: () => number;
  getCount: () => number;
}

export const useCartStore = create<CartStore>()(
  persist(
    (set, get) => ({
      items: [],
      isOpen: false,
      
      addItem: (item) => {
        const existing = get().items.find(
          i => i.productId === item.productId && i.variant?.id === item.variant?.id
        );
        
        if (existing) {
          set(state => ({
            items: state.items.map(i =>
              i.id === existing.id
                ? { ...i, quantity: i.quantity + item.quantity }
                : i
            )
          }));
        } else {
          set(state => ({
            items: [...state.items, { ...item, id: `${item.productId}-${item.variant?.id || 'default'}-${Date.now()}` }]
          }));
        }
      },
      
      removeItem: (id) => {
        set(state => ({ items: state.items.filter(i => i.id !== id) }));
      },
      
      updateQuantity: (id, quantity) => {
        if (quantity <= 0) {
          get().removeItem(id);
          return;
        }
        set(state => ({
          items: state.items.map(i =>
            i.id === id ? { ...i, quantity } : i
          )
        }));
      },
      
      clearCart: () => set({ items: [] }),
      
      toggleCart: () => set(state => ({ isOpen: !state.isOpen })),
      
      setCartOpen: (open) => set({ isOpen: open }),
      
      getTotal: () => {
        return get().items.reduce((sum, item) => sum + item.price * item.quantity, 0);
      },
      
      getCount: () => {
        return get().items.reduce((sum, item) => sum + item.quantity, 0);
      }
    }),
    {
      name: 'cart-storage',
      partialize: (state) => ({ items: state.items })
    }
  )
);
