import React from "react";
import { TinyMCE } from "./tinymce";

let interval: any;

export default function useTinyMCE() {
    const [tinyMCE, setTinyMCE] = React.useState<TinyMCE>();
    const [refresh, setRefresh] = React.useState(0);
    const [scriptLoaded, setScriptLoaded] = React.useState(false);

    React.useEffect(() => {
        if (refresh >= 5) return;

        const clientWindow = window as Window & { tinymce?: TinyMCE };

        if (clientWindow.tinymce) {
            setScriptLoaded(true);
            return;
        }

        const script = document.createElement("script");

        const baseUrl =
            process.env.NEXT_PUBLIC_TINYMCE_BASE_URL ||
            "https://www.datasquirel.com/tinymce-public";

        script.src = `${baseUrl}/tinymce.min.js`;
        script.async = true;

        script.onload = () => {
            setScriptLoaded(true);
        };

        document.head.appendChild(script);
    }, [refresh]);

    React.useEffect(() => {
        if (!scriptLoaded) return;

        const clientWindow = window as Window & { tinymce?: TinyMCE };

        let tinyMCE = clientWindow.tinymce;

        if (tinyMCE) {
            setTinyMCE(tinyMCE);
        } else {
            setRefresh((prev) => prev + 1);
        }
    }, [scriptLoaded]);

    return { tinyMCE };
}
