// NOTE: Pelican's fenced_code puts language-* on , not
,
// so we select the  elements and walk up to the 
.
const codeBlocks = document.querySelectorAll('code[class*="language-"]');

console.log("copy-code.js loaded, found:", codeBlocks.length);

codeBlocks.forEach((code) => {
  const pre = code.closest("pre");
  if (!pre) return;

  const button = document.createElement("button");
  button.className = "copy-to-clipboard-button";
  button.type = "button";
  button.textContent = "Copy";

  button.addEventListener("click", async () => {
    try {
      await navigator.clipboard.writeText(code.innerText);
      button.textContent = "Copied";
    } catch {
      button.textContent = "Failed";
    }
    setTimeout(() => (button.textContent = "Copy"), 1500);
  });

  pre.appendChild(button);
});