// Dedicated permission-grant page for Autonomous Mode.
//
// Why this page exists instead of just calling chrome.permissions.request
// from the floating panel's chip click:
//
//   In MV3, chrome.permissions.request() only works inside a user-gesture
//   context. The gesture forwarded with chrome.runtime.sendMessage to a
//   service worker is inconsistent — different Chrome versions handle it
//   differently, and any awaited storage read in the SW handler consumes
//   the gesture window before request() can fire, so it silently fails
//   with no prompt and no error.
//
//   An extension page that the user lands on has its OWN guaranteed
//   gesture context: the click on the Enable button below is a fresh
//   activation that propagates straight to permissions.request(). This
//   path always works.

const btn = document.getElementById("grant");
const status = document.getElementById("status");

function setStatus(msg, kind = "") {
  status.textContent = msg;
  status.className = "status " + kind;
}

btn.addEventListener("click", async () => {
  btn.disabled = true;
  setStatus("Waiting for Chrome's permission dialog…");
  let granted = false;
  try {
    granted = await chrome.permissions.request({ permissions: ["debugger"] });
  } catch (err) {
    setStatus(`Chrome rejected the request: ${err.message}`, "err");
    btn.disabled = false;
    return;
  }

  if (!granted) {
    // User clicked Deny — don't auto-re-prompt next time.
    await chrome.storage.local.set({ _liAutonomousOffered: true });
    setStatus("You clicked Deny. To enable later: chrome://extensions → Nexus Connect → Details → Optional permissions → Debugger.", "err");
    btn.disabled = false;
    return;
  }

  // Permission granted — flip the flag and close this tab.
  await chrome.storage.local.set({
    _liAutonomousMode: true,
    _liAutonomousOffered: true,
    _liAutonomousExplicitlyDisabled: false,
  });
  setStatus("Autonomous Mode enabled. Closing this tab…", "ok");

  // Give the user a half-second to read the success message, then close.
  setTimeout(() => {
    try {
      // chrome.tabs.getCurrent then chrome.tabs.remove — works from an
      // extension page.
      chrome.tabs.getCurrent((tab) => {
        if (tab?.id != null) chrome.tabs.remove(tab.id);
        else window.close();
      });
    } catch {
      window.close();
    }
  }, 800);
});

// On load, check if the permission is already granted. If so, just flip the
// flag and close — no need to make the user click anything.
(async () => {
  try {
    const already = await chrome.permissions.contains({ permissions: ["debugger"] });
    if (already) {
      await chrome.storage.local.set({
        _liAutonomousMode: true,
        _liAutonomousOffered: true,
        _liAutonomousExplicitlyDisabled: false,
      });
      setStatus("Already granted — Autonomous Mode is on. Closing…", "ok");
      setTimeout(() => {
        chrome.tabs.getCurrent((tab) => {
          if (tab?.id != null) chrome.tabs.remove(tab.id);
          else window.close();
        });
      }, 600);
    }
  } catch { /* fall through to manual click */ }
})();
