(() => {
  "use strict";
  const bridge = window.chrome && window.chrome.webview ? window.chrome.webview : null;
  function post(msg) { if (bridge) bridge.postMessage(msg); }

  let sourceUrl = "";

  function onHostMessage(e) {
    let msg;
    try { msg = typeof e.data === "string" ? JSON.parse(e.data) : e.data; } catch { return; }
    if (msg && msg.type === "reader.data") {
      sourceUrl = msg.url || "";
      document.getElementById("rtUrl").textContent = sourceUrl;
      const out = extract(msg.html || "", sourceUrl);
      if (!out) fail("Couldn't find a readable article on this page.");
      else render(out);
    }
  }
  if (bridge) bridge.addEventListener("message", onHostMessage);
  window.addEventListener("message", onHostMessage);
  post({ type: "reader.get" });

  function fail(text) {
    const wrap = document.getElementById("readerWrap");
    wrap.innerHTML = `<div class="reader-fail"><h2>No article found</h2><p>${text}</p></div>`;
  }

  // ---- Article extraction (self-contained, Nepali-friendly) ----
  function extract(html, url) {
    const doc = new DOMParser().parseFromString(html, "text/html");
    if (!doc.body) return null;

    // Candidates in priority order: semantic tags / class names used by most CMSs.
    const candidates = doc.querySelectorAll(
      "article, [role='main'], main, .post-content, .entry-content, .article-content, " +
      ".post, .article, .single-content, .content-area, .story-body, .story__content, " +
      "#article-body, .blog-post, .prose, .rich-text, .td-post-content, .elementor-widget-theme-post-content"
    );

    let best = null;
    let bestScore = -1;
    for (const el of candidates) {
      const score = scoreElement(el);
      if (score > bestScore) { bestScore = score; best = el; }
    }

    // Fallback: the container holding the most <p> text.
    if (!best) {
      const paras = doc.querySelectorAll("p");
      if (paras.length >= 3) {
        const parent = paras[0].parentElement;
        if (parent) best = parent;
      }
    }
    if (!best) return null;

    // Title: nearest h1 (inside candidate first), else document.title.
    let title = "";
    const h1 = best.querySelector("h1");
    if (h1) title = h1.textContent.trim();
    if (!title) {
      const anyH1 = doc.querySelector("h1");
      if (anyH1) title = anyH1.textContent.trim();
    }
    if (!title) title = (doc.title || "Untitled").trim();

    // Site name from the URL host.
    let site = "";
    try { site = new URL(url).hostname.replace(/^www\./, ""); } catch { site = ""; }

    // Byline / date when available.
    let byline = "";
    const by = best.querySelector("[rel='author'], .byline, .author, [class*='author-name']");
    if (by) byline = by.textContent.trim().replace(/\s+/g, " ");
    let dateStr = "";
    const time = best.querySelector("time, [datetime], .date, [class*='published'], [class*='post-date']");
    if (time) {
      const d = time.getAttribute("datetime") || time.textContent || "";
      const parsed = new Date(d);
      if (!isNaN(parsed)) dateStr = parsed.toLocaleDateString(undefined, { year: "numeric", month: "long", day: "numeric" });
    }

    // Clean the article: drop scripts, nav, ads, embeds of no value.
    best.querySelectorAll("script, style, iframe, form, button, nav, aside, .ad, .ads, .advertisement, " +
      ".social-share, .share, .related, .recommended, .comments, #comments, .newsletter, .subscribe, .promo")
      .forEach((n) => n.remove());

    // Normalize headings/paragraphs and preserve figure images.
    best.querySelectorAll("h1, h2, h3, h4, h5, h6").forEach((h) => {
      const lvl = Math.min(3, parseInt(h.tagName[1], 10));
      const nh = doc.createElement("h" + lvl);
      nh.textContent = h.textContent.trim();
      h.replaceWith(nh);
    });
    best.querySelectorAll("img").forEach((img) => {
      const src = img.getAttribute("src") || img.getAttribute("data-src") || "";
      if (!src) { img.remove(); return; }
      img.removeAttribute("srcset");
      img.removeAttribute("loading");
      img.removeAttribute("style");
      if (img.closest("a")) {
        // unwrap links around images
        const a = img.closest("a");
        a.parentNode.replaceChild(img, a);
      }
    });

    return { title, site, byline, dateStr, body: best.innerHTML };
  }

  function scoreElement(el) {
    const text = el.textContent || "";
    const pCount = el.querySelectorAll("p").length;
    const len = text.trim().length;
    let score = 0;
    score += Math.min(pCount, 20) * 8;
    score += Math.min(len / 200, 30);
    if (el.tagName === "ARTICLE") score += 10;
    if (el.tagName === "MAIN") score += 5;
    return score;
  }

  function render(a) {
    const wrap = document.getElementById("readerWrap");
    const art = document.createElement("article");
    art.className = "reader";
    const metaParts = [];
    if (a.site) metaParts.push(`<span>${a.site}</span>`);
    if (a.byline) metaParts.push(`<span class="dot">•</span><span>${a.byline}</span>`);
    if (a.dateStr) metaParts.push(`<span class="dot">•</span><span>${a.dateStr}</span>`);
    art.innerHTML = `
      <h1 class="reader-title">${escapeHtml(a.title)}</h1>
      <div class="reader-meta">${metaParts.join("")}</div>
      <div class="reader-body">${a.body}</div>`;
    wrap.innerHTML = "";
    wrap.appendChild(art);
  }

  function escapeHtml(s) {
    return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  }

  document.getElementById("openBtn").addEventListener("click", () => {
    if (sourceUrl) post({ type: "nav.url", url: sourceUrl });
  });
})();