import QuizAnswerer from "@/components/QuizAnswerer";
import { Root, createRoot } from "react-dom/client";
import { pollForSelector } from "../shared/pollForSelector";


export class ContainerWidget {
    root: Root | undefined;

    constructor({ selector, quizId, selectorPollingTimeLimit = 60 }: {
        quizId: string;
        selector: string;
        /**
         * In seconds, null - polling disabled
         */
        selectorPollingTimeLimit?: number | null;
    }) {
        const element = document.querySelector(selector);
        if (element) {
            this.root = createRoot(element);
            this.root.render(
                <QuizAnswerer
                    quizId={quizId}
                    changeFaviconAndTitle={false}
                    disableGlobalCss
                />
            );

            return;
        }

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

        pollForSelector(selector, selectorPollingTimeLimit, (element) => {
            this.root = createRoot(element);
            this.root.render(
                <QuizAnswerer
                    quizId={quizId}
                    changeFaviconAndTitle={false}
                    disableGlobalCss
                />
            );
        });
    }

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