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

export interface CartItem {
  productId: string;
  name: string;
  brand: string;
  price: number;
  image: string;
  color?: string;
  size?: string;
  quantity: number;
}

interface CartState {
  items: CartItem[];
  isOpen: boolean;

  // Actions
  addItem: (item: Omit<CartItem, 'quantity'>) => void;
  removeItem: (productId: string, color?: string, size?: string) => void;
  updateQuantity: (productId: string, quantity: number, color?: string, size?: string) => void;
  clearCart: () => void;
  toggleCart: () => void;
  openCart: () => void;
  closeCart: () => void;

  // Computed (via selectors)
  getTotal: () => number;
  getItemCount: () => number;
}

function itemKey(item: { productId: string; color?: string; size?: string }) {
  return `${item.productId}-${item.color || ''}-${item.size || ''}`;
}

export const useCartStore = create<CartState>()(
  persist(
    (set, get) => ({
      items: [],
      isOpen: false,

      addItem: (item) => {
        const key = itemKey(item);
        set((state) => {
          const existing = state.items.find(i => itemKey(i) === key);
          if (existing) {
            return {
              items: state.items.map(i =>
                itemKey(i) === key ? { ...i, quantity: i.quantity + 1 } : i
              ),
              isOpen: true,
            };
          }
          return {
            items: [...state.items, { ...item, quantity: 1 }],
            isOpen: true,
          };
        });
      },

      removeItem: (productId, color, size) => {
        const key = itemKey({ productId, color, size });
        set((state) => ({
          items: state.items.filter(i => itemKey(i) !== key),
        }));
      },

      updateQuantity: (productId, quantity, color, size) => {
        const key = itemKey({ productId, color, size });
        if (quantity <= 0) {
          set((state) => ({ items: state.items.filter(i => itemKey(i) !== key) }));
        } else {
          set((state) => ({
            items: state.items.map(i =>
              itemKey(i) === key ? { ...i, quantity } : i
            ),
          }));
        }
      },

      clearCart: () => set({ items: [] }),
      toggleCart: () => set((s) => ({ isOpen: !s.isOpen })),
      openCart: () => set({ isOpen: true }),
      closeCart: () => set({ isOpen: false }),

      getTotal: () => get().items.reduce((sum, i) => sum + i.price * i.quantity, 0),
      getItemCount: () => get().items.reduce((sum, i) => sum + i.quantity, 0),
    }),
    {
      name: 'ol-cart',
      partialize: (state) => ({ items: state.items }), // persist only items, not isOpen
    }
  )
);
