// Consent popup — renders the AUTHORITATIVE run manifest the service worker
// built (with the extension's own token) and returns the user's decision. The
// requesting web page never touches this UI (it's an extension page), so it
// cannot fake an approval. See background.js handleCircuitMutate / askConsent.
(function () {
  "use strict";
  const req = new URLSearchParams(location.search).get("req");
  const $ = (id) => document.getElementById(id);

  const VERB = {
    like: "Like",
    comment: "Comment on",
    reply: "Reply to",
    retweet: "Repost",
    follow: "Follow",
    connect: "Connect with",
    message: "Message",
    dm: "DM",
    react: "React to",
  };

  let decided = false;
  function decide(approved) {
    if (decided) return;
    decided = true;
    try {
      chrome.runtime.sendMessage({ type: "consent-resolve", req, approved }, () => window.close());
    } catch {
      /* closing anyway */
    }
    setTimeout(() => window.close(), 300);
  }

  function actionRow(a) {
    const row = document.createElement("div");
    row.className = "act";
    const chan = a.channel ? String(a.channel).toUpperCase() + " · " : "";
    const verb = VERB[a.action] || a.action || "act on";
    const from = a.account ? ` — as ${a.account}` : "";
    row.textContent = `${chan}${verb} ${a.target || ""}${from}`.trim();
    return row;
  }

  if (!req) {
    $("title").textContent = "Invalid request";
    $("approve").style.display = "none";
    return;
  }

  chrome.runtime.sendMessage({ type: "consent-get", req }, (resp) => {
    if (!resp || !resp.ok) {
      $("title").textContent = "This request expired";
      $("summary").textContent = "Close this window and try again from the quest.";
      $("approve").style.display = "none";
      return;
    }
    const m = resp.manifest || {};
    if (resp.title) $("title").textContent = resp.title;
    $("summary").textContent = m.summary || "";
    const warns = Array.isArray(m.warnings) ? m.warnings : [];
    for (const t of warns) {
      const d = document.createElement("div");
      d.className = "warn";
      d.textContent = "⚠ " + t;
      $("warnings").appendChild(d);
    }
    const acts = Array.isArray(m.actions) ? m.actions : [];
    if (acts.length) {
      for (const a of acts) $("actions").appendChild(actionRow(a));
    } else {
      const d = document.createElement("div");
      d.className = "faint";
      d.textContent = "No concrete actions to preview yet.";
      $("actions").appendChild(d);
    }
  });

  $("approve").addEventListener("click", () => decide(true));
  $("decline").addEventListener("click", () => decide(false));
  // Closing the window without deciding counts as a decline.
  window.addEventListener("beforeunload", () => decide(false));
})();
