import React, { ReactElement } from 'react';
import { createRoot } from 'react-dom/client';
import { Provider } from 'react-redux';
import type { Store } from 'redux';

import createCache from '@emotion/cache';
import { CacheProvider } from '@emotion/react';

import { ThemeListener } from '../ThemeListener/ThemeListener';

export const mountSettings = (rootId: string, content: ReactElement, store?: Store) => {
  const el = document.getElementById(rootId);
  if (!el) return;

  const cache = createCache({ key: 'mui', prepend: true });

  let tree: ReactElement = (
    <CacheProvider value={cache}>
      <ThemeListener>{content}</ThemeListener>
    </CacheProvider>
  );

  if (store) {
    tree = <Provider store={store}>{tree}</Provider>;
  }

  createRoot(el).render(<React.StrictMode>{tree}</React.StrictMode>);
};
