// ILoveMD Intelligent Webpage Content Extractor

(function () {
  function extractSemanticContent() {
    const title = document.querySelector("h1")?.innerText.trim() || document.title || "Webpage Document";
    const url = window.location.href;
    const metaDescription = document.querySelector('meta[name="description"]')?.getAttribute("content") || "";

    // Find main content container with semantic scoring
    const candidates = Array.from(
      document.querySelectorAll("article, [role='main'], main, .post-content, .article-content, .entry-content, #content, .content")
    );

    let mainContainer = document.body;
    if (candidates.length > 0) {
      // Pick container with highest paragraph text density
      candidates.sort((a, b) => {
        const textA = a.innerText.length;
        const textB = b.innerText.length;
        return textB - textA;
      });
      mainContainer = candidates[0];
    }

    const clone = mainContainer.cloneNode(true);

    // Noisy selectors to strip out
    const noiseSelectors = [
      "script", "style", "noscript", "iframe", "svg", "nav", "footer", "header", "aside",
      ".ad", ".ads", ".advertisement", ".banner", ".popup", ".modal", ".sidebar",
      ".comments", ".comment-list", ".related-posts", ".share-buttons", ".social-share",
      ".cookie-banner", ".newsletter-signup", ".author-bio", ".site-navigation"
    ];

    noiseSelectors.forEach((sel) => {
      clone.querySelectorAll(sel).forEach((el) => el.remove());
    });

    // Remove empty containers
    clone.querySelectorAll("div, section, span, p").forEach((el) => {
      if (!el.innerText.trim() && el.children.length === 0) {
        el.remove();
      }
    });

    return {
      title,
      url,
      description: metaDescription,
      html: clone.innerHTML,
    };
  }

  const data = extractSemanticContent();
  return data;
})();
