/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	// The require scope
/******/ 	var __webpack_require__ = {};
/******/ 	
/************************************************************************/
/******/ 	/* webpack/runtime/make namespace object */
/******/ 	(() => {
/******/ 		// define __esModule on exports
/******/ 		__webpack_require__.r = (exports) => {
/******/ 			if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 				Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 			}
/******/ 			Object.defineProperty(exports, '__esModule', { value: true });
/******/ 		};
/******/ 	})();
/******/ 	
/************************************************************************/
var __webpack_exports__ = {};
/*!************************************!*\
  !*** ./extension/js/background.js ***!
  \************************************/
__webpack_require__.r(__webpack_exports__);
function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
// js/background.js
// V2.0.0 - Updated to support Unified Credits, Inline Auth, and Account Deletion logic.

var creating;

/**
 * Traffic controller: Routes messages between UI and the Firebase-enabled Offscreen Document.
 */
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  if (message.target === 'background') {
    // --- 1. MOBILE & UI ACTIONS (Handled directly in Service Worker) ---

    if (message.type === 'triggerMobileAnnotation') {
      var tabId = message.data.tabId;
      if (chrome.scripting && chrome.scripting.executeScript) {
        chrome.scripting.executeScript({
          target: {
            tabId: tabId
          },
          func: function func() {
            return window.getSelection().toString();
          }
        }, function (results) {
          if (chrome.runtime.lastError || !results || !results[0] || !results[0].result) {
            console.log("No text selected or script failed.");
            return;
          }
          var selectedText = results[0].result;
          chrome.tabs.get(tabId, function (tab) {
            return openCreationWindow(tab, selectedText);
          });
        });
      } else {
        console.error("Scripting API not available. Check manifest permissions.");
      }
      return;
    }
    if (message.type === 'openAnnotationViewer') {
      var viewerUrl = chrome.runtime.getURL('html/annotation_viewer.html');
      var urlWithParams = "".concat(viewerUrl, "?urlId=").concat(message.data.urlId, "&anchorId=").concat(message.data.anchorId, "&anchorText=").concat(encodeURIComponent(message.data.anchorText), "&annotations=").concat(encodeURIComponent(message.data.annotations), "&tabId=").concat(sender.tab.id);
      if (typeof chrome.windows !== 'undefined') {
        chrome.windows.create({
          url: urlWithParams,
          type: 'popup',
          width: 800,
          height: 700
        });
      } else {
        chrome.tabs.create({
          url: urlWithParams
        });
      }
      return;
    }
    if (message.type === 'updateTooltip') {
      chrome.action.setTitle({
        title: message.data.text
      });
      return;
    }
    if (message.type === 'reloadTab') {
      if (message.data.tabId) chrome.tabs.reload(message.data.tabId);
      return;
    }

    // --- 2. BACKEND ACTIONS (Forwarded to Offscreen/Firebase) ---

    // V2 WHITELIST: Added 'getUserData' (for unified credits) and 'requestAccountDeletion'
    var validBackendActions = ['registerUser', 'signInUser', 'getAuthStatus', 'signOutUser', 'getUserProfile', 'getUserData', 'createAnnotation', 'forwardAnnotation', 'rejectAnnotation', 'reportAnnotation', 'getAnnotationsForUrl', 'setUsername', 'checkInteraction', 'deleteAnnotation', 'requestAccountDeletion', 'resetPassword', 'updateUserProfile', 'checkProfileViews', 'fetchUserHistory'];
    if (validBackendActions.includes(message.type)) {
      // STRICT PRESERVATION: Passing message.data exactly as the original code did
      // to ensure no payload nesting bugs occur in offscreen.js.
      sendMessageToOffscreen(message.type, message.data).then(sendResponse)["catch"](function (error) {
        console.error("V2 Backend Error:", message.type, error);
        sendResponse({
          success: false,
          error: error.message
        });
      });
      return true; // Keep message channel open for async response
    }
  }
  return false;
});

/**
 * Ensures the Offscreen Document (the DOM environment for Firebase) is active.
 */
function setupOffscreenDocument(_x) {
  return _setupOffscreenDocument.apply(this, arguments);
}
/**
 * Helper function to securely send a message to our offscreen document
 */
