import { ContainerWidgetParams } from "@/model/widget/container";
import { Root, createRoot } from "react-dom/client";
import { pollForSelector } from "../shared/pollForSelector";
import QuizContainer from "./QuizContainer";

export class ContainerWidget {
  root: Root | undefined;

  constructor(props: ContainerWidgetParams) {
    const { selector, selectorPollingTimeLimit = 60 } = props;

    const element = document.querySelector(selector);
    if (element) {
      this.root = createRoot(element);
      this.render(props);

      return;
    }

    if (!selectorPollingTimeLimit) {
      console.error(`Не удалось найти элемент ${selector} для вставки виджета`);
      return;
    }

    pollForSelector(selector, selectorPollingTimeLimit, (element) => {
      this.root = createRoot(element);
      this.render(props);
    });
  }

  render(props: Omit<ContainerWidgetParams, "selector" | "selectorPollingTimeLimit">) {
    this.root?.render(<QuizContainer {...props} />);
  }

  destroy() {
    if (this.root) this.root.unmount();
  }
}
