// @ts-check

const codeBlocks = document.querySelectorAll("pre");

if (codeBlocks) {
    try {
        codeBlocks?.forEach((codeBlock) => {
            if (codeBlock.classList.contains("skip-js")) return;
            codeBlock.style.position = "relative";

            const copyCodeButton = document.createElement("span");
            // copyCodeButton.style.position = "absolute";
            // copyCodeButton.style.top = "10px";
            // copyCodeButton.style.right = "10px";
            copyCodeButton.style.cursor = "pointer";
            // copyCodeButton.style.display = "none";

            copyCodeButton.addEventListener("click", () => {
                // console.log(codeBlock.innerText);
                // console.log(codeBlock.textContent);
                navigator.clipboard.writeText(codeBlock.innerText).then(() => {
                    window.alert("Code Copied!");
                });
            });

            const copyIcon = document.createElement("img");
            copyIcon.src = "/images/copy.png";
            copyIcon.width = 16;
            copyIcon.height = 16;

            copyCodeButton.appendChild(copyIcon);

            codeBlock.appendChild(copyCodeButton);
        });
    } catch (error) {}
}

window.addEventListener("click", (e) => {
    const cancelBlocks = document.querySelectorAll(".window-cancel");
    /** @type {HTMLElement} */ // @ts-ignore
    const targetEl = e.target;
    cancelBlocks.forEach((el) => {
        if (targetEl.closest(".window-cancel")) return;
        el.classList.add("hidden");
    });
});

const queryUrls = document.querySelectorAll("a.query-url");
queryUrls.forEach((urlEl) => {
    const urlHref = urlEl.getAttribute("href");

    if (!urlHref?.match(/\?/)) {
        urlEl.setAttribute("href", `${urlHref}${window.location.search}`);
    }
});
