import React, { useEffect, useState } from 'react';
import { _RPGUI } from './RPGUIRoot';

interface IProps {
  elementDOMId: string;
  elementRenderedDOMKey: string; // this is what "proves" the element is rendered
  children: React.ReactNode;
  RPGUICreateFunction:
    | 'dropdown'
    | 'slider'
    | 'checkbox'
    | 'draggable'
    | 'progress'
    | 'radio'
    | 'list';
}

export const RPGUIForceRenderStart: React.FC<IProps> = ({
  children,
  elementDOMId,
  elementRenderedDOMKey,
  RPGUICreateFunction,
}) => {
  const [isRendered, setIsRendered] = useState<boolean>(false);

  useEffect(() => {
    if (_RPGUI) {
      const element = document.getElementById(elementDOMId);

      // create an interval to wait for the element to be rendered
      // if it's not, trigger the rendering forcefully
      const interval = setInterval(() => {
        const dropdown = document.querySelector(elementRenderedDOMKey);

        if (!dropdown && !isRendered) {
          _RPGUI.__create_funcs[RPGUICreateFunction](element);
          setIsRendered(true);
          clearInterval(interval);
        }
      }, 10);
    }
  }, []);

  return <>{children}</>;
};
