import { isLocalhost } from "./util";
export function cleanupEditor(html) {
    const tmpElement = Object.assign(document.createElement("div"), {
        innerHTML: html,
    });
    const elementsToRemove = Array.from(tmpElement.querySelectorAll("[data-eden-remove-on-save]"));
    elementsToRemove.forEach((el) => el.remove());
    return tmpElement.innerHTML;
}
export function closeDetailsElements() {
    const openedFaqs = document.querySelectorAll("[data-eden-editor] details[open]");
    if (openedFaqs) {
        Array.from(openedFaqs).forEach((faq) => faq.removeAttribute("open"));
    }
}
export function cleanupTagsAndPreserveContent(selector) {
    const tags = Array.from(document.querySelectorAll(selector));
    tags.forEach((tag) => {
        if (!tag.textContent)
            return;
        tag.outerHTML = tag.textContent;
    });
}
export function cleanupOldSvgAttributes() {
    const svgUseElements = Array.from(document.querySelectorAll("[data-eden-editor] use"));
    svgUseElements.forEach((svg) => {
        if (svg.hasAttribute("xlink:href")) {
            const value = svg.getAttribute("xlink:href");
            if (!value)
                return;
            svg.setAttribute("href", value);
            svg.removeAttribute("xlink:href");
        }
    });
}
const SVG_HREF_ATTRIBUTES = ["xlink:href", "href"];
export function randomizeSvgSpriteCalls() {
    if (!isLocalhost())
        return;
    SVG_HREF_ATTRIBUTES.forEach((attribute) => {
        const svgUseElements = Array.from(document.querySelectorAll("[data-eden-editor] use"));
        svgUseElements.forEach((use) => {
            const href = use.getAttribute(attribute);
            if (!href)
                return;
            const url = new URL(href, window.location.origin);
            const { hash } = url;
            const random = Math.floor(Math.random() * 10);
            url.searchParams.set("r", String(random));
            url.hash = hash;
            use.setAttribute("href", url.toString());
        });
    });
}
export function cleanupRandomSvgSpriteCallParams() {
    if (!isLocalhost())
        return;
    const { lang } = window.EdenConfig;
    SVG_HREF_ATTRIBUTES.forEach((attribute) => {
        const svgUseElements = Array.from(document.querySelectorAll("[data-eden-editor] use"));
        svgUseElements.forEach((use) => {
            const href = use.getAttribute(attribute);
            if (!href)
                return;
            const url = new URL(href, window.location.origin);
            url.searchParams.delete("r");
            const { pathname, hash } = url;
            const path = pathname.replace(`/${lang}/`, "/");
            use.setAttribute(attribute, `${path}${hash}`);
        });
    });
}
