// ILoveMD Popup JavaScript Logic

document.addEventListener("DOMContentLoaded", async () => {
  // Tab Switcher Elements
  const tabWebpage = document.getElementById("nav-tab-webpage");
  const tabFile = document.getElementById("nav-tab-file");
  const viewWebpage = document.getElementById("view-webpage");
  const viewFile = document.getElementById("view-file");

  // Counter Badge Element
  const globalCounterVal = document.getElementById("global-counter-val");

  // Tab 1 Webpage Elements
  const mdTextarea = document.getElementById("md-textarea");
  const convertBtn = document.getElementById("convert-page-btn");
  const tokenGpt = document.getElementById("token-gpt");
  const wordCount = document.getElementById("word-count");
  const btnCopy = document.getElementById("btn-copy");
  const btnDownload = document.getElementById("btn-download");
  const btnFrontmatter = document.getElementById("btn-frontmatter");
  const btnHeadings = document.getElementById("btn-headings");
  const btnClean = document.getElementById("btn-clean");
  const toast = document.getElementById("toast");

  // Tab 2 File Convert Elements
  const dropzone = document.getElementById("file-dropzone");
  const fileInput = document.getElementById("file-input");
  const fileStatusText = document.getElementById("file-status-text");
  const btnDownloadFileMd = document.getElementById("btn-download-file-md");
  const fileMdTextarea = document.getElementById("file-md-textarea");

  let activeTitle = "document.md";
  let activeConvertedFilename = "converted.md";

  function showToast(msg) {
    toast.textContent = msg;
    toast.style.display = "block";
    setTimeout(() => {
      toast.style.display = "none";
    }, 2500);
  }

  function updateMetrics() {
    const text = mdTextarea.value || "";
    const chars = text.length;
    const words = text.trim() ? text.trim().split(/\s+/).length : 0;
    const tokens = Math.ceil(chars / 3.8);

    tokenGpt.textContent = `GPT-4: ~${tokens} tokens`;
    wordCount.textContent = words;
  }

  // Ping Global Document Counter API Endpoint
  async function pingGlobalCounter(amount = 1) {
    try {
      const res = await fetch("https://ilovemd.online/api/counter", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ amount }),
      });
      const data = await res.json();
      if (data && data.count) {
        globalCounterVal.textContent = data.count;
      }
    } catch {
      // Fallback local increment
      const current = parseInt(globalCounterVal.textContent || "687", 10);
      globalCounterVal.textContent = current + amount;
    }
  }

  async function fetchInitialGlobalCount() {
    try {
      const res = await fetch("https://ilovemd.online/api/counter");
      const data = await res.json();
      if (data && data.count) {
        globalCounterVal.textContent = data.count;
      }
    } catch {
      globalCounterVal.textContent = "687";
    }
  }

  fetchInitialGlobalCount();

  mdTextarea.addEventListener("input", updateMetrics);

  // Tab Switching Handler
  tabWebpage.addEventListener("click", () => {
    tabWebpage.classList.add("active");
    tabFile.classList.remove("active");
    viewWebpage.style.display = "flex";
    viewFile.style.display = "none";
  });

  tabFile.addEventListener("click", () => {
    tabFile.classList.add("active");
    tabWebpage.classList.remove("active");
    viewFile.style.display = "flex";
    viewWebpage.style.display = "none";
  });

  // Load any previously saved/context menu converted Markdown
  try {
    const stored = await chrome.storage.local.get(["lastConvertedMd", "lastTitle"]);
    if (stored.lastConvertedMd) {
      mdTextarea.value = stored.lastConvertedMd;
      if (stored.lastTitle) activeTitle = stored.lastTitle.replace(/\.[^/.]+$/, "") + ".md";
      updateMetrics();
    }
  } catch (e) {
    console.error(e);
  }

  // Convert Active Tab Webpage to Markdown
  convertBtn.addEventListener("click", async () => {
    convertBtn.textContent = "⌛ Extracting & Cleaning Webpage...";
    convertBtn.disabled = true;

    try {
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      if (!tab || !tab.id) {
        showToast("❌ No active webpage tab found");
        return;
      }

      if (tab.url && (tab.url.startsWith("chrome://") || tab.url.startsWith("chrome-extension://") || tab.url.startsWith("edge://"))) {
        showToast("⚠️ Browser system pages restricted");
        mdTextarea.value = `# ${tab.title || "Browser System Page"}\n\n*Note*: Chrome security restricts script execution on internal system pages (${tab.url}). Please open any regular website (e.g. wikipedia.org, github.com, news site) to convert live webpages to Markdown!`;
        updateMetrics();
        return;
      }

      activeTitle = (tab.title || "webpage").replace(/[^a-zA-Z0-9_\-]/g, "_") + ".md";

      // Execute content script to pull DOM
      const results = await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: () => {
          const title = document.querySelector("h1")?.innerText.trim() || document.title || "Webpage Document";
          const url = window.location.href;
          const metaDesc = document.querySelector('meta[name="description"]')?.getAttribute("content") || "";

          const mainEl = document.querySelector("article, [role='main'], main, .post-content, .article-content, #content") || document.body;
          const clone = mainEl.cloneNode(true);

          const stripSelectors = [
            "script", "style", "noscript", "iframe", "svg", "nav", "footer", "header", "aside",
            ".ad", ".ads", ".sidebar", ".comments", ".cookie-banner", ".share-buttons"
          ];
          stripSelectors.forEach((s) => clone.querySelectorAll(s).forEach((el) => el.remove()));

          return { title, url, description: metaDesc, html: clone.innerHTML, text: clone.innerText };
        },
      });

      if (results && results[0] && results[0].result) {
        const data = results[0].result;
        let md = `# ${data.title || tab.title}\n\n*Source*: [${data.url}](${data.url})\n`;
        if (data.description) md += `*Summary*: ${data.description}\n`;
        md += `\n---\n\n`;

        const converter = window.ILoveMDConverter || globalThis.ILoveMDConverter;
        if (converter && typeof converter.convertHtmlToMarkdown === "function") {
          md += await converter.convertHtmlToMarkdown(data.html);
        } else {
          md += data.text || data.html.replace(/<[^>]+>/g, " ");
        }

        // Clean extra newlines
        md = md.replace(/\n{3,}/g, "\n\n").trim();
        mdTextarea.value = md;
        await chrome.storage.local.set({ lastConvertedMd: md, lastTitle: activeTitle });
        updateMetrics();
        pingGlobalCounter(1);
        showToast("✓ Webpage Converted!");
      }
    } catch (err) {
      console.error("Conversion error", err);
      showToast("❌ Unable to read webpage");
    } finally {
      convertBtn.textContent = "⚡ Convert Active Page to Markdown";
      convertBtn.disabled = false;
    }
  });

  // Action Tools (Tab 1)
  btnCopy.addEventListener("click", () => {
    navigator.clipboard.writeText(mdTextarea.value);
    showToast("✓ Copied to Clipboard!");
  });

  btnDownload.addEventListener("click", () => {
    const blob = new Blob([mdTextarea.value], { type: "text/markdown;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = activeTitle.endsWith(".md") ? activeTitle : `${activeTitle}.md`;
    a.click();
    URL.revokeObjectURL(url);
    showToast("✓ Downloaded .MD File!");
  });

  btnFrontmatter.addEventListener("click", () => {
    const text = mdTextarea.value;
    const tokens = Math.ceil(text.length / 3.8);
    const dateStr = new Date().toISOString().split("T")[0];
    const yaml = `---\ntitle: "${activeTitle.replace(/\.md$/, "")}"\ndate: ${dateStr}\ntokens_estimated: ${tokens}\ntags: ["web-ingest", "rag-ready"]\n---\n\n`;
    mdTextarea.value = yaml + text.replace(/^---[\s\S]*?---\n*/, "");
    updateMetrics();
    showToast("✓ YAML Frontmatter Injected!");
  });

  btnHeadings.addEventListener("click", () => {
    const lines = mdTextarea.value.split("\n");
    const cleaned = lines
      .map((l) => {
        if (/^#+\s+/.test(l)) {
          return l.replace(/<[^>]+>/g, "").trim();
        }
        return l;
      })
      .join("\n")
      .replace(/\n{3,}/g, "\n\n");

    mdTextarea.value = cleaned;
    updateMetrics();
    showToast("✓ Headings Normalized!");
  });

  btnClean.addEventListener("click", () => {
    let text = mdTextarea.value;
    text = text
      .replace(/<[^>]+>/g, "")
      .replace(/&nbsp;/gi, " ")
      .replace(/[\u200B-\u200D\uFEFF]/g, "")
      .replace(/[ \t]+$/gm, "")
      .replace(/\n{3,}/g, "\n\n")
      .trim();

    mdTextarea.value = text;
    updateMetrics();
    showToast("✓ HTML Noise Cleaned!");
  });

  // Tab 2 File Upload Handling
  dropzone.addEventListener("click", () => fileInput.click());

  dropzone.addEventListener("dragover", (e) => {
    e.preventDefault();
    dropzone.style.backgroundColor = "#f4f4f5";
  });

  dropzone.addEventListener("dragleave", () => {
    dropzone.style.backgroundColor = "#ffffff";
  });

  dropzone.addEventListener("drop", async (e) => {
    e.preventDefault();
    dropzone.style.backgroundColor = "#ffffff";
    if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
      await processFile(e.dataTransfer.files[0]);
    }
  });

  fileInput.addEventListener("change", async (e) => {
    if (e.target.files && e.target.files.length > 0) {
      await processFile(e.target.files[0]);
    }
  });

  async function processFile(file) {
    fileStatusText.textContent = `⌛ Parsing ${file.name}...`;
    activeConvertedFilename = `${file.name.replace(/\.[^/.]+$/, "")}.md`;

    try {
      let mdResult = "";
      if (typeof convertFileToMarkdownInExtension !== "undefined") {
        mdResult = await convertFileToMarkdownInExtension(file);
      } else {
        const text = await file.text();
        mdResult = `# File: ${file.name}\n\n${text}`;
      }

      fileMdTextarea.value = mdResult;
      fileStatusText.textContent = `✓ Converted: ${file.name}`;
      btnDownloadFileMd.style.display = "block";
      pingGlobalCounter(1);
      showToast(`✓ ${file.name} Converted!`);
    } catch (err) {
      console.error(err);
      fileStatusText.textContent = `❌ Error converting ${file.name}`;
    }
  }

  btnDownloadFileMd.addEventListener("click", () => {
    const blob = new Blob([fileMdTextarea.value], { type: "text/markdown;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = activeConvertedFilename;
    a.click();
    URL.revokeObjectURL(url);
    showToast("✓ Downloaded .MD File!");
  });
});
