import { createStore } from "skybridge/web";
type CartItem = { id: string; name: string; price: number; quantity: number };
type CartState = {
items: CartItem[];
addItem: (item: Omit<CartItem, "quantity">) => void;
removeItem: (id: string) => void;
updateQuantity: (id: string, quantity: number) => void;
total: () => number;
clear: () => void;
};
const useCartStore = createStore<CartState>((set, get) => ({
items: [],
addItem: (item) => set((state) => {
const existing = state.items.find(existingItem => existingItem.id === item.id);
if (existing) {
return {
items: state.items.map(existingItem =>
existingItem.id === item.id ? { ...existingItem, quantity: existingItem.quantity + 1 } : existingItem
),
};
}
return { items: [...state.items, { ...item, quantity: 1 }] };
}),
removeItem: (id) => set((state) => ({
items: state.items.filter(item => item.id !== id),
})),
updateQuantity: (id, quantity) => set((state) => ({
items: state.items.map(item =>
item.id === id ? { ...item, quantity } : item
),
})),
total: () => get().items.reduce(
(sum, item) => sum + item.price * item.quantity,
0
),
clear: () => set({ items: [] }),
}), { items: [] }); // Default state for first load