/**
 * browser-compat.js — cross-browser compatibility shim
 * Loaded first in Firefox (MV2) background scripts list.
 *
 * Normalises the API surface so service-worker.js can use
 * `chrome.action.*` regardless of whether we're in MV2 or MV3.
 */

// Shim chrome.action → chrome.browserAction for Firefox MV2 background pages.
// In Chrome/Edge MV3, chrome.action is already defined; this block is a no-op.
(function () {
  if (typeof chrome === 'undefined') return;

  // MV2: browserAction exists but action does not
  if (typeof chrome.action === 'undefined' && typeof chrome.browserAction !== 'undefined') {
    chrome.action = chrome.browserAction;
  }

  // Guard chrome.identity — Firefox does not support it.
  // Replace with a stub that returns a meaningful error.
  if (typeof chrome.identity === 'undefined') {
    chrome.identity = {
      getAuthToken: function (_opts, callback) {
        var err = { message: 'chrome.identity is not supported in Firefox' };
        // Make lastError available for a tick, then invoke callback
        chrome.runtime.lastError = err;
        if (typeof callback === 'function') {
          callback(undefined);
        }
        // Clear lastError after the tick so unrelated code is not affected
        setTimeout(function () { chrome.runtime.lastError = undefined; }, 0);
      }
    };
  }
})();
