import { ComponentPropsWithoutRef } from "react";
import { Root, createRoot } from "react-dom/client";
import { pollForSelector } from "../shared/pollForSelector";
import QuizContainer from "./QuizContainer";


type Props = ComponentPropsWithoutRef<typeof QuizContainer>;

export class ContainerWidget {
    root: Root | undefined;

    constructor(props: Props & {
        selector: string;
        /**
         * In seconds, null - polling disabled
         */
        selectorPollingTimeLimit?: number | null;
    }) {
        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: Props) {
        this.root?.render(<QuizContainer {...props} />);
    }

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