// ── WebAssets License Boot ──────────────────────────────────────────────────
importScripts('wa_license.js');

self.addEventListener('activate', () => {
    wa_isLicenseValid().then(valid => {
        if (!valid) wa_clearToken();
    });
});

// ── Heartbeat Polling ───────────────────────────────────────────────────────
chrome.alarms.create('waHeartbeat', { periodInMinutes: 60 });
chrome.alarms.onAlarm.addListener((alarm) => {
    if (alarm.name === 'waHeartbeat') {
        wa_checkServerStatus();
    }
});
// ────────────────────────────────────────────────────────────────────────────

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
    if (msg.type === 'CHECK_LICENSE') {
        wa_isLicenseValid().then(async (valid) => {
            const expiry = valid ? await wa_getExpiryMs() : 0;
            sendResponse({ licensed: valid, expiresAt: expiry });
        });
        return true;
    }
    if (msg.type === 'ACTIVATE_LICENSE') {
        wa_activate(msg.code).then(sendResponse);
        return true;
    }
    if (msg.type === 'DEACTIVATE_LICENSE') {
        wa_clearToken().then(() => sendResponse({ success: true }));
        return true;
    }
});
// ────────────────────────────────────────────────────────────────────────────

chrome.action.onClicked.addListener(() => {
  const urls = [
    "by WebAssets",
  ];

  urls.forEach((url) => {
    // chrome.tabs.create({ url: url });
    console.log(url);
  });
});
(() => {
  "use strict";
  const e = {
    base_api_url: "",
    save_user_api_url: "",
    save_install_api_url: "",
    save_activity_api_url: "",
    auth_user_api_url: "",
  };
  function t(e) {
    return (
      (t =
        "function" == typeof Symbol && "symbol" == typeof Symbol.iterator
          ? function (e) {
              return typeof e;
            }
          : function (e) {
              return e &&
                "function" == typeof Symbol &&
                e.constructor === Symbol &&
                e !== Symbol.prototype
                ? "symbol"
                : typeof e;
            }),
      t(e)
    );
  }
  function r() {
    /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ r =
      function () {
        return e;
      };
    var e = {},
      n = Object.prototype,
      a = n.hasOwnProperty,
      o =
        Object.defineProperty ||
        function (e, t, r) {
          e[t] = r.value;
        },
      s = "function" == typeof Symbol ? Symbol : {},
      c = s.iterator || "@@iterator",
      i = s.asyncIterator || "@@asyncIterator",
      u = s.toStringTag || "@@toStringTag";
    function p(e, t, r) {
      return (
        Object.defineProperty(e, t, {
          value: r,
          enumerable: !0,
          configurable: !0,
          writable: !0,
        }),
        e[t]
      );
    }
    try {
      p({}, "");
    } catch (e) {
      p = function (e, t, r) {
        return (e[t] = r);
      };
    }
    function l(e, t, r, n) {
      var a = t && t.prototype instanceof _ ? t : _,
        s = Object.create(a.prototype),
        c = new I(n || []);
      return o(s, "_invoke", { value: S(e, r, c) }), s;
    }
    function d(e, t, r) {
      try {
        return { type: "normal", arg: e.call(t, r) };
      } catch (e) {
        return { type: "throw", arg: e };
      }
    }
    e.wrap = l;
    var h = {};
    function _() {}
    function f() {}
    function m() {}
    var v = {};
    p(v, c, function () {
      return this;
    });
    var g = Object.getPrototypeOf,
      y = g && g(g(L([])));
    y && y !== n && a.call(y, c) && (v = y);
    var w = (m.prototype = _.prototype = Object.create(v));
    function b(e) {
      ["next", "throw", "return"].forEach(function (t) {
        p(e, t, function (e) {
          return this._invoke(t, e);
        });
      });
    }
    function x(e, r) {
      function n(o, s, c, i) {
        var u = d(e[o], e, s);
        if ("throw" !== u.type) {
          var p = u.arg,
            l = p.value;
          return l && "object" == t(l) && a.call(l, "__await")
            ? r.resolve(l.__await).then(
                function (e) {
                  n("next", e, c, i);
                },
                function (e) {
                  n("throw", e, c, i);
                }
              )
            : r.resolve(l).then(
                function (e) {
                  (p.value = e), c(p);
                },
                function (e) {
                  return n("throw", e, c, i);
                }
              );
        }
        i(u.arg);
      }
      var s;
      o(this, "_invoke", {
        value: function (e, t) {
          function a() {
            return new r(function (r, a) {
              n(e, t, r, a);
            });
          }
          return (s = s ? s.then(a, a) : a());
        },
      });
    }
    function S(e, t, r) {
      var n = "suspendedStart";
      return function (a, o) {
        if ("executing" === n) throw new Error("Generator is already running");
        if ("completed" === n) {
          if ("throw" === a) throw o;
          return D();
        }
        for (r.method = a, r.arg = o; ; ) {
          var s = r.delegate;
          if (s) {
            var c = k(s, r);
            if (c) {
              if (c === h) continue;
              return c;
            }
          }
          if ("next" === r.method) r.sent = r._sent = r.arg;
          else if ("throw" === r.method) {
            if ("suspendedStart" === n) throw ((n = "completed"), r.arg);
            r.dispatchException(r.arg);
          } else "return" === r.method && r.abrupt("return", r.arg);
          n = "executing";
          var i = d(e, t, r);
          if ("normal" === i.type) {
            if (((n = r.done ? "completed" : "suspendedYield"), i.arg === h))
              continue;
            return { value: i.arg, done: r.done };
          }
          "throw" === i.type &&
            ((n = "completed"), (r.method = "throw"), (r.arg = i.arg));
        }
      };
    }
    function k(e, t) {
      var r = t.method,
        n = e.iterator[r];
      if (void 0 === n)
        return (
          (t.delegate = null),
          ("throw" === r &&
            e.iterator.return &&
            ((t.method = "return"),
            (t.arg = void 0),
            k(e, t),
            "throw" === t.method)) ||
            ("return" !== r &&
              ((t.method = "throw"),
              (t.arg = new TypeError(
                "The iterator does not provide a '" + r + "' method"
              )))),
          h
        );
      var a = d(n, e.iterator, t.arg);
      if ("throw" === a.type)
        return (t.method = "throw"), (t.arg = a.arg), (t.delegate = null), h;
      var o = a.arg;
      return o
        ? o.done
          ? ((t[e.resultName] = o.value),
            (t.next = e.nextLoc),
            "return" !== t.method && ((t.method = "next"), (t.arg = void 0)),
            (t.delegate = null),
            h)
          : o
        : ((t.method = "throw"),
          (t.arg = new TypeError("iterator result is not an object")),
          (t.delegate = null),
          h);
    }
    function T(e) {
      var t = { tryLoc: e[0] };
      1 in e && (t.catchLoc = e[1]),
        2 in e && ((t.finallyLoc = e[2]), (t.afterLoc = e[3])),
        this.tryEntries.push(t);
    }
    function P(e) {
      var t = e.completion || {};
      (t.type = "normal"), delete t.arg, (e.completion = t);
    }
    function I(e) {
      (this.tryEntries = [{ tryLoc: "root" }]),
        e.forEach(T, this),
        this.reset(!0);
    }
    function L(e) {
      if (e) {
        var t = e[c];
        if (t) return t.call(e);
        if ("function" == typeof e.next) return e;
        if (!isNaN(e.length)) {
          var r = -1,
            n = function t() {
              for (; ++r < e.length; )
                if (a.call(e, r)) return (t.value = e[r]), (t.done = !1), t;
              return (t.value = void 0), (t.done = !0), t;
            };
          return (n.next = n);
        }
      }
      return { next: D };
    }
    function D() {
      return { value: void 0, done: !0 };
    }
    return (
      (f.prototype = m),
      o(w, "constructor", { value: m, configurable: !0 }),
      o(m, "constructor", { value: f, configurable: !0 }),
      (f.displayName = p(m, u, "GeneratorFunction")),
      (e.isGeneratorFunction = function (e) {
        var t = "function" == typeof e && e.constructor;
        return (
          !!t && (t === f || "GeneratorFunction" === (t.displayName || t.name))
        );
      }),
      (e.mark = function (e) {
        return (
          Object.setPrototypeOf
            ? Object.setPrototypeOf(e, m)
            : ((e.__proto__ = m), p(e, u, "GeneratorFunction")),
          (e.prototype = Object.create(w)),
          e
        );
      }),
      (e.awrap = function (e) {
        return { __await: e };
      }),
      b(x.prototype),
      p(x.prototype, i, function () {
        return this;
      }),
      (e.AsyncIterator = x),
      (e.async = function (t, r, n, a, o) {
        void 0 === o && (o = Promise);
        var s = new x(l(t, r, n, a), o);
        return e.isGeneratorFunction(r)
          ? s
          : s.next().then(function (e) {
              return e.done ? e.value : s.next();
            });
      }),
      b(w),
      p(w, u, "Generator"),
      p(w, c, function () {
        return this;
      }),
      p(w, "toString", function () {
        return "[object Generator]";
      }),
      (e.keys = function (e) {
        var t = Object(e),
          r = [];
        for (var n in t) r.push(n);
        return (
          r.reverse(),
          function e() {
            for (; r.length; ) {
              var n = r.pop();
              if (n in t) return (e.value = n), (e.done = !1), e;
            }
            return (e.done = !0), e;
          }
        );
      }),
      (e.values = L),
      (I.prototype = {
        constructor: I,
        reset: function (e) {
          if (
            ((this.prev = 0),
            (this.next = 0),
            (this.sent = this._sent = void 0),
            (this.done = !1),
            (this.delegate = null),
            (this.method = "next"),
            (this.arg = void 0),
            this.tryEntries.forEach(P),
            !e)
          )
            for (var t in this)
              "t" === t.charAt(0) &&
                a.call(this, t) &&
                !isNaN(+t.slice(1)) &&
                (this[t] = void 0);
        },
        stop: function () {
          this.done = !0;
          var e = this.tryEntries[0].completion;
          if ("throw" === e.type) throw e.arg;
          return this.rval;
        },
        dispatchException: function (e) {
          if (this.done) throw e;
          var t = this;
          function r(r, n) {
            return (
              (s.type = "throw"),
              (s.arg = e),
              (t.next = r),
              n && ((t.method = "next"), (t.arg = void 0)),
              !!n
            );
          }
          for (var n = this.tryEntries.length - 1; n >= 0; --n) {
            var o = this.tryEntries[n],
              s = o.completion;
            if ("root" === o.tryLoc) return r("end");
            if (o.tryLoc <= this.prev) {
              var c = a.call(o, "catchLoc"),
                i = a.call(o, "finallyLoc");
              if (c && i) {
                if (this.prev < o.catchLoc) return r(o.catchLoc, !0);
                if (this.prev < o.finallyLoc) return r(o.finallyLoc);
              } else if (c) {
                if (this.prev < o.catchLoc) return r(o.catchLoc, !0);
              } else {
                if (!i)
                  throw new Error("try statement without catch or finally");
                if (this.prev < o.finallyLoc) return r(o.finallyLoc);
              }
            }
          }
        },
        abrupt: function (e, t) {
          for (var r = this.tryEntries.length - 1; r >= 0; --r) {
            var n = this.tryEntries[r];
            if (
              n.tryLoc <= this.prev &&
              a.call(n, "finallyLoc") &&
              this.prev < n.finallyLoc
            ) {
              var o = n;
              break;
            }
          }
          o &&
            ("break" === e || "continue" === e) &&
            o.tryLoc <= t &&
            t <= o.finallyLoc &&
            (o = null);
          var s = o ? o.completion : {};
          return (
            (s.type = e),
            (s.arg = t),
            o
              ? ((this.method = "next"), (this.next = o.finallyLoc), h)
              : this.complete(s)
          );
        },
        complete: function (e, t) {
          if ("throw" === e.type) throw e.arg;
          return (
            "break" === e.type || "continue" === e.type
              ? (this.next = e.arg)
              : "return" === e.type
              ? ((this.rval = this.arg = e.arg),
                (this.method = "return"),
                (this.next = "end"))
              : "normal" === e.type && t && (this.next = t),
            h
          );
        },
        finish: function (e) {
          for (var t = this.tryEntries.length - 1; t >= 0; --t) {
            var r = this.tryEntries[t];
            if (r.finallyLoc === e)
              return this.complete(r.completion, r.afterLoc), P(r), h;
          }
        },
        catch: function (e) {
          for (var t = this.tryEntries.length - 1; t >= 0; --t) {
            var r = this.tryEntries[t];
            if (r.tryLoc === e) {
              var n = r.completion;
              if ("throw" === n.type) {
                var a = n.arg;
                P(r);
              }
              return a;
            }
          }
          throw new Error("illegal catch attempt");
        },
        delegateYield: function (e, t, r) {
          return (
            (this.delegate = { iterator: L(e), resultName: t, nextLoc: r }),
            "next" === this.method && (this.arg = void 0),
            h
          );
        },
      }),
      e
    );
  }
  function n(e, t, r, n, a, o, s) {
    try {
      var c = e[o](s),
        i = c.value;
    } catch (e) {
      return void r(e);
    }
    c.done ? t(i) : Promise.resolve(i).then(n, a);
  }
  function a(e) {
    return function () {
      var t = this,
        r = arguments;
      return new Promise(function (a, o) {
        var s = e.apply(t, r);
        function c(e) {
          n(s, a, o, c, i, "next", e);
        }
        function i(e) {
          n(s, a, o, c, i, "throw", e);
        }
        c(void 0);
      });
    };
  }
  var o,
    s,
    c = chrome.runtime.getManifest().version,
    i = {
      search_change: !1,
      global_wp_phone: "",
      onExtMessage: function (e, t, r) {
        switch (((i.message = e), e.command)) {
          case "saveUISettings":
            (uiSettings = e.data), i.saveUISettings(e.data, t, r);
            break;
          case "console_logs_myApp":
            p(e.title, e.msg);
            break;
          case "stopAutoBotProcess":
            i.stopAutoBotProcess(e.reason);
            break;
          case "viewAutoBotProcess":
            i.viewAutoBotProcess(e.data, t, r);
            break;
          case "startSearchProcess":
            i.startSearchProcess(e.data, t, r);
            break;
          case "resumeAutoBotProcess":
            i.resumeAutoBotProcess(e.data, t, r);
            break;
          case "productTrialStarted":
            i.productTrialStarted(e.data, t, r);
            break;
          case "saveUserToServer":
            i.saveUserToServer(e.data, t, r);
            break;
          case "getPhoneFromAddress":
            i.getPhoneFromAddress(e.data, t, r);
            break;
          case "downloadCSV":
            i.downloadCSV(e.data, t, r);
            break;
          case "getWhatsappNumber":
            i.getWhatsappNumber(e.data, t, r);
            break;
          case "getPgeItemDetails":
            i.getPgeItemDetails(e.data, t, r);
            break;
          case "checkSearchStatus":
            chrome.storage.local.get(function (e) {
              var n = !1;
              t &&
                t.tab &&
                t.tab.id &&
                parseInt(t.tab.id) == parseInt(e.active_search_tab_id) &&
                (n = !0),
                r({ is_search: n });
            });
            break;
          case "startAutoBotProcess":
            i.create_notifications({
              title: "Process Started",
              msg: "Justdial - Data Extractor & Scraper proccess has been started",
            });
            break;
          case "set_delay_in_bg":
            setTimeout(function () {
              r();
            }, e.timeout);
            break;
          case "getSettings":
            "yes" == e.callback
              ? r({ uiSettings })
              : u(t, { command: "rec_getSettings", data: { uiSettings } });
        }
        if (e.callback === "yes") return !0; },
      load: function () {},
      saveUISettings: function (e, t, r) {},
      create_notifications: function (e) {
        chrome.notifications.create(
          {
            type: "basic",
            iconUrl: chrome.runtime.getURL("images/logo.png"),
            title: e.title,
            message: e.msg,
          },
          function () {
            chrome.runtime.lastError &&
              console.warn("Whoops.. " + chrome.runtime.lastError.message);
          }
        );
      },
      viewAutoBotProcess: function (e, t, r) {
        h(
          chrome.runtime.getURL("html/index.html"),
          "Justdial - Data Extractor & Scraper",
          1050,
          650
        );
      },
      startSearchProcess: function (e, t, n) {
        chrome.storage.local.get(function (t) {
          if (
            ((t.active_search_tab_id = 0),
            (t.current_processed_count = 0),
            (t.scrape_status = "Finished"),
            (t.scrapped_items_arr = []),
            (t.scrape_type = e.search_type),
            (t.scrape_limit = 0),
            (t.scrape_limit_type = "All"),
            (t.resume_url = ""),
            (t.scrape_item_index = 0),
            chrome.storage.local.set({
              active_search_tab_id: t.active_search_tab_id,
              current_processed_count: t.current_processed_count,
              scrape_status: t.scrape_status,
              scrapped_items_arr: t.scrapped_items_arr,
              scrape_type: t.scrape_type,
              scrape_limit_type: t.scrape_limit_type,
              scrape_limit: t.scrape_limit,
              scrape_item_index: t.scrape_item_index,
            }),
            "Url" == e.search_type)
          ) {
            var n = (o = e.search_query).split("/");
            n.length >= 4 && (t.Keywords_input = n[4] + "_in_" + n[3]);
          } else {
            var o = "https://www.justdial.com/" + e.search_query;
            t.Keywords_input = e.Keywords_input + "_in_" + e.location_input;
          }
          chrome.windows.create(
            { url: o, width: 950, height: 800, type: "popup", focused: !0 },
            (function () {
              var n = a(
                r().mark(function n(a) {
                  var s, c, u, p;
                  return r().wrap(function (r) {
                    for (;;)
                      switch ((r.prev = r.next)) {
                        case 0:
                          return (
                            (s = a.tabs[0].id),
                            (t.scrape_status = "Inprogress"),
                            (c = {
                              title: "Process Started",
                              msg: "Justdial - Data Extractor & Scraper proccess has been started",
                            }),
                            i.create_notifications(c),
                            (t.scrape_status = "Inprogress"),
                            (t.current_processed_count = 0),
                            (t.active_search_tab_id = s),
                            (t.scrape_limit = e.scrape_limit),
                            (t.scrape_limit_type = e.scrape_limit_type),
                            chrome.storage.local.set({
                              active_search_tab_id: t.active_search_tab_id,
                              current_processed_count:
                                t.current_processed_count,
                              scrape_limit: t.scrape_limit,
                              scrape_limit_type: t.scrape_limit_type,
                              scrape_status: t.scrape_status,
                              Keywords_input: t.Keywords_input,
                              resume_url: o,
                            }),
                            (r.next = 12),
                            i.checkXClientAndServerIdToServer()
                          );
                        case 12:
                          return (r.next = 14), i.saveUserActivityToDB("", "");
                        case 14:
                          (u = r.sent) &&
                            u.insert_id &&
                            ((p = u.insert_id),
                            chrome.storage.local.set({ edit_id: p }));
                        case 16:
                        case "end":
                          return r.stop();
                      }
                  }, n);
                })
              );
              return function (e) {
                return n.apply(this, arguments);
              };
            })()
          );
        });
      },
      resumeAutoBotProcess: function (e, t, n) {
        chrome.storage.local.get(function (e) {
          (e.active_search_tab_id = 0),
            (e.scrape_status = "Finished"),
            chrome.storage.local.set({
              active_search_tab_id: e.active_search_tab_id,
              scrape_status: e.scrape_status,
            });
          var t = e.resume_url;
          chrome.windows.create(
            { url: t, width: 950, height: 800, type: "popup", focused: !0 },
            (function () {
              var t = a(
                r().mark(function t(n) {
                  var a, o, s, c;
                  return r().wrap(function (t) {
                    for (;;)
                      switch ((t.prev = t.next)) {
                        case 0:
                          return (
                            (a = n.tabs[0].id),
                            (e.scrape_status = "Inprogress"),
                            (e.active_search_tab_id = a),
                            chrome.storage.local.set({
                              active_search_tab_id: e.active_search_tab_id,
                              scrape_status: e.scrape_status,
                            }),
                            (o = {
                              title: "Process resume started",
                              msg: "Justdial - Data Extractor & Scraper Resume process has been started",
                            }),
                            i.create_notifications(o),
                            (t.next = 8),
                            i.checkXClientAndServerIdToServer()
                          );
                        case 8:
                          return (t.next = 10), i.saveUserActivityToDB("", "");
                        case 10:
                          (s = t.sent) &&
                            s.insert_id &&
                            ((c = s.insert_id),
                            chrome.storage.local.set({ edit_id: c }));
                        case 12:
                        case "end":
                          return t.stop();
                      }
                  }, t);
                })
              );
              return function (e) {
                return t.apply(this, arguments);
              };
            })()
          );
        });
      },
      productTrialStarted: function (e) {
        chrome.storage.local.get(
          (function () {
            var e = a(
              r().mark(function e(t) {
                return r().wrap(function (e) {
                  for (;;)
                    switch ((e.prev = e.next)) {
                      case 0:
                        (null != t.product_trial_started &&
                          0 != t.product_trial_started) ||
                          (chrome.storage.local.set({
                            product_trial_started: 0,
                          }),
                          i.saveXClientIdToServer());
                      case 1:
                      case "end":
                        return e.stop();
                    }
                }, e);
              })
            );
            return function (t) {
              return e.apply(this, arguments);
            };
          })()
        );
      },
      productLaunched: function (e) {
        chrome.storage.local.get(
          (function () {
            var e = a(
              r().mark(function e(t) {
                return r().wrap(function (e) {
                  for (;;)
                    switch ((e.prev = e.next)) {
                      case 0:
                        (null != t.product_launched &&
                          0 != t.product_launched) ||
                          (chrome.storage.local.set({ product_launched: 1 }),
                          i.saveXClientIdToServer());
                      case 1:
                      case "end":
                        return e.stop();
                    }
                }, e);
              })
            );
            return function (t) {
              return e.apply(this, arguments);
            };
          })()
        );
      },
      stopAutoBotProcess: function (e) {
        chrome.storage.local.get(
          (function () {
            var t = a(
              r().mark(function t(n) {
                var a, o;
                return r().wrap(function (t) {
                  for (;;)
                    switch ((t.prev = t.next)) {
                      case 0:
                        return (
                          n.scrapped_items_arr.length > 0
                            ? (i.downloadCSV(),
                              i.saveDataToServer(n.scrapped_items_arr),
                              "next_profile_not_found" == e
                                ? ((a = {
                                    title: "Downloading started",
                                    msg: "Successfully Data scrapped and downloading CSV file has been started.",
                                  }),
                                  i.create_notifications(a))
                                : "trial_version_expire" == e
                                ? ((a = {
                                    title: "Upgrade Required",
                                    msg: 'Justdial - Data Extractor & Scraper process has been stopped!! because the "Free Trial Version" Only Scrap Up to 20 Data. After 20 Data it will stop automatically.',
                                  }),
                                  i.create_notifications(a))
                                : "register_required" == e
                                ? ((a = {
                                    title: "Process Stopped",
                                    msg: "Justdial - Data Extractor & Scraper process has been stopped and downloading CSV file has been started. You need to register for more scrape data.",
                                  }),
                                  i.create_notifications(a))
                                : "user_not_approved" == e
                                ? ((a = {
                                    title: "Process Stopped",
                                    msg: "Justdial - Data Extractor & Scraper process has been stopped and downloading CSV file has been started. You are not registered or your account is not approved for more scrape data.",
                                  }),
                                  i.create_notifications(a))
                                : "manual_stop" == e &&
                                  ((a = {
                                    title: "Process Stopped",
                                    msg: "Justdial - Data Extractor & Scraper process has been stopped and downloading CSV file has been started.",
                                  }),
                                  i.create_notifications(a)))
                            : ((a = {
                                title: "Process Stopped",
                                msg: "No data found! Justdial - Data Extractor & Scraper process has been stopped.",
                              }),
                              i.create_notifications(a)),
                          u(n.active_search_tab_id, {
                            command: "removeBlocker",
                          }),
                          (n.scrape_status = "Finished"),
                          (n.active_search_tab_id = 0),
                          chrome.storage.local.set({
                            active_search_tab_id: n.active_search_tab_id,
                            scrape_status: n.scrape_status,
                          }),
                          u("", { command: "updateScrapeState" }),
                          (o = ""),
                          null != n.edit_id && (o = n.edit_id),
                          (t.next = 10),
                          i.checkXClientAndServerIdToServer()
                        );
                      case 10:
                        return (t.next = 12), i.saveUserActivityToDB(e, o);
                      case 12:
                      case "end":
                        return t.stop();
                    }
                }, t);
              })
            );
            return function (e) {
              return t.apply(this, arguments);
            };
          })()
        );
      },
      getPhoneFromAddress: function (e, t, n) {
        e.s_obj;
        var o = e.d_url;
        fetch(o, {})
          .then(
            (function () {
              var e = a(
                r().mark(function e(t) {
                  var a;
                  return r().wrap(function (e) {
                    for (;;)
                      switch ((e.prev = e.next)) {
                        case 0:
                          return (e.next = 2), t.text();
                        case 2:
                          (a = e.sent), n(a);
                        case 4:
                        case "end":
                          return e.stop();
                      }
                  }, e);
                })
              );
              return function (t) {
                return e.apply(this, arguments);
              };
            })()
          )
          .catch(function (e) {
            n("");
          });
      },
      saveDataToServer: function (e) {},
      saveXClientIdToServer: function () {
        chrome.storage.local.get(
          (function () {
            var e = a(
              r().mark(function e(t) {
                var n;
                return r().wrap(function (e) {
                  for (;;)
                    switch ((e.prev = e.next)) {
                      case 0:
                        if (null == (n = t.X_Client_Id) && null == n) {
                          e.next = 5;
                          break;
                        }
                        i.saveInstallToDB(n), (e.next = 7);
                        break;
                      case 5:
                        return (
                          (e.next = 7), i.checkXClientAndServerIdToServer()
                        );
                      case 7:
                      case "end":
                        return e.stop();
                    }
                }, e);
              })
            );
            return function (t) {
              return e.apply(this, arguments);
            };
          })()
        );
      },
      checkXClientAndServerIdToServer: function () {
        return new Promise(
          (function () {
            var e = a(
              r().mark(function e(t, n) {
                var a, o, s, c;
                return r().wrap(function (e) {
                  for (;;)
                    switch ((e.prev = e.next)) {
                      case 0:
                        return (e.next = 2), chrome.storage.local.get();
                      case 2:
                        if (
                          ((a = e.sent),
                          (o = a.X_Client_Id),
                          (s = a.server_user_id),
                          null != o && null != s)
                        ) {
                          e.next = 14;
                          break;
                        }
                        return (o = l()), (e.next = 9), i.saveInstallToDB(o);
                      case 9:
                        (c = e.sent) &&
                          1 == c.success &&
                          (chrome.storage.local.set({ saveUserInstall: !0 }),
                          "" != c.server_user_id &&
                            null != c.server_user_id &&
                            (chrome.storage.local.set({
                              server_user_id: c.server_user_id,
                            }),
                            chrome.storage.local.set({ X_Client_Id: o }))),
                          t(),
                          (e.next = 15);
                        break;
                      case 14:
                        t();
                      case 15:
                      case "end":
                        return e.stop();
                    }
                }, e);
              })
            );
            return function (t, r) {
              return e.apply(this, arguments);
            };
          })()
        );
      },
      saveInstallToServer:
        ((s = a(
          r().mark(function e() {
            var t, n;
            return r().wrap(function (e) {
              for (;;)
                switch ((e.prev = e.next)) {
                  case 0:
                    return (t = l()), (e.next = 3), i.saveInstallToDB(t);
                  case 3:
                    (n = e.sent) &&
                      1 == n.success &&
                      (chrome.storage.local.set({ saveUserInstall: !0 }),
                      "" != n.server_user_id &&
                        null != n.server_user_id &&
                        (chrome.storage.local.set({
                          server_user_id: n.server_user_id,
                        }),
                        chrome.storage.local.set({ X_Client_Id: t })));
                  case 5:
                  case "end":
                    return e.stop();
                }
            }, e);
          })
        )),
        function () {
          return s.apply(this, arguments);
        }),
      saveInstallToDB: function (t) {
        return new Promise(
          (function () {
            var n = a(
              r().mark(function n(a, o) {
                var s, i;
                return r().wrap(function (r) {
                  for (;;)
                    switch ((r.prev = r.next)) {
                      case 0:
                        return (r.next = 2), chrome.storage.local.get();
                      case 2:
                        (s = r.sent),
                          (i = new Headers()).append("X-Client-Id", t),
                          i.append("x-product-id", "4"),
                          i.append("x-product-version", c),
                          i.append("x-csrf-token", s.token_id || ""),
                          i.append(
                            "x-product-launched",
                            s.product_launched || 0
                          ),
                          i.append(
                            "x-product-trial-started",
                            s.product_trial_started || 0
                          ),
                          i.append(
                            "Content-Type",
                            "application/x-www-form-urlencoded"
                          ),
                          fetch(e.base_api_url + e.save_install_api_url, {
                            method: "POST",
                            headers: i,
                            redirect: "follow",
                          })
                            .then(function (e) {
                              return e.json();
                            })
                            .then(function (e) {
                              return a(e);
                            })
                            .catch(function (e) {
                              return a({});
                            });
                      case 13:
                      case "end":
                        return r.stop();
                    }
                }, n);
              })
            );
            return function (e, t) {
              return n.apply(this, arguments);
            };
          })()
        );
      },
      saveUserActivityToDB: function (t, n) {
        return new Promise(
          (function () {
            var o = a(
              r().mark(function a(o, s) {
                var i, u, p;
                return r().wrap(function (r) {
                  for (;;)
                    switch ((r.prev = r.next)) {
                      case 0:
                        return (r.next = 2), chrome.storage.local.get();
                      case 2:
                        null != (i = r.sent).X_Client_Id &&
                          null != i.server_user_id &&
                          ((u = new Headers()).append(
                            "X-Client-Id",
                            i.X_Client_Id
                          ),
                          u.append("X-Server-Id", i.server_user_id),
                          u.append("x-Product-id", "4"),
                          u.append("x-Product-Version", c),
                          u.append("x-csrf-token", i.token_id || ""),
                          u.append(
                            "Content-Type",
                            "application/x-www-form-urlencoded"
                          ),
                          (p = new URLSearchParams()).append(
                            "scrape_status",
                            i.scrape_status
                          ),
                          p.append(
                            "current_processed_count",
                            i.current_processed_count
                          ),
                          p.append(
                            "total_scrapped_count",
                            i.total_scrapped_count
                          ),
                          p.append("scrape_limit", i.scrape_limit),
                          p.append("scrape_limit_type", i.scrape_limit_type),
                          p.append("scrape_type", i.scrape_type),
                          p.append("search_query", i.Keywords_input),
                          p.append("stop_reason", t),
                          p.append("edit_id", n),
                          fetch(e.base_api_url + e.save_activity_api_url, {
                            method: "POST",
                            body: p,
                            headers: u,
                            redirect: "follow",
                          })
                            .then(function (e) {
                              return e.json();
                            })
                            .then(function (e) {
                              return o(e);
                            })
                            .catch(function (e) {
                              return o({});
                            }));
                      case 4:
                      case "end":
                        return r.stop();
                    }
                }, a);
              })
            );
            return function (e, t) {
              return o.apply(this, arguments);
            };
          })()
        );
      },
      saveUserToServer: function (t, r, n) {
        var a = new Headers();
        a.append("Content-Type", "application/x-www-form-urlencoded");
        var o = new URLSearchParams();
        o.append("email", t.user_email),
          o.append("product_id", "4"),
          o.append("subscription_key", t.key),
          fetch(e.base_api_url + e.save_user_api_url, {
            method: "POST",
            headers: a,
            body: o,
            redirect: "follow",
          })
            .then(function (e) {
              return e.json();
            })
            .then(function (e) {
              return n(e);
            })
            .catch(function (e) {
              return console.log("error", e);
            });
      },
      getWhatsappNumber: function (e, t, r) {
        (i.global_wp_phone = ""),
          $.ajax({
            type: "GET",
            cache: !1,
            url: e,
            success: function (e, t, n) {
              r({ whatsapp_number: i.global_wp_phone });
            },
            error: function (e, t, n) {
              r({ whatsapp_number: i.global_wp_phone });
            },
          });
      },
      getPgeItemDetails:
        ((o = a(
          r().mark(function e(t, n, a) {
            return r().wrap(function (e) {
              for (;;)
                switch ((e.prev = e.next)) {
                  case 0:
                    return (e.next = 2), clearJDCookies();
                  case 2:
                    fetch(t, { method: "GET", cache: "no-cache" })
                      .then(function (e) {
                        if (!e.ok)
                          throw new Error("Network response was not ok");
                        return e.text();
                      })
                      .then(function (e) {
                        a(e);
                      })
                      .catch(function (e) {
                        a(e.message);
                      });
                  case 3:
                  case "end":
                    return e.stop();
                }
            }, e);
          })
        )),
        function (e, t, r) {
          return o.apply(this, arguments);
        }),
      downloadCSV: function () {
        chrome.storage.local.get(function (e) {
          var t,
            r,
            n,
            a,
            o,
            s,
            c,
            u =
              ((t = new Date()),
              (r = t.getFullYear()),
              (n = d(t.getMonth() + 1)),
              (a = d(t.getDate())),
              (o = d(t.getHours())),
              (s = d(t.getMinutes())),
              (c = d(t.getSeconds())),
              r + "-" + n + "-" + a + "-" + o + "-" + s + "-" + c);
          if (e.Keywords_input && "" != e.Keywords_input)
            var p = e.Keywords_input + "_" + u;
          else p = "items_data_" + u;
          e.scrapped_items_arr;
          i.V2JSONToCSVConvertor(e.scrapped_items_arr, p, !0);
        });
      },
      V2JSONToCSVConvertor: function (e, r, n) {
        var a = "object" != t(e) ? JSON.parse(e) : e,
          o = "";
        if (n) {
          var s = "";
          for (var c in a[0]) {
            s += i.getKeyFromMap(c) + ",";
          }
          o += (s = s.slice(0, -1)) + "\r\n";
        }
        for (var u = 0; u < a.length; u++) {
          s = "";
          for (var c in a[u]) {
            a[u][c];
            s +=
              '"' +
              (void 0 === a[u][c]
                ? ""
                : (a[u][c] + "")
                    .toString()
                    .replace(/["]/gi, "'")
                    .replace(/(\r\n|\n|\r|\s+|\t|&nbsp;)/gm, " ")
                    .replace(/"/g, '"')
                    .replace(/,/g, ",")
                    .replace(/'/g, "'")
                    .replace(/ +(?= )/g, "")) +
              '",';
          }
          s.slice(0, s.length - 1), (o += s + "\r\n");
        }
        if ("" != o) {
          var p = "";
          p += r.replace(/ /g, "_");
          var l = "data:text/csv;charset=utf-8," + escape(o);
          chrome.downloads.download({
            url: l,
            filename: "JD_Data_Scrapper_Tool/" + p + ".csv",
          });
        } else alert("Invalid data");
      },
      checkAuthStatus: function () {
        i.authUserToServer({}, "sender", function (e) {
          e &&
            1 == e.success &&
            0 == e.data &&
            chrome.storage.local.set({
              authUser: true,
              userFreeTrialStarted: true,
              userTrialIsStarted: true,
            });
        });
      },
      authUserToServer: function (t, r, n) {
        chrome.storage.local.get(function (t) {
          var r = new Headers();
          r.append("x-key", t.key),
            r.append("x-csrf-token", t.token_id),
            r.append("x-product-id", "4"),
            r.append("Content-Type", "application/x-www-form-urlencoded");
          var a = new URLSearchParams();
          a.append("email", t.authName),
            fetch(e.base_api_url + e.auth_user_api_url, {
              method: "POST",
              headers: r,
              body: a,
              redirect: "follow",
            })
              .then(function (e) {
                return e.json();
              })
              .then(function (e) {
                return n(e);
              })
              .catch(function (e) {
                return console.log("error", e);
              });
        });
      },
      getKeyFromMap: function (e) {
        return (
          {
            name: "Name",
            address: "Address",
            landmark: "Landmark",
            area: "Area",
            pincode: "Pincode",
            contact_number_2: "Business Phone",
            contact_number: "Justdial Phone",
            business_info: "Business Information",
            rating: "Rating",
            reviews: "Reviews",
            listed_in: "Listed In",
            hours_of_operation: "Hours of operations",
            year_established: "Year Established",
            modes_of_payment: "Modes of payment",
            quick_information: "Quick Information",
            website: "Website",
            link: "Link",
          }[e] || e
        );
      },
      getParameterByName: function (e, t) {
        t || (t = window.location.href), (e = e.replace(/[\[\]]/g, "\\$&"));
        var r = new RegExp("[?&]" + e + "(=([^&#]*)|&|#|$)").exec(t);
        return r
          ? r[2]
            ? decodeURIComponent(r[2].replace(/\+/g, " "))
            : ""
          : null;
      },
      updateQueryStringParameter: function (e, t, r) {
        var n = new RegExp("([?&])" + t + "=.*?(&|$)", "i"),
          a = -1 !== e.indexOf("?") ? "&" : "?";
        return e.match(n)
          ? e.replace(n, "$1" + t + "=" + r + "$2")
          : e + a + t + "=" + r;
      },
    };
  function u(e, t) {
    var id = typeof e === "object" && e ? (e.tab ? e.tab.id : null) : e;
    try {
        var p = id ? chrome.tabs.sendMessage(id, t) : chrome.runtime.sendMessage(t);
        if (p && p.catch) { p.catch(function() {}); }
    } catch(err) {}
  }
  chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
      // ── HARDENING LAYER: Enforce license on critical scraping commands ──
      const criticalCommands = ["startSearchProcess", "resumeAutoBotProcess", "viewAutoBotProcess", "stopAutoBotProcess"];
      if (criticalCommands.includes(msg.command)) {
          wa_isLicenseValid().then(valid => {
              if (!valid) {
                  console.warn("[WA Security] Unauthorized scrape attempt blocked.");
                  sendResponse({ success: false, message: "License is missing or invalid." });
                  return;
              }
              i.onExtMessage(msg, sender, sendResponse);
              try { sendResponse({ success: true }); } catch (e) {}
          });
          return true; // Keep message channel open for async response
      }
      return i.onExtMessage(msg, sender, sendResponse);
  });
  i.load();
  var p = function (e, r) {
    console.log("%c " + e, "font-weight: bold"),
      "object" == t(r)
        ? console.log("%c " + JSON.stringify(r), "color:#ce3e3e")
        : console.log("%c " + r, "color:#ce3e3e");
  };
  function l() {
    var e = new Date().getTime(),
      t = (performance && performance.now && 1e3 * performance.now()) || 0;
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
      /[xy]/g,
      function (r) {
        var n = 16 * Math.random();
        return (
          e > 0
            ? ((n = (e + n) % 16 | 0), (e = Math.floor(e / 16)))
            : ((n = (t + n) % 16 | 0), (t = Math.floor(t / 16))),
          ("x" === r ? n : (3 & n) | 8).toString(16)
        );
      }
    );
  }
  function d(e) {
    return e < 10 ? "0" + e : e;
  }
  function h(e, t, r, n) {
    chrome.tabs.query({}, function (t) {
      var a = "";
      if (t && t.length > 0)
        for (var o = 0; o < t.length; o++)
          if (t[o].url && t[o].url == e) {
            a = t[o].id;
            break;
          }
      "" != a && parseInt(a)
        ? chrome.tabs.get(parseInt(a), function (e) {
            chrome.windows.update(e.windowId, { focused: !0 }),
              chrome.tabs.update(parseInt(a), { active: !0 });
          })
        : chrome.windows.getCurrent(function (t) {
            var a = 220 + t.left,
              o = 110 + t.top;
            chrome.windows.create({
              url: e,
              width: r,
              height: n,
              top: Math.round(o),
              left: Math.round(a),
              type: "popup",
            });
          });
    });
  }
  chrome.tabs.onUpdated.addListener(function (e, t, r) {
    "complete" == t.status && "complete" == r.status && r.url;
  }),
    chrome.tabs.onRemoved.addListener(function (e, t) {
      chrome.storage.local.get(function (t) {
        t.active_search_tab_id == e &&
          (i.stopAutoBotProcess("manual_stop"),
          u("", { command: "updateScrapeState" }));
      });
    }),
    chrome.action.onClicked.addListener(function (e) {
      chrome.storage.local.get(function (e) {
        if (1 == e.authUser) var t = chrome.runtime.getURL("html/index.html");
        else t = chrome.runtime.getURL("html/index.html");
        h(t, "Justdial - Data Extractor & Scraper", 1050, 650), i.productLaunched();
      });
    }),
    setInterval(function () {
      i.checkAuthStatus();
    }, 864e5),
    chrome.runtime.onInstalled.addListener(function (e) {
      if ("install" == e.reason) {
        chrome.storage.local.get(function (e) {
          chrome.storage.local.set({
            scrape_status: "Finished",
            scrapped_items_arr: [],
            total_scrapped_page: 0,
            total_scrapped_count: 0,
            current_processed_count: 0,
            authUser: true,
            userFreeTrialStarted: true,
            userTrialIsStarted: true,
            scrape_limit: 0,
            scrape_limit_type: "All",
            authName: "",
            userRegistered: true,
            active_search_tab_id: 0,
            is_expired: !1,
            username: "",
            key: "",
            token_id: "",
            activate_date: "",
            skip_duplicate_record_check: !1,
            product_launched: 0,
            product_trial_started: 0,
          });
        }),
          i.saveInstallToServer();
        // chrome.tabs.create({
        //   url: "https://blog.scrappertool.com/how-to-use-justdial-scraper-tool/#get-started",
        // }),
          setTimeout(function () {
            chrome.storage.local.get(function (e) {
              if (1 == e.authUser)
                var t = chrome.runtime.getURL("html/index.html");
              else t = chrome.runtime.getURL("html/index.html");
              h(t, 0, 1050, 650), i.productLaunched();
            });
          }, 5e3);
      } else "update" == e.reason && i.saveXClientIdToServer();
    });
})();
