(() => {
  "use strict";
  const bridge = window.chrome && window.chrome.webview ? window.chrome.webview : null;
  function post(msg) { if (bridge) bridge.postMessage(msg); }
  function ask(type) { post({ type }); }
  function toast(text) {
    const t = document.getElementById("toast");
    t.textContent = text;
    t.classList.add("show");
    setTimeout(() => t.classList.remove("show"), 1600);
  }
  function fmtBytes(n) {
    if (!n) return "—";
    const u = ["B", "KB", "MB", "GB"];
    let i = 0;
    while (n >= 1024 && i < u.length - 1) { n /= 1024; i++; }
    return n.toFixed(i === 0 ? 0 : 1) + " " + u[i];
  }

  // IMPORTANT: WebView2 delivers host→page messages on `window.chrome.webview`'s
  // message event — NOT the window's. Listen on both so this works in and out of WebView2.
  function onHostMessage(e) {
    let msg;
    try { msg = typeof e.data === "string" ? JSON.parse(e.data) : e.data; } catch { return; }
    if (msg && msg.type === "downloads.data") render(msg.items || []);
  }
  if (bridge) bridge.addEventListener("message", onHostMessage);
  window.addEventListener("message", onHostMessage);
  ask("downloads.get");

  function render(items) {
    const list = document.getElementById("downloadsList");
    if (!items.length) { list.innerHTML = '<div class="empty">No downloads yet — files you download land here and in your Downloads folder</div>'; return; }
    list.innerHTML = "";
    items.forEach((d) => {
      const row = document.createElement("div");
      row.className = "list-item";
      const status = d.done
        ? (d.state === "interrupted" ? '<span style="color:#d64545">Interrupted</span>' : '<span style="color:var(--accent)">Completed</span>')
        : `<span>${Math.round(d.progress)}%</span>`;
      row.innerHTML = `
        <span style="font-size:17px">⬇</span>
        <div style="min-width:0;flex:1">
          <div class="li-title">${esc(d.name)}</div>
          <div class="li-sub">${status}</div>
        </div>`;
      if (!d.done) {
        const bar = document.createElement("div");
        bar.style.cssText = "height:5px;width:120px;border-radius:3px;background:var(--border);overflow:hidden";
        bar.innerHTML = `<div style="height:100%;width:${Math.max(2, d.progress)}%;background:var(--accent)"></div>`;
        row.appendChild(bar);
      } else {
        const actions = document.createElement("div");
        actions.className = "li-actions";
        if (d.state !== "interrupted") {
          const open = document.createElement("button");
          open.className = "btn sm";
          open.textContent = "Open";
          open.addEventListener("click", () => post({ type: "downloads.open", path: d.path }));
          actions.appendChild(open);
        }
        const folder = document.createElement("button");
        folder.className = "btn sm";
        folder.textContent = "Folder";
        folder.addEventListener("click", () => post({ type: "downloads.openfolder", path: d.path }));
        actions.appendChild(folder);
        row.appendChild(actions);
      }
      list.appendChild(row);
    });
  }

  document.getElementById("refreshBtn").addEventListener("click", () => ask("downloads.get"));
  document.getElementById("clearBtn").addEventListener("click", () => {
    // Custom in-app confirm — no browser alert.
    document.getElementById("dlgOverlay").classList.remove("hidden");
  });
  document.getElementById("dlgOk").addEventListener("click", () => {
    document.getElementById("dlgOverlay").classList.add("hidden");
    post({ type: "downloads.clear" });
    toast("Downloads cleared");
  });
  document.getElementById("dlgCancel").addEventListener("click", () => {
    document.getElementById("dlgOverlay").classList.add("hidden");
  });

  function esc(s) {
    return String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
  }
})();