(() => {
  "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 esc(s) {
    return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;").replace(/'/g, "&#39;");
  }

  function onHostMessage(e) {
    let msg;
    try { msg = typeof e.data === "string" ? JSON.parse(e.data) : e.data; } catch { return; }
    if (msg && msg.type === "permissions.data") render(msg.items || []);
  }
  if (bridge) bridge.addEventListener("message", onHostMessage);
  window.addEventListener("message", onHostMessage);
  ask("permissions.get");

  function render(groups) {
    const list = document.getElementById("permList");
    document.getElementById("permEmpty").style.display = groups.length ? "none" : "block";
    list.innerHTML = "";
    groups.forEach((g) => {
      const card = document.createElement("div");
      card.className = "card";
      card.style.marginBottom = "12px";
      const head = document.createElement("div");
      head.style.cssText = "display:flex;align-items:center;justify-content:space-between;padding:14px 18px;border-bottom:1px solid var(--border)";
      head.innerHTML = `<div style="display:flex;align-items:center;gap:10px;min-width:0">
                          <span style="width:26px;height:26px;border-radius:50%;background:var(--hover);display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;color:var(--fg);flex-shrink:0">${esc((g.host || "?").charAt(0).toUpperCase())}</span>
                          <div style="min-width:0">
                            <div style="font-size:13.5px;font-weight:600">${esc(g.host)}</div>
                          </div>
                        </div>`;
      card.appendChild(head);
      (g.permissions || []).forEach((p) => {
        const row = document.createElement("div");
        row.className = "row";
        row.style.padding = "10px 18px";
        row.innerHTML = `
          <div>
            <div class="r-label" style="font-size:13px">${esc(p.kind)}</div>
          </div>
          <div class="r-ctrl pill-group" style="gap:4px">
            <button class="pill sm-pill ${p.state === 'allow' ? 'active' : ''}" data-state="allow">Allow</button>
            <button class="pill sm-pill ${p.state === 'deny' ? 'active' : ''}" data-state="deny">Block</button>
          </div>`;
        const style = document.createElement("style");
        style.textContent = ".sm-pill{padding:5px 12px;font-size:11.5px}";
        document.head.appendChild(style);
        row.querySelectorAll(".pill").forEach((b) => {
          b.addEventListener("click", () => {
            post({ type: "permissions.set", kind: p.kind, host: g.host, state: b.dataset.state });
            toast(`${p.kind} for ${g.host}: ${b.dataset.state === "allow" ? "Allowed" : "Blocked"}`);
          });
        });
        card.appendChild(row);
      });
      list.appendChild(card);
    });
  }

  document.getElementById("resetBtn").addEventListener("click", () => {
    document.getElementById("dlgOverlay").classList.remove("hidden");
  });
  document.getElementById("dlgCancel").addEventListener("click", () => {
    document.getElementById("dlgOverlay").classList.add("hidden");
  });
  document.getElementById("dlgOk").addEventListener("click", () => {
    document.getElementById("dlgOverlay").classList.add("hidden");
    post({ type: "permissions.clear" });
    toast("All permissions reset");
  });
})();