/* Adds a copy button to every .codeblock. Code stays selectable as a fallback. */
(function () {
  function build() {
    document.querySelectorAll(".codeblock").forEach((block) => {
      if (block.dataset.copy) return;
      block.dataset.copy = "1";
      const pre = block.querySelector("pre");
      if (!pre) return;
      const btn = document.createElement("button");
      btn.type = "button";
      btn.className = "copy-btn";
      btn.textContent = "Copy";
      btn.setAttribute("aria-label", "Copy code to clipboard");
      btn.addEventListener("click", async () => {
        try {
          await navigator.clipboard.writeText(pre.innerText);
          btn.textContent = "Copied";
        } catch (e) {
          btn.textContent = "Press Ctrl+C";
        }
        setTimeout(() => (btn.textContent = "Copy"), 1500);
      });
      block.appendChild(btn);
    });
  }
  document.addEventListener("DOMContentLoaded", build);
  document.addEventListener("partials:loaded", build);
})();
