import { createSlice , CaseReducer , PayloadAction } from '@reduxjs/toolkit' ; export type ShopItem = { id : number ; name : string ; price : number ; imageUrl ? : string ; description ? : string ; } ; export interface CartItem extends ShopItem { quantity : number ; } export type CartState = { visible : boolean ; items : CartItem [ ] ; } ; const toggleVisibility = ( state ) => { state . visible = ! state . visible ; } ; const clearCart = ( state ) => { state . visible = false ; state . items = [ ] ; } ; const clearItem = ( state , action ) => { state . items = state . items . filter ( ( item ) => item . id !== action . payload . id ) ; } ; const removeItem = ( state , action ) => { const existingCartItem = state . items . find ( ( item ) => item . id === action . payload . id ) ; if ( ! existingCartItem ) return ; if ( existingCartItem . quantity === 1 ) { state . items = state . items . filter ( ( item ) => item . id !== action . payload . id ) ; } else { existingCartItem . quantity -= 1 ; } } ; const saveItem = ( state , action ) => { const existingCartItem = state . items . find ( ( item ) => item . id === action . payload . id ) as CartItem ; if ( existingCartItem ) { existingCartItem . quantity = action . payload . quantity ; } else { state . items . push ( action . payload ) ; } } ; const initialState = { visible : false , items : [ ] , } ; const counterSlice = createSlice ( { name : 'cart' , initialState , reducers : { toggleVisibilityAction : toggleVisibility , saveItemAction : saveItem , clearItemAction : clearItem , removeItemAction : removeItem , clearCartAction : clearCart , } , } ) ; export const { actions , reducer } = counterSlice ; export const { toggleVisibilityAction , saveItemAction , clearItemAction , removeItemAction , clearCartAction , } = actions ; export default reducer ;