import { rootReducer } from './rootReducer.js';
import { INIT_STATE } from './types.js';

/**
 * @param {Function} rootReducer
 * @param {number} initialState
 */

const currentStep = Number(localStorage.getItem('trainingModalCurrentStep'));

const initialState = {
  currentStep: currentStep >= 1 && currentStep <= 6 ? currentStep : 1,
  isAllowRender: false,
};

const createStore = (rootReducer, initialState) => {
  let state = rootReducer(initialState, { type: INIT_STATE });
  const subscribers = [];

  return {
    dispatch(action) {
      state = rootReducer(state, action);
      subscribers.forEach((sub) => sub());
    },
    subscribe(callback) {
      subscribers.push(callback);
    },
    getState() {
      return state;
    },
  };
};

export const { dispatch, getState, subscribe } = createStore(rootReducer, initialState);