import { useLayoutEffect, useMemo } from "react";

let counter = 0;

/**
 * Dynamically creates a style-tag in your head with a given plain CSS string.
 */
function usePlainCss(css: string, uniqueId?: string, keep?: boolean) {
    const id = useMemo(() => `react-use-plain-css-${uniqueId || (counter++).toString(36)}`, []);

    useLayoutEffect(() => {
        let element = document.getElementById(id);

        if (!element) {
            element = document.createElement("style");
            (element.style as any).type = "text/css";
            element.id = id;
            element.setAttribute("skip-rucss", "true");
            document.getElementsByTagName("head")[0].appendChild(element);
        }

        element.innerHTML = css;

        return () => {
            if (!keep) {
                element.parentNode?.removeChild(element);
            }
        };
    }, [css, keep]);

    return id;
}

export { usePlainCss };
