import React from 'react';
import { createRoot } from 'react-dom/client';
import { Provider } from 'react-redux';

import { store } from '@northern.tech/store/store';

import { EntryPoint } from '../components/Auditlog/EntryPoint';
import { ThemeListener } from '../components/ThemeListener/ThemeListener';
import '../styles.scss';

// observer body change and mount component
// as root elements might not be rendered on the loading time
const mountReactComponents = () => {
  const elements = document.querySelectorAll('.auditLogEntryPoint:not([data-react-mounted])');

  elements.forEach(element => {
    const root = createRoot(element as HTMLElement);
    root.render(
      <React.StrictMode>
        <Provider store={store}>
          <ThemeListener>
            <EntryPoint />
          </ThemeListener>
        </Provider>
      </React.StrictMode>
    );

    // Mark the element to avoid re-rendering
    element.setAttribute('data-react-mounted', 'true');
  });
};

const observer = new MutationObserver(() => {
  mountReactComponents();
});

observer.observe(document.body, { childList: true, subtree: true });
mountReactComponents();
