/**
 * JavaScript to handle the "Copy for LLM" functionality.
 * It fetches the clean Markdown file (generated by the Python hook)
 * and copies it to the user's clipboard.
 */
document.addEventListener("DOMContentLoaded", function () {
  // We use event delegation to catch clicks on any element with the class
  document.body.addEventListener("click", function (e) {
    const button = e.target.closest(".copy-llm-button");
    if (!button) return;

    e.preventDefault();

    // Determine the path to the clean .md file
    // Example: /devops-delivery/index.html -> /devops-delivery/index.md
    // Example: /devops-delivery/ (with use_directory_urls) -> /devops-delivery/index.md
    let path = window.location.pathname;
    
    // Ensure we are fetching index.md if we're at a directory root
    if (path.endsWith("/")) {
      path += "index.md";
    } else if (path.endsWith(".html")) {
      path = path.replace(/\.html$/, ".md");
    } else {
      // Fallback for unexpected URL structures
      path += "index.md";
    }

    // Fetch the raw Markdown content
    fetch(path)
      .then((response) => {
        if (!response.ok) {
          throw new Error(`Could not find the Markdown source at ${path}`);
        }
        return response.text();
      })
      .then((text) => {
        // Copy the text to the clipboard
        navigator.clipboard.writeText(text).then(() => {
          // Provide visual feedback
          const originalTitle = button.getAttribute("title") || "Copy for LLM";
          const originalHTML = button.innerHTML;

          // Change icon to checkmark temporarily
          button.classList.add("copy-llm-button--success");
          button.setAttribute("title", "Copied to clipboard!");
          
          // If the button has an svg icon, we could swap it here.
          // For now, we rely on the title tooltip and a class change.

          setTimeout(() => {
            button.classList.remove("copy-llm-button--success");
            button.setAttribute("title", originalTitle);
          }, 2000);
        });
      })
      .catch((err) => {
        console.error("Copy for LLM failed:", err);
        // Simple alert as fallback for errors
        alert("Failed to copy for LLM context: " + err.message);
      });
  });
});
