import Taro from '@tarojs/taro'

const CART_KEY = 'MARKET_CART'

export interface CartItem {
  id: number
  name: string
  price: number
  image: string
  quantity: number
  selected: boolean
  stock: number
  description: string
}

export const getCart = (): CartItem[] => {
  return Taro.getStorageSync(CART_KEY) || []
}

export const setCart = (cart: CartItem[]) => {
  Taro.setStorageSync(CART_KEY, cart)
}

export const addToCart = (product: any, quantity: number = 1) => {
  const cart = getCart()
  const existing = cart.find(item => item.id === product.id)
  
  if (existing) {
    existing.quantity += quantity
    if (existing.quantity > product.stock) existing.quantity = product.stock
  } else {
    cart.push({
      id: product.id,
      name: product.name,
      price: product.price,
      image: product.static_image_url || product.detail_image_url,
      quantity: quantity,
      selected: true,
      stock: product.stock,
      description: product.description
    })
  }
  
  setCart(cart)
  Taro.showToast({ title: '已加入购物车', icon: 'success' })
}

export const updateQuantity = (id: number, quantity: number) => {
  const cart = getCart()
  const item = cart.find(i => i.id === id)
  if (item) {
    item.quantity = quantity
    if (item.quantity > item.stock) item.quantity = item.stock
    if (item.quantity < 1) item.quantity = 1
    setCart(cart)
  }
  return cart
}

export const removeItem = (id: number) => {
  const cart = getCart()
  const newCart = cart.filter(i => i.id !== id)
  setCart(newCart)
  return newCart
}

export const toggleSelect = (id: number) => {
  const cart = getCart()
  const item = cart.find(i => i.id === id)
  if (item) {
    item.selected = !item.selected
    setCart(cart)
  }
  return cart
}

export const toggleSelectAll = (selected: boolean) => {
  const cart = getCart()
  cart.forEach(item => item.selected = selected)
  setCart(cart)
  return cart
}

export const getSelectedItems = () => {
  return getCart().filter(item => item.selected)
}

export const getCartCount = () => {
  return getCart().reduce((sum, item) => sum + item.quantity, 0)
}
