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

import { GroupsApp } from '../components/Groups/GroupsApp';
import { GROUPS_BASE_PATH } from '../components/Groups/constants';
import type { GroupsConfig } from '../components/Groups/GroupsConfigContext';
import { store } from '../components/Groups/store';
import { ThemeListener } from '../components/ThemeListener/ThemeListener';
import '../styles.scss';

const defaultConfig: GroupsConfig = { canCreateShared: false, canViewData: false, isSuperHub: false };

const parseConfig = (el: HTMLElement): GroupsConfig => {
  try {
    return { ...defaultConfig, ...JSON.parse(el.dataset.props || '{}') };
  } catch {
    return defaultConfig;
  }
};

let root: Root | null = null;

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

  root = createRoot(el);
  root.render(
    <Provider store={store}>
      <BrowserRouter basename={GROUPS_BASE_PATH}>
        <ThemeListener>
          <GroupsApp config={parseConfig(el)} />
        </ThemeListener>
      </BrowserRouter>
    </Provider>
  );

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

// The mount node may be rendered after this script runs; observe until present.
const observer = new MutationObserver(mount);
observer.observe(document.body, { childList: true, subtree: true });
mount();
