import { ref, watch } from 'vue' import { defineStore } from 'pinia' import { cartApi } from '../api' export const useCartStore = defineStore('cart', () => { const items = ref([]) const loading = ref(false) const totalAmount = ref(0) const totalCount = ref(0) async function fetchCart() { loading.value = true try { const res: any = await cartApi.list() items.value = res.data || [] calcTotals() } finally { loading.value = false } } async function addItem(productId: number, quantity: number) { await cartApi.add({ product_id: productId, quantity }) await fetchCart() } async function updateItem(id: number, quantity: number) { await cartApi.update(id, { quantity }) await fetchCart() } async function removeItem(id: number) { await cartApi.delete(id) await fetchCart() } async function removeItems(ids: number[]) { for (const id of ids) { await cartApi.delete(id) } await fetchCart() } function calcTotals() { totalAmount.value = items.value.reduce((sum, item) => sum + (item.product?.price || 0) * item.quantity, 0) totalCount.value = items.value.reduce((sum, item) => sum + item.quantity, 0) } watch(items, calcTotals, { deep: true }) return { items, loading, totalAmount, totalCount, fetchCart, addItem, updateItem, removeItem, removeItems } })