import { createRoot } from "react-dom/client";

import { getSidebarCustomize } from "./getSidebarCustomize.js";

type RenderFunction = (liElement: HTMLLIElement) => any;

type RenderOptions = {
    render: RenderFunction;
    type: "before" | "after";
};

/**
 * Allows to prepend an React node before a section li-element.
 *
 * @param sections
 */
function addContentBesideSection(sections: { [key: string]: RenderFunction | RenderOptions }) {
    const customize = getSidebarCustomize();

    for (const sectionId of Object.keys(sections)) {
        let opts: Partial<RenderOptions> = {};
        const Component = sections[sectionId];

        if (typeof Component === "function") {
            opts.render = Component;
            opts.type = "before";
        } else {
            opts = Component;
        }

        const liElement = (customize.section(sectionId)?.container.get(0) ||
            customize.control(sectionId)?.container.get(0)) as HTMLLIElement;

        if (!liElement) {
            return;
        }

        const renderNode = document.createElement("div");

        if (opts.type === "before") {
            liElement.before(renderNode);
        } else {
            liElement.after(renderNode);
        }

        createRoot(renderNode).render(opts.render(liElement));
    }
}

export { addContentBesideSection };
