1import { defineStore } from "pinia"
2import { computed, ref } from "vue"
3
4interface Product {
5 id: string
6 name: string
7 price: number
8 image: string
9}
10
11interface CartItem {
12 product: Product
13 quantity: number
14}
15
16export const useCartStore = defineStore("cart", () => {
17 const items = ref<CartItem[]>([])
18 const isOpen = ref(false)
19
20 const totalItems = computed(() =>
21 items.value.reduce((sum, item) => sum + item.quantity, 0)
22 )
23
24 const totalPrice = computed(() =>
25 items.value.reduce(
26 (sum, item) => sum + item.product.price * item.quantity,
27 0
28 )
29 )
30
31 const formattedTotal = computed(() =>
32 new Intl.NumberFormat("en-US", {
33 style: "currency",
34 currency: "USD",
35 }).format(totalPrice.value)
36 )
37
38 function addItem(product: Product, quantity = 1): void {
39 const existing = items.value.find(
40 (item) => item.product.id === product.id
41 )
42 if (existing) {
43 existing.quantity += quantity
44 } else {
45 items.value.push({ product, quantity })
46 }
47 }
48
49 function removeItem(productId: string): void {
50 const index = items.value.findIndex(
51 (item) => item.product.id === productId
52 )
53 if (index !== -1) {
54 items.value.splice(index, 1)
55 }
56 }
57
58 function updateQuantity(productId: string, quantity: number): void {
59 const item = items.value.find(
60 (item) => item.product.id === productId
61 )
62 if (item) {
63 if (quantity <= 0) {
64 removeItem(productId)
65 } else {
66 item.quantity = quantity
67 }
68 }
69 }
70
71 function clearCart(): void {
72 items.value = []
73 }
74
75 function toggle(): void {
76 isOpen.value = !isOpen.value
77 }
78
79 return {
80 items,
81 isOpen,
82 totalItems,
83 totalPrice,
84 formattedTotal,
85 addItem,
86 removeItem,
87 updateQuantity,
88 clearCart,
89 toggle,
90 }
91})