import { defineStore } from 'pinia'

export interface CartItem {
  id: number
  name: string
  price: number
  quantity: number
  imageUrl: string 
}

export const useCartStore = defineStore('cart', {
  state: () => ({
    cartItems: [] as CartItem[],
  }),

  getters: {
    // 总价计算
    totalPrice(state): number {
      return state.cartItems.reduce((sum, item) => sum + item.price * item.quantity, 0)
    },
  },

  actions: {
    addToCart(item: CartItem) {
      const existing = this.cartItems.find(i => i.id === item.id)
      if (existing) {
        existing.quantity += item.quantity
      } else {
        this.cartItems.push(item)
      }
      this.saveToLocalStorage()
    },

    updateQuantity(id: number, quantity: number) {
        const item = this.cartItems.find(i => i.id === id);
        if (item && quantity >= 1) {
          item.quantity = quantity;
          this.saveToLocalStorage();
        }
      },
    
    removeFromCart(id: number) {
      this.cartItems = this.cartItems.filter(i => i.id !== id)
      this.saveToLocalStorage()
    },

    clearCart() {
      this.cartItems = []
      this.saveToLocalStorage()
    },

    loadFromLocalStorage() {
      const stored = localStorage.getItem('cart')
      if (stored) {
        this.cartItems = JSON.parse(stored)
      }
    },

    saveToLocalStorage() {
      localStorage.setItem('cart', JSON.stringify(this.cartItems))
    },

    setCart(items: CartItem[]) {
      this.cartItems = items
      this.saveToLocalStorage()
    },
  },
})