import { useReducer } from 'react';

import domReady from '@wordpress/dom-ready';
import { createRoot } from '@wordpress/element';
import { HashRouter } from 'react-router-dom';

import {
  adminSettingsReducer,
  premiumSettingsReducer,
  settingsReducer,
} from './context/reducer';
import {
  AdminSettingsContext,
  AdminSettingsDispatchContext,
  SettingsContext,
  SettingsDispatchContext,
  PremiumSettingsContext,
  PremiumSettingsDispatchContext,
} from './context/contexts';

import {
  adminSettings,
  premiumSettings,
  settings,
} from './context/initialState';
import InitSettingsPage from './initSettingsPage';

import './styles/global.styles.scss';

const Providers = () => {
  const [data, dispatch] = useReducer(settingsReducer, settings);
  const [appData, appDispatch] = useReducer(
    adminSettingsReducer,
    adminSettings
  );
  const [premiumData, premiumDispatch] = useReducer(
    premiumSettingsReducer,
    premiumSettings
  );

  return (
    <PremiumSettingsContext.Provider value={premiumData}>
      <PremiumSettingsDispatchContext.Provider value={premiumDispatch}>
        <AdminSettingsContext.Provider value={appData}>
          <AdminSettingsDispatchContext.Provider value={appDispatch}>
            <SettingsContext.Provider value={data}>
              <SettingsDispatchContext.Provider value={dispatch}>
                <HashRouter>
                  <InitSettingsPage />
                </HashRouter>
              </SettingsDispatchContext.Provider>
            </SettingsContext.Provider>
          </AdminSettingsDispatchContext.Provider>
        </AdminSettingsContext.Provider>
      </PremiumSettingsDispatchContext.Provider>
    </PremiumSettingsContext.Provider>
  );
};

domReady(() => {
  const root = createRoot(document.getElementById('botfoundry-settings'));

  root.render(<Providers />);
});
