const initialState = {
  items: [],
  total: 0,
};

const cartReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'ADD_TO_CART':
      const itemToAdd = action.payload;
      const existingItem = state.items.find(item => item.id === itemToAdd.id);
      if (existingItem) {
        existingItem.quantity += itemToAdd.quantity;
      } else {
        state.items.push(itemToAdd);
      }
      state.total += itemToAdd.price * itemToAdd.quantity;
      return {...state};

    case 'REMOVE_FROM_CART':
      const itemIdToRemove = action.payload;
      const itemToRemove = state.items.find(item => item.id === itemIdToRemove);
      if (itemToRemove) {
        state.total -= itemToRemove.price * itemToRemove.quantity;
        state.items = state.items.filter(item => item.id !== itemIdToRemove);
      }
      return {...state};

    case 'CLEAR_CART':
      return {
        ...state,
        items: [],
        total: 0,
      };

    default:
      return state;
  }
};

export default cartReducer;