function _setupOffscreenDocument() {
  _setupOffscreenDocument = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(path) {
    var offscreenUrl, existingContexts, existingTabs, _t;
    return _regenerator().w(function (_context) {
      while (1) switch (_context.p = _context.n) {
        case 0:
          offscreenUrl = chrome.runtime.getURL(path);
          if (!(typeof chrome.offscreen !== 'undefined')) {
            _context.n = 10;
            break;
          }
          _context.p = 1;
          _context.n = 2;
          return chrome.runtime.getContexts({
            contextTypes: ['OFFSCREEN_DOCUMENT'],
            documentUrls: [offscreenUrl]
          });
        case 2:
          existingContexts = _context.v;
          if (!(existingContexts.length > 0)) {
            _context.n = 3;
            break;
          }
          return _context.a(2);
        case 3:
          if (!creating) {
            _context.n = 5;
            break;
          }
          _context.n = 4;
          return creating;
        case 4:
          _context.n = 7;
          break;
        case 5:
          creating = chrome.offscreen.createDocument({
            url: path,
            reasons: ['IFRAME_SCRIPTING'],
            justification: 'Firebase SDK needs a DOM environment to initialize'
          });
          _context.n = 6;
          return creating;
        case 6:
          creating = null;
        case 7:
          _context.n = 9;
          break;
        case 8:
          _context.p = 8;
          _t = _context.v;
          console.log("Offscreen API failed, falling back to tab strategy.");
        case 9:
          return _context.a(2);
        case 10:
          _context.n = 11;
          return chrome.tabs.query({
            url: offscreenUrl
          });
        case 11:
          existingTabs = _context.v;
          if (!(existingTabs.length > 0)) {
            _context.n = 12;
            break;
          }
          return _context.a(2);
        case 12:
          _context.n = 13;
          return chrome.tabs.create({
            url: offscreenUrl,
            active: false,
            pinned: true
          });
        case 13:
          return _context.a(2);
      }
    }, _callee, null, [[1, 8]]);
  }));
  return _setupOffscreenDocument.apply(this, arguments);
}
function sendMessageToOffscreen(_x2, _x3) {
  return _sendMessageToOffscreen.apply(this, arguments);
} // --- CONTEXT MENUS & INITIALIZATION ---
function _sendMessageToOffscreen() {
  _sendMessageToOffscreen = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(type, data) {
    return _regenerator().w(function (_context2) {
      while (1) switch (_context2.n) {
        case 0:
          if (!creating) {
            _context2.n = 1;
            break;
          }
          _context2.n = 1;
          return creating;
        case 1:
          _context2.n = 2;
          return setupOffscreenDocument('html/offscreen.html');
        case 2:
          return _context2.a(2, new Promise(function (resolve, reject) {
            chrome.runtime.sendMessage({
              type: type,
              target: 'offscreen',
              data: data
            }, function (response) {
              if (chrome.runtime.lastError) {
                console.error("Messaging error:", chrome.runtime.lastError.message);
                reject(chrome.runtime.lastError);
              } else {
                resolve(response);
              }
            });
          }));
      }
    }, _callee2);
  }));
  return _sendMessageToOffscreen.apply(this, arguments);
}
function createContextMenu() {
  chrome.contextMenus.create({
    id: "create-anotato-annotation",
    title: "Create Anotato Annotation",
    contexts: ["selection"]
  }, function () {
    if (chrome.runtime.lastError) {/* Ignore duplicates */}
  });
}
chrome.runtime.onInstalled.addListener(function (details) {
  createContextMenu();
  if (details.reason === 'install') {
    var token = 'inst_' + Date.now().toString(36) + Math.random().toString(36).substring(2);
    chrome.storage.local.set({
      installToken: token
    });
  }
});
chrome.runtime.onStartup.addListener(function () {
  return createContextMenu();
});
chrome.contextMenus.onClicked.addListener(function (info, tab) {
  if (info.menuItemId === "create-anotato-annotation") {
    openCreationWindow(tab, info.selectionText);
  }
});
function openCreationWindow(tab, selectionText) {
  if (!selectionText || !tab) return;
  var pageUrl = tab.url;
  var creationUrl = chrome.runtime.getURL('html/create_annotation.html');
  var urlWithParams = "".concat(creationUrl, "?text=").concat(encodeURIComponent(selectionText), "&url=").concat(encodeURIComponent(pageUrl), "&tabId=").concat(tab.id);
  if (typeof chrome.windows !== 'undefined') {
    chrome.windows.create({
      url: urlWithParams,
      type: 'popup',
      width: 700,
      height: 550
    });
  } else {
    chrome.tabs.create({
      url: urlWithParams
    });
  }
}
/******/ })()
;
//# sourceMappingURL=background.js.map