import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { AllCommunityModule, ModuleRegistry } from 'ag-charts-community';
import App from './App';
import './styles.css';

ModuleRegistry.registerModules([AllCommunityModule]);

declare global {
  interface Window {
    __chartReactRoots?: WeakMap<Element, ReturnType<typeof createRoot>>;
  }
}

const chartContainerId = 'sbChart';

const getRootRegistry = () => {
  window.__chartReactRoots ??= new WeakMap<Element, ReturnType<typeof createRoot>>();
  return window.__chartReactRoots;
};

const mount = () => {
  const container = document.getElementById(chartContainerId);
  if (!container) return false;

  const roots = getRootRegistry();
  let root = roots.get(container);
  if (!root) {
    root = createRoot(container);
    roots.set(container, root);
  }

  root.render(
    <StrictMode>
      <App />
    </StrictMode>,
  );
  return true;
};

if (!mount()) {
  let retryCount = 0;
  const timer = window.setInterval(() => {
    retryCount += 1;
    if (mount() || retryCount >= 40) {
      window.clearInterval(timer);
      if (retryCount >= 40) {
        console.warn(`${chartContainerId} container was not found.`);
      }
    }
  }, 50);
}
