import { matchingSelector } from "@devowl-wp/resolve-none-computed-style";
import { fastdom } from "@devowl-wp/web-scoped-css";

(window as any).rcbPoweredByCacheOuterHTML = "";

/**
 * Get the server-side-rendered powered by link.
 */
function getSsrPoweredByLink(id: string) {
    const originalPoweredLink = document.getElementById(id) as HTMLAnchorElement;
    const poweredLink = document.createElement("div");

    if ((window as any).rcbPoweredByCacheOuterHTML) {
        // We have cached the link as we remove it from the DOM
        poweredLink.innerHTML = (window as any).rcbPoweredByCacheOuterHTML;
    } else if (
        matchingSelector(originalPoweredLink, "a") &&
        originalPoweredLink.innerHTML.toLowerCase().indexOf("Real Cookie Banner")
    ) {
        (window as any).rcbPoweredByCacheOuterHTML = originalPoweredLink.outerHTML;
        poweredLink.innerHTML = (window as any).rcbPoweredByCacheOuterHTML;
        fastdom.mutate(() => originalPoweredLink.parentNode.removeChild(originalPoweredLink));
    }

    return poweredLink.children[0] as HTMLAnchorElement;
}

export { getSsrPoweredByLink };
