(function () {
  "use strict";

  const copiedLabel = "Kopiert";
  const copyLabel = "Kopieren";
  const resetDelayMs = 1600;

  function getCodeText(codeElement) {
    return codeElement.textContent.replace(/\n$/, "");
  }

  async function copyText(text) {
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text);
      return;
    }

    const textArea = document.createElement("textarea");
    textArea.value = text;
    textArea.setAttribute("readonly", "");
    textArea.style.position = "fixed";
    textArea.style.top = "-1000px";
    textArea.style.opacity = "0";
    document.body.appendChild(textArea);
    textArea.select();

    try {
      document.execCommand("copy");
    } finally {
      textArea.remove();
    }
  }

  function setButtonState(button, label, copied) {
    button.textContent = label;
    button.setAttribute("aria-label", label);
    button.classList.toggle("is-copied", copied);
  }

  function enhanceCodeBlock(preElement) {
    if (preElement.closest(".mtp-code-block")) {
      return;
    }

    const codeElement = preElement.querySelector("code");
    if (!codeElement || !getCodeText(codeElement).trim()) {
      return;
    }

    const wrapper = document.createElement("div");
    wrapper.className = "mtp-code-block";
    preElement.parentNode.insertBefore(wrapper, preElement);
    wrapper.appendChild(preElement);

    const button = document.createElement("button");
    button.type = "button";
    button.className = "mtp-copy-code-button";
    setButtonState(button, copyLabel, false);

    button.addEventListener("click", async () => {
      const originalLabel = button.textContent;
      button.disabled = true;

      try {
        await copyText(getCodeText(codeElement));
        setButtonState(button, copiedLabel, true);
        window.setTimeout(() => {
          button.disabled = false;
          setButtonState(button, copyLabel, false);
        }, resetDelayMs);
      } catch (error) {
        button.disabled = false;
        setButtonState(button, originalLabel || copyLabel, false);
      }
    });

    wrapper.appendChild(button);
  }

  function initCopyButtons() {
    document.querySelectorAll("#content pre").forEach(enhanceCodeBlock);
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", initCopyButtons, { once: true });
  } else {
    initCopyButtons();
  }
})();
