(() => {
  "use strict";
  const bridge = window.chrome && window.chrome.webview ? window.chrome.webview : null;
  function post(msg) { if (bridge) bridge.postMessage(msg); }
  function toast(text) {
    const t = document.getElementById("toast");
    t.textContent = text;
    t.classList.add("show");
    setTimeout(() => t.classList.remove("show"), 1600);
  }

  function onHostMessage(e) {
    let msg;
    try { msg = typeof e.data === "string" ? JSON.parse(e.data) : e.data; } catch { return; }
    if (msg && msg.type === "source.data") {
      document.getElementById("srcUrl").textContent = msg.url || "(unknown URL)";
      const html = msg.html || "";
      document.getElementById("srcCode").innerHTML = highlight(html);
    }
  }
  if (bridge) bridge.addEventListener("message", onHostMessage);
  window.addEventListener("message", onHostMessage);
  post({ type: "source.get" });

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

  // Lightweight HTML syntax highlighting: comments, strings, tags, attributes.
  function highlight(raw) {
    const code = esc(raw);
    const lines = code.split("\n");
    return lines.map((line) => {
      let out = "";
      // comments
      line = line.replace(/(&lt;!--[\s\S]*?--&gt;)/g, '<span class="c">$1</span>');
      // strings inside tags
      line = line.replace(/(&quot;.*?&quot;|&#39;.*?&#39;)/g, '<span class="s">$1</span>');
      // attribute names
      line = line.replace(/([a-zA-Z-]+)(=)(?=&quot;|&#39;)/g, '<span class="a">$1</span>$2');
      // tags
      line = line.replace(/(&lt;\/?)([a-zA-Z][a-zA-Z0-9]*)/g, '$1<span class="t">$2</span>');
      line = line.replace(/(\/?&gt;)/g, '<span class="p">$1</span>');
      return line;
    }).join("\n");
  }

  document.getElementById("copyBtn").addEventListener("click", () => {
    const raw = document.getElementById("srcCode").textContent;
    navigator.clipboard && navigator.clipboard.writeText(raw).then(() => toast("Source copied to clipboard"), () => {});
  });
})();