document.addEventListener('DOMContentLoaded', () => { // Select all
 elements that contain code blocks
  const preBlocks = document.querySelectorAll('pre');

  const copyIcon =
    '';
  const checkIcon =
    '';

  preBlocks.forEach((pre) => {
    // Wrap the 
 so the button can sit outside its horizontal
    // scroll container — a child of pre would scroll along with the code.
    const wrapper = document.createElement('div');
    wrapper.className = 'code-block-wrapper';
    pre.parentNode.insertBefore(wrapper, pre);
    wrapper.appendChild(pre);

    // Create the copy button
    const button = document.createElement('button');
    button.innerHTML = copyIcon;
    button.className = 'copy-code-btn';
    button.setAttribute('aria-label', 'Copy code');
    button.setAttribute('title', 'Copy code');

    wrapper.appendChild(button);

    button.addEventListener('click', async () => {
      // Find the  element within the 
      const code = pre.querySelector('code');
      if (!code) return;

      // Get the text content, removing any leading/trailing whitespace
      const text = code.innerText;

      try {
        if (navigator.clipboard && window.isSecureContext) {
          // Modern Async Clipboard API
          await navigator.clipboard.writeText(text);
        } else {
          // Fallback for insecure contexts (like local network IPs via HTTP)
          const textArea = document.createElement('textarea');
          textArea.value = text;

          // Move outside the screen to make it invisible
          textArea.style.position = 'absolute';
          textArea.style.left = '-999999px';

          document.body.appendChild(textArea);
          textArea.select();

          document.execCommand('copy');
          textArea.remove();
        }

        // Add visual feedback
        button.innerHTML = checkIcon;
        button.classList.add('copied');
        button.setAttribute('aria-label', 'Copied');
        button.setAttribute('title', 'Copied!');

        // Revert back after 2 seconds
        setTimeout(() => {
          button.innerHTML = copyIcon;
          button.classList.remove('copied');
          button.setAttribute('aria-label', 'Copy code');
          button.setAttribute('title', 'Copy code');
        }, 2000);
      } catch (err) {
        console.error('Failed to copy code: ', err);
      }
    });
  });
});