
import thunk from 'redux-thunk';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { authReducer, promiseReducer, cartReducer } from '../reducer';
import { actionRootCats, actionSearchGood } from "../action";

// export const store = createStore(combineReducers({
//   promise: promiseReducer, 
//   auth: authReducer, 
//   cart: cartReducer
// }), applyMiddleware(thunk));
 
// store.subscribe(() => console.log(store.getState()));
// store.dispatch(actionRootCats());



const localStoredReducer = (reducer, localStorageName) => 
  (state, action) => { 

    if(!state) {
      const key = localStorage.getItem(localStorageName); 
      if(key) { 
       return JSON.parse(key);
      } else {
       return reducer(state, action);
      }  
    }       
    if(state) {
      let newState = reducer(state, action);  
      localStorage.setItem(localStorageName, JSON.stringify(newState));
      return newState;
    }   
  }


 


  export const store = createStore(combineReducers({
    promise: localStoredReducer(promiseReducer, 'promise'), 
    auth: localStoredReducer(authReducer, 'auth'), 
    cart: localStoredReducer(cartReducer, 'cart')
  }), applyMiddleware(thunk));


  


store.subscribe(() => console.log(store.getState()));
store.dispatch(actionRootCats());
// setTimeout(() => {
//   store.dispatch(actionSearchGood("iPhone 11"));
// }, 2000)
