const { convertHtmlToMarkdown } = htmlToSMD;

// Handle copy markdown button
document.getElementById("copy-markdown").addEventListener("click", async function() {
  const markdownOutput = document.getElementById("markdown-output");
  try {
    await navigator.clipboard.writeText(markdownOutput.textContent);
  } catch (err) {
    console.error('Failed to copy text: ', err);
  }
});

// Handle toggle between URL and HTML input
document.getElementById("input-html-toggle").addEventListener("change", function(e) {
  const urlInput = document.getElementById("url-input");
  const htmlInput = document.getElementById("html-input");
  
  if (e.target.checked) {
    urlInput.classList.add("hidden");
    htmlInput.classList.remove("hidden");
    urlInput.removeAttribute("required");
  } else {
    urlInput.classList.remove("hidden");
    htmlInput.classList.add("hidden");
    urlInput.setAttribute("required", "");
  }
});

function isValidUrl(string) {
  try {
    new URL(string);
    return true;
  } catch (_) {
    return false;
  }
}

document
  .getElementById("converter-form")
  .addEventListener("submit", async function (e) {
    e.preventDefault();

    const isHtmlInput = document.getElementById("input-html-toggle").checked;
    const urlInput = document.getElementById("url-input").value;
    const htmlInput = document.getElementById("html-input").value;
    const markdownOutput = document.getElementById("markdown-output");

    if (!isHtmlInput && !isValidUrl(urlInput)) {
      alert("Please enter a valid URL");
      return;
    }
    const extractMainContent = document.getElementById(
      "extract-main-content"
    ).checked;
    const refifyUrls = document.getElementById("refify-urls").checked;
    const enableTableColumnTracking = document.getElementById(
      "enable-table-column-tracking"
    ).checked;
    const websiteDomain = document.getElementById("website-domain").value;

    const options = {
      extractMainContent,
      refifyUrls,
      enableTableColumnTracking,
      websiteDomain: websiteDomain || undefined,
    };

    try {
      let htmlContent;
      if (isHtmlInput) {
        htmlContent = htmlInput;
      } else {
        // Fetch HTML content from the server
        const response = await fetch(
          `/fetch-html?url=${encodeURIComponent(urlInput)}`
        );
        if (!response.ok) {
          throw new Error("Failed to fetch HTML content");
        }
        htmlContent = await response.text();
      }

      // Convert HTML to Markdown
      const markdown = await convertHtmlToMarkdown(htmlContent, options);
      markdownOutput.textContent = markdown;
      document.getElementById("copy-markdown").disabled = false;
    } catch (error) {
      markdownOutput.textContent = "Error: " + error.message;
    }
  });