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

function calculateControlBreadcrumb(setting: string) {
    return new Promise<string>((resolve) => {
        const customize = getSidebarCustomize();

        customize.control(
            setting,
            ({ container, section }: { container: JQuery<HTMLLIElement>; section: () => string }) => {
                const foundHeadlines: Record<string, string> = {};
                container.prevAll(".customize-control-headline").each(function () {
                    const h = jQuery(this).children().children().get(0);
                    const { nodeName, innerHTML } = h;
                    if (!foundHeadlines[nodeName]) {
                        foundHeadlines[nodeName] = innerHTML;
                    }
                });

                resolve(
                    [
                        customize.section(section()).headContainer.text().trim().split("\n")[0],
                        ...Object.values(foundHeadlines).reverse(),
                        container.find(".customize-control-title,input+label").first().text(),
                    ].join(" ▸ "),
                );
            },
        );
    });
}

export { calculateControlBreadcrumb };
