import { createRoot, Root } from 'react-dom/client';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';

import { HostsApp } from '../components/Hosts/HostsApp';
import { store } from '../components/Hosts/store';
import { ThemeListener } from '../components/ThemeListener/ThemeListener';
import '../styles.scss';

let root: Root | null = null;

const mount = () => {
  const el = document.querySelector('#hosts-root:not([data-react-mounted])');
  if (!el) return;

  root = createRoot(el as HTMLElement);
  root.render(
    <Provider store={store}>
      <BrowserRouter basename="/hosts">
        <ThemeListener>
          <HostsApp />
        </ThemeListener>
      </BrowserRouter>
    </Provider>
  );

  el.setAttribute('data-react-mounted', 'true');
};

const observer = new MutationObserver(mount);
observer.observe(document.body, { childList: true, subtree: true });
mount();
