import { Root, createRoot } from "react-dom/client";
import OpenQuizButton from "./OpenQuizButton";
import { createPortal } from "react-dom";
import { pollForSelector } from "../pollForSelector";


export class ButtonWidget {
    root: Root | undefined;
    element = document.createElement("div");

    constructor({ quizId, selector, 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(<OpenQuizButton quizId={quizId} />);

            return;
        }

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

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

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

export class ButtonWidgetFixed {
    root: Root | undefined;
    element = document.createElement("div");

    constructor({ quizId, side }: {
        quizId: string;
        side: "left" | "right";
    }) {
        this.element.style.setProperty("display", "none");
        document.body.appendChild(this.element);

        this.root = createRoot(this.element);

        this.root.render(createPortal(
            <OpenQuizButton
                fixedSide={side}
                quizId={quizId}
            />,
            document.body
        ));
    }

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