(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('nice-select2')) :
  typeof define === 'function' && define.amd ? define(['nice-select2'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.NiceSelect));
})(this, (function (NiceSelect) { 'use strict';

  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

  var NiceSelect__default = /*#__PURE__*/_interopDefaultLegacy(NiceSelect);

  function _assertClassBrand(e, t, n) {
    if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
    throw new TypeError("Private element is not present on this object");
  }
  function _assertThisInitialized(e) {
    if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
    return e;
  }
  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);
      });
    };
  }
  function _callSuper(t, o, e) {
    return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
  }
  function _checkPrivateRedeclaration(e, t) {
    if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
  }
  function _classCallCheck(a, n) {
    if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
  }
  function _classPrivateFieldGet2(s, a) {
    return s.get(_assertClassBrand(s, a));
  }
  function _classPrivateFieldInitSpec(e, t, a) {
    _checkPrivateRedeclaration(e, t), t.set(e, a);
  }
  function _classPrivateFieldSet2(s, a, r) {
    return s.set(_assertClassBrand(s, a), r), r;
  }
  function _defineProperties(e, r) {
    for (var t = 0; t < r.length; t++) {
      var o = r[t];
      o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o);
    }
  }
  function _createClass(e, r, t) {
    return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
      writable: !1
    }), e;
  }
  function _defineProperty(e, r, t) {
    return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
      value: t,
      enumerable: !0,
      configurable: !0,
      writable: !0
    }) : e[r] = t, e;
  }
  function _get() {
    return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) {
      var p = _superPropBase(e, t);
      if (p) {
        var n = Object.getOwnPropertyDescriptor(p, t);
        return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value;
      }
    }, _get.apply(null, arguments);
  }
  function _getPrototypeOf(t) {
    return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
      return t.__proto__ || Object.getPrototypeOf(t);
    }, _getPrototypeOf(t);
  }
  function _inherits(t, e) {
    if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function");
    t.prototype = Object.create(e && e.prototype, {
      constructor: {
        value: t,
        writable: !0,
        configurable: !0
      }
    }), Object.defineProperty(t, "prototype", {
      writable: !1
    }), e && _setPrototypeOf(t, e);
  }
  function _isNativeReflectConstruct() {
    try {
      var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
    } catch (t) {}
    return (_isNativeReflectConstruct = function () {
      return !!t;
    })();
  }
  function ownKeys(e, r) {
    var t = Object.keys(e);
    if (Object.getOwnPropertySymbols) {
      var o = Object.getOwnPropertySymbols(e);
      r && (o = o.filter(function (r) {
        return Object.getOwnPropertyDescriptor(e, r).enumerable;
      })), t.push.apply(t, o);
    }
    return t;
  }
  function _objectSpread2(e) {
    for (var r = 1; r < arguments.length; r++) {
      var t = null != arguments[r] ? arguments[r] : {};
      r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
        _defineProperty(e, r, t[r]);
      }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
        Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
      });
    }
    return e;
  }
  function _possibleConstructorReturn(t, e) {
    if (e && ("object" == typeof e || "function" == typeof e)) return e;
    if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined");
    return _assertThisInitialized(t);
  }
  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 _regeneratorDefine(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 (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]())) : (_regeneratorDefine(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, _regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
    }
    return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine(u), _regeneratorDefine(u, o, "Generator"), _regeneratorDefine(u, n, function () {
      return this;
    }), _regeneratorDefine(u, "toString", function () {
      return "[object Generator]";
    }), (_regenerator = function () {
      return {
        w: i,
        m: f
      };
    })();
  }
  function _regeneratorDefine(e, r, n, t) {
    var i = Object.defineProperty;
    try {
      i({}, "", {});
    } catch (e) {
      i = 0;
    }
    _regeneratorDefine = function (e, r, n, t) {
      function o(r, n) {
        _regeneratorDefine(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));
    }, _regeneratorDefine(e, r, n, t);
  }
  function _setPrototypeOf(t, e) {
    return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
      return t.__proto__ = e, t;
    }, _setPrototypeOf(t, e);
  }
  function _superPropBase(t, o) {
    for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t)););
    return t;
  }
  function _superPropGet(t, o, e, r) {
    var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e);
    return 2 & r && "function" == typeof p ? function (t) {
      return p.apply(e, t);
    } : p;
  }
  function _toPrimitive(t, r) {
    if ("object" != typeof t || !t) return t;
    var e = t[Symbol.toPrimitive];
    if (void 0 !== e) {
      var i = e.call(t, r || "default");
      if ("object" != typeof i) return i;
      throw new TypeError("@@toPrimitive must return a primitive value.");
    }
    return ("string" === r ? String : Number)(t);
  }
  function _toPropertyKey(t) {
    var i = _toPrimitive(t, "string");
    return "symbol" == typeof i ? i : i + "";
  }
  function _typeof(o) {
    "@babel/helpers - typeof";

    return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
      return typeof o;
    } : function (o) {
      return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
    }, _typeof(o);
  }

  var eventBus = function eventBus() {
    var data = {};
    return {
      on: function on(events, callback) {
        events.split(' ').forEach(function (event) {
          (data[event] = data[event] || []).push(callback);
        });
      },
      off: function off(events, callback) {
        events.split(' ').forEach(function (event) {
          data[event] = (data[event] || []).filter(function (i) {
            return i !== callback;
          });
        });
      },
      emit: function emit(event) {
        for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
          args[_key - 1] = arguments[_key];
        }
        (data[event] || []).forEach(function (callback) {
          return callback.apply(void 0, args);
        });
      },
      destroy: function destroy() {
        return data = {};
      }
    };
  };

  var restApi = function restApi(url) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    var restUrl = url;
    var config = options;
    var request = /*#__PURE__*/function () {
      var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(method, url, route) {
        var options,
          body,
          init,
          response,
          errorText,
          _args = arguments,
          _t;
        return _regenerator().w(function (_context) {
          while (1) switch (_context.p = _context.n) {
            case 0:
              options = _args.length > 3 && _args[3] !== undefined ? _args[3] : {};
              body = _args.length > 4 && _args[4] !== undefined ? _args[4] : null;
              _context.p = 1;
              url = route ? "".concat(url, "/").concat(route) : url;
              init = {
                method: method,
                headers: new Headers({
                  'Content-Type': 'application/json',
                  'X-WP-Nonce': options.nonce
                }),
                body: body
              };
              _context.n = 2;
              return fetch(url, init);
            case 2:
              response = _context.v;
              if (response.ok) {
                _context.n = 4;
                break;
              }
              _context.n = 3;
              return response.text()["catch"](function () {
                return null;
              });
            case 3:
              errorText = _context.v;
              throw new Error(JSON.stringify({
                message: 'REST API request failed',
                status: response.status,
                statusText: response.statusText,
                url: url,
                method: method,
                bodySent: body,
                serverResponse: errorText
              }));
            case 4:
              _context.n = 5;
              return response.json();
            case 5:
              return _context.a(2, _context.v);
            case 6:
              _context.p = 6;
              _t = _context.v;
              throw new Error(JSON.stringify({
                message: 'Network or parsing error',
                originalError: _t.message,
                method: method,
                url: url,
                route: route,
                bodySent: body
              }));
            case 7:
              return _context.a(2);
          }
        }, _callee, null, [[1, 6]]);
      }));
      return function request(_x, _x2, _x3) {
        return _ref.apply(this, arguments);
      };
    }();
    return {
      get: function () {
        var _get = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2() {
          var route,
            _args2 = arguments;
          return _regenerator().w(function (_context2) {
            while (1) switch (_context2.n) {
              case 0:
                route = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : null;
                _context2.n = 1;
                return request('GET', restUrl, route, config);
              case 1:
                return _context2.a(2, _context2.v);
            }
          }, _callee2);
        }));
        function get() {
          return _get.apply(this, arguments);
        }
        return get;
      }(),
      post: function () {
        var _post = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3() {
          var route,
            body,
            _args3 = arguments;
          return _regenerator().w(function (_context3) {
            while (1) switch (_context3.n) {
              case 0:
                route = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : null;
                body = _args3.length > 1 && _args3[1] !== undefined ? _args3[1] : null;
                _context3.n = 1;
                return request('POST', restUrl, route, config, body);
              case 1:
                return _context3.a(2, _context3.v);
            }
          }, _callee3);
        }));
        function post() {
          return _post.apply(this, arguments);
        }
        return post;
      }(),
      "delete": function () {
        var _delete2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4() {
          var route,
            body,
            _args4 = arguments;
          return _regenerator().w(function (_context4) {
            while (1) switch (_context4.n) {
              case 0:
                route = _args4.length > 0 && _args4[0] !== undefined ? _args4[0] : null;
                body = _args4.length > 1 && _args4[1] !== undefined ? _args4[1] : null;
                _context4.n = 1;
                return request('DELETE', restUrl, route, config, body);
              case 1:
                return _context4.a(2, _context4.v);
            }
          }, _callee4);
        }));
        function _delete() {
          return _delete2.apply(this, arguments);
        }
        return _delete;
      }(),
      patch: function () {
        var _patch = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5() {
          var route,
            body,
            _args5 = arguments;
          return _regenerator().w(function (_context5) {
            while (1) switch (_context5.n) {
              case 0:
                route = _args5.length > 0 && _args5[0] !== undefined ? _args5[0] : null;
                body = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : null;
                _context5.n = 1;
                return request('PATCH', restUrl, route, config, body);
              case 1:
                return _context5.a(2, _context5.v);
            }
          }, _callee5);
        }));
        function patch() {
          return _patch.apply(this, arguments);
        }
        return patch;
      }()
    };
  };

  var defaults = {
    classes: {
      message: 'dcaw-message',
      box: 'dcaw-messages-wrapper'
    },
    timeout: 4000,
    max: 1
  };
  var messageHub = function messageHub() {
    var messageBox = document.querySelector(".".concat(defaults.classes.box));
    var data = [];
    function findElement(element) {
      return data.find(function (i) {
        return i.element === element;
      });
    }
    function buildElement(str) {
      var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'success';
      var element = document.createElement('div');
      element.classList.add(defaults.classes.message, "is-".concat(type));
      element.textContent = str;
      return element;
    }
    function removeElement(element) {
      var message = findElement(element);
      clearTimeout(message.timeout);
      messageBox.removeChild(message.element);
      data = data.filter(function (i) {
        return i !== message;
      });
    }
    function insertElement(element) {
      var _findElement = findElement(element),
        timeout = _findElement.timeout;
      messageBox.appendChild(element);
      element.addEventListener('click', function (event) {
        event.stopPropagation();
        clearTimeout(timeout);
        removeElement(element);
      });
      element.addEventListener('mouseover', function () {
        clearTimeout(timeout);
      });
      element.addEventListener('mouseleave', function () {
        timeout = elementTimeout(element);
      });
    }
    function elementTimeout(element) {
      return setTimeout(function () {
        removeElement(element);
      }, defaults.timeout);
    }
    function buildBox() {
      messageBox = document.createElement('div');
      messageBox.classList.add(defaults.classes.box);
      document.body.appendChild(messageBox);
    }
    return {
      show: function show(str, type) {
        if (!messageBox) buildBox();
        var element = buildElement(str, type);
        var timeout = elementTimeout(element);
        if (data.length >= defaults.max) {
          removeElement(data[0].element);
        }
        data.push({
          element: element,
          timeout: timeout
        });
        insertElement(element);
      }
    };
  };

  var _Event = /*#__PURE__*/new WeakMap();
  var _Message = /*#__PURE__*/new WeakMap();
  var _Options = /*#__PURE__*/new WeakMap();
  var _Rest = /*#__PURE__*/new WeakMap();
  var _Store = /*#__PURE__*/new WeakMap();
  var _Counters = /*#__PURE__*/new WeakMap();
  var _Tables = /*#__PURE__*/new WeakMap();
  var _Name = /*#__PURE__*/new WeakMap();
  var Core = /*#__PURE__*/function () {
    function Core(name) {
      var _this = this;
      var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      _classCallCheck(this, Core);
      _classPrivateFieldInitSpec(this, _Event, eventBus());
      _classPrivateFieldInitSpec(this, _Message, messageHub());
      _classPrivateFieldInitSpec(this, _Options, {});
      _classPrivateFieldInitSpec(this, _Rest, void 0);
      _classPrivateFieldInitSpec(this, _Store, []);
      _classPrivateFieldInitSpec(this, _Counters, []);
      _classPrivateFieldInitSpec(this, _Tables, []);
      _classPrivateFieldInitSpec(this, _Name, void 0);
      _defineProperty(this, "mount", function () {
        _classPrivateFieldGet2(_Rest, _this).get().then(function (result) {
          if (result.ok) {
            _classPrivateFieldSet2(_Store, _this, result.data);
            _this.initCounters();
            _this.initTables();
            _this.initEvents();
            _this.emit("mount");
          }
        });
      });
      _defineProperty(this, "onMaximum", function (result) {
        _this.show(result.message, "info");
      });
      _defineProperty(this, "onDeleteProduct", function (result) {
        _this.show(result.message, "info");
      });
      _defineProperty(this, "onPostProduct", function (result) {
        _this.show(result.message);
      });
      _defineProperty(this, "initCounters", function () {
        var _classPrivateFieldGet2$1 = _classPrivateFieldGet2(_Options, _this),
          selectors = _classPrivateFieldGet2$1.selectors,
          classes = _classPrivateFieldGet2$1.classes,
          compare_page = _classPrivateFieldGet2$1.compare_page;
        document.querySelectorAll(selectors.counters).forEach(function (parent) {
          var link = document.createElement("a");
          if (compare_page) {
            link.setAttribute("href", compare_page);
          }
          link.classList.add(classes.counter, classes.empty);
          _classPrivateFieldGet2(_Counters, _this).push(link);
          parent.appendChild(link);
        });
      });
      _defineProperty(this, "updateCounters", function () {
        var length = _classPrivateFieldGet2(_Store, _this).reduce(function (acc, data) {
          if (data.products) {
            return acc + data.products.length;
          }
        }, 0);
        var _classPrivateFieldGet3 = _classPrivateFieldGet2(_Options, _this),
          empty = _classPrivateFieldGet3.classes.empty;
        _classPrivateFieldGet2(_Counters, _this).forEach(function (counter) {
          if (length) {
            counter.textContent = length.toString();
            counter.classList.remove(empty);
          } else {
            counter.classList.add(empty);
            counter.textContent = "";
          }
        });
      });
      _defineProperty(this, "initTables", function () {
        document.querySelectorAll(_classPrivateFieldGet2(_Options, _this).selectors.tables).forEach(function (table) {
          _classPrivateFieldGet2(_Tables, _this).push(table);
        });
      });
      _defineProperty(this, "updateTables", /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2() {
        return _regenerator().w(function (_context2) {
          while (1) switch (_context2.n) {
            case 0:
              _classPrivateFieldGet2(_Tables, _this).forEach(/*#__PURE__*/function () {
                var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(table) {
                  var selectedCategoryId, url, result, _t;
                  return _regenerator().w(function (_context) {
                    while (1) switch (_context.p = _context.n) {
                      case 0:
                        _this.emit("loading", true, table);
                        selectedCategoryId = _this.getSelectedCategoryId();
                        url = selectedCategoryId ? "table?category_id=".concat(selectedCategoryId) : "table";
                        _context.p = 1;
                        _context.n = 2;
                        return _this.rest.get(url);
                      case 2:
                        result = _context.v;
                        table.innerHTML = result.data;
                        _context.n = 4;
                        break;
                      case 3:
                        _context.p = 3;
                        _t = _context.v;
                        _this.onError(_t);
                      case 4:
                        _context.p = 4;
                        _this.emit("loading", false, table);
                        return _context.f(4);
                      case 5:
                        return _context.a(2);
                    }
                  }, _callee, null, [[1, 3, 4, 5]]);
                }));
                return function (_x) {
                  return _ref2.apply(this, arguments);
                };
              }());
            case 1:
              return _context2.a(2);
          }
        }, _callee2);
      })));
      _defineProperty(this, "getSelectedCategoryId", function () {
        var categoryFilter = document.getElementById("category-filter");
        return categoryFilter ? categoryFilter.value : "";
      });
      _defineProperty(this, "onLoading", function () {
        var loading = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
        var elem = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
        if (elem instanceof Element) {
          var method = loading ? "add" : "remove";
          elem.classList[method](_classPrivateFieldGet2(_Options, _this).classes.loading);
        }
      });
      _defineProperty(this, "documentClickHandler", /*#__PURE__*/function () {
        var _ref3 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(event) {
          var _classPrivateFieldGet4, button, _classPrivateFieldGet5, _button, active, $button, productID, inStore, _t2;
          return _regenerator().w(function (_context3) {
            while (1) switch (_context3.p = _context3.n) {
              case 0:
                _classPrivateFieldGet4 = _classPrivateFieldGet2(_Options, _this), button = _classPrivateFieldGet4.selectors.button;
                if (!event.target.closest(button)) {
                  _context3.n = 8;
                  break;
                }
                event.preventDefault();
                _classPrivateFieldGet5 = _classPrivateFieldGet2(_Options, _this), _button = _classPrivateFieldGet5.selectors.button, active = _classPrivateFieldGet5.classes.active;
                $button = event.target.closest(_button);
                productID = parseInt($button.dataset.id);
                _this.emit("loading", true, $button);
                _context3.p = 1;
                inStore = _classPrivateFieldGet2(_Store, _this).some(function (data) {
                  if (data.products && data.products.includes(productID)) {
                    return true;
                  }
                });
                if (!inStore) {
                  _context3.n = 3;
                  break;
                }
                $button.classList.remove(active);
                _context3.n = 2;
                return _this.deleteProduct(productID);
              case 2:
                _context3.n = 5;
                break;
              case 3:
                _context3.n = 4;
                return _this.postProduct(productID);
              case 4:
                $button.classList.add(active);
              case 5:
                _context3.n = 7;
                break;
              case 6:
                _context3.p = 6;
                _t2 = _context3.v;
                _this.onError(_t2);
              case 7:
                _context3.p = 7;
                _this.emit("loading", false, $button);
                _this.emit("updated");
                return _context3.f(7);
              case 8:
                return _context3.a(2);
            }
          }, _callee3, null, [[1, 6, 7, 8]]);
        }));
        return function (_x2) {
          return _ref3.apply(this, arguments);
        };
      }());
      _defineProperty(this, "postProduct", /*#__PURE__*/function () {
        var _ref4 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(productID, body) {
          var result;
          return _regenerator().w(function (_context4) {
            while (1) switch (_context4.n) {
              case 0:
                _context4.n = 1;
                return _classPrivateFieldGet2(_Rest, _this).post("product/".concat(productID), body);
              case 1:
                result = _context4.v;
                if (!result.ok) {
                  _context4.n = 2;
                  break;
                }
                _classPrivateFieldSet2(_Store, _this, result.data);
                _this.emit("post-product", result);
                _context4.n = 3;
                break;
              case 2:
                throw result;
              case 3:
                return _context4.a(2, result);
            }
          }, _callee4);
        }));
        return function (_x3, _x4) {
          return _ref4.apply(this, arguments);
        };
      }());
      _defineProperty(this, "deleteProduct", /*#__PURE__*/function () {
        var _ref5 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(productID, body) {
          var result;
          return _regenerator().w(function (_context5) {
            while (1) switch (_context5.n) {
              case 0:
                _context5.n = 1;
                return _classPrivateFieldGet2(_Rest, _this)["delete"]("product/".concat(productID), body);
              case 1:
                result = _context5.v;
                if (!result.ok) {
                  _context5.n = 2;
                  break;
                }
                _classPrivateFieldSet2(_Store, _this, result.data);
                _this.emit("delete-product", result);
                _context5.n = 3;
                break;
              case 2:
                throw result;
              case 3:
                return _context5.a(2, result);
            }
          }, _callee5);
        }));
        return function (_x5, _x6) {
          return _ref5.apply(this, arguments);
        };
      }());
      _defineProperty(this, "on", function (event, callback) {
        _classPrivateFieldGet2(_Event, _this).on("".concat(_classPrivateFieldGet2(_Name, _this), ":").concat(event), callback);
        return _this;
      });
      _defineProperty(this, "off", function (event, callback) {
        _classPrivateFieldGet2(_Event, _this).off("".concat(_classPrivateFieldGet2(_Name, _this), ":").concat(event), callback);
        return _this;
      });
      _defineProperty(this, "emit", function (event) {
        var _classPrivateFieldGet6;
        for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
          args[_key - 1] = arguments[_key];
        }
        (_classPrivateFieldGet6 = _classPrivateFieldGet2(_Event, _this)).emit.apply(_classPrivateFieldGet6, ["".concat(_classPrivateFieldGet2(_Name, _this), ":").concat(event)].concat(args));
        return _this;
      });
      _defineProperty(this, "destroy", function () {
        var completely = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
        _this.emit("".concat(_classPrivateFieldGet2(_Name, _this), ":destroy"), completely);
        _classPrivateFieldGet2(_Event, _this).destroy();
        return _this;
      });
      _defineProperty(this, "show", function () {
        var _classPrivateFieldGet7;
        (_classPrivateFieldGet7 = _classPrivateFieldGet2(_Message, _this)).show.apply(_classPrivateFieldGet7, arguments);
      });
      _classPrivateFieldSet2(_Options, this, options);
      _classPrivateFieldSet2(_Name, this, name);
      var _classPrivateFieldGet8 = _classPrivateFieldGet2(_Options, this),
        nonce = _classPrivateFieldGet8.nonce,
        rest = _classPrivateFieldGet8.rest;
      _classPrivateFieldSet2(_Rest, this, restApi(rest + "/" + name, {
        nonce: nonce
      }));
    }
    return _createClass(Core, [{
      key: "initEvents",
      value: function initEvents() {
        this.on("loading", this.onLoading);
        this.on("max", this.onMaximum);
        this.on("post-product", this.onPostProduct);
        this.on("delete-product", this.onDeleteProduct);
        this.on("mount", this.updateCounters);
        this.on("updated", this.updateCounters);
        this.on("updated", this.updateTables);
        document.addEventListener("click", this.documentClickHandler);
      }
    }, {
      key: "onError",
      value: function onError(error) {
        if (error.code) {
          this.emit(error.code, error);
        }
      }
    }, {
      key: "options",
      get: function get() {
        return _classPrivateFieldGet2(_Options, this);
      }
    }, {
      key: "rest",
      get: function get() {
        return _classPrivateFieldGet2(_Rest, this);
      }
    }, {
      key: "store",
      get: function get() {
        return _classPrivateFieldGet2(_Store, this);
      },
      set: function set(value) {
        _classPrivateFieldSet2(_Store, this, value);
      }
    }, {
      key: "tables",
      get: function get() {
        return _classPrivateFieldGet2(_Tables, this);
      }
    }]);
  }();

  var Compare = /*#__PURE__*/function (_Core) {
    function Compare() {
      var _this;
      var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      _classCallCheck(this, Compare);
      _this = _callSuper(this, Compare, ['compare', options]);
      _defineProperty(_this, "tableClickHandler", /*#__PURE__*/function () {
        var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(e) {
          var button, _button, productID, _t, _t2;
          return _regenerator().w(function (_context) {
            while (1) switch (_context.p = _context.n) {
              case 0:
                if (!e.target.closest('[data-action="clear"]')) {
                  _context.n = 5;
                  break;
                }
                e.preventDefault();
                button = e.target.closest('[data-action="clear"]');
                _this.emit('loading', true, button);
                _context.p = 1;
                _context.n = 2;
                return _this.clearCompare();
              case 2:
                _context.n = 4;
                break;
              case 3:
                _context.p = 3;
                _t = _context.v;
                _superPropGet((Compare), "onError", _this, 3)([_t]);
              case 4:
                _context.p = 4;
                _this.emit('loading', false, button);
                _this.emit('updated');
                return _context.f(4);
              case 5:
                if (!e.target.closest(_this.options.selectors.remove)) {
                  _context.n = 10;
                  break;
                }
                e.preventDefault();
                _button = e.target.closest(_this.options.selectors.remove);
                productID = parseInt(_button.dataset.id);
                _this.emit('loading', true, _button);
                _context.p = 6;
                _context.n = 7;
                return _this.deleteProduct(productID);
              case 7:
                _context.n = 9;
                break;
              case 8:
                _context.p = 8;
                _t2 = _context.v;
                _this.onError(_t2);
              case 9:
                _context.p = 9;
                _this.emit('loading', false, _button);
                _this.emit('updated');
                return _context.f(9);
              case 10:
                if (e.target.closest(_this.options.selectors.collapse)) {
                  e.preventDefault();
                  e.target.closest(_this.options.selectors.collapse).parentNode.classList.toggle(_this.options.classes.collapse);
                }
              case 11:
                return _context.a(2);
            }
          }, _callee, null, [[6, 8, 9, 10], [1, 3, 4, 5]]);
        }));
        return function (_x) {
          return _ref.apply(this, arguments);
        };
      }());
      _defineProperty(_this, "clearCompare", /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2() {
        var result;
        return _regenerator().w(function (_context2) {
          while (1) switch (_context2.n) {
            case 0:
              _context2.n = 1;
              return _this.rest["delete"]();
            case 1:
              result = _context2.v;
              if (!result.ok) {
                _context2.n = 2;
                break;
              }
              _this.store = result.data;
              _this.emit('cleared', result);
              _context2.n = 3;
              break;
            case 2:
              throw result;
            case 3:
              return _context2.a(2, result);
          }
        }, _callee2);
      })));
      _defineProperty(_this, "updateTableByCategory", /*#__PURE__*/function () {
        var _ref3 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(e) {
          var selectedCategoryId, result, _t3;
          return _regenerator().w(function (_context3) {
            while (1) switch (_context3.p = _context3.n) {
              case 0:
                selectedCategoryId = e.target.value;
                _this.emit('loading', true);
                _context3.p = 1;
                if (!(selectedCategoryId === '')) {
                  _context3.n = 2;
                  break;
                }
                // Если категория пуста, обновляем все таблицы
                _this.updateTables();
                _context3.n = 4;
                break;
              case 2:
                _context3.n = 3;
                return _this.rest.get("table?category_id=".concat(selectedCategoryId));
              case 3:
                result = _context3.v;
                _this.tables.forEach(function (table) {
                  table.innerHTML = result.data;
                });
              case 4:
                _context3.n = 6;
                break;
              case 5:
                _context3.p = 5;
                _t3 = _context3.v;
                _this.onError(_t3);
              case 6:
                _context3.p = 6;
                _this.emit('loading', false);
                return _context3.f(6);
              case 7:
                return _context3.a(2);
            }
          }, _callee3, null, [[1, 5, 6, 7]]);
        }));
        return function (_x2) {
          return _ref3.apply(this, arguments);
        };
      }());
      _this.initEvents();
      return _this;
    }
    _inherits(Compare, _Core);
    return _createClass(Compare, [{
      key: "initEvents",
      value: function initEvents() {
        var _this2 = this;
        _superPropGet(Compare, "initEvents", this, 3)([]);
        var categoryFilter = document.getElementById('category-filter');
        if (categoryFilter) {
          categoryFilter.addEventListener('change', this.updateTableByCategory);
        }
        this.tables.forEach(function (table) {
          table.addEventListener('click', _this2.tableClickHandler);
        });
      }
    }]);
  }(Core);

  var config = {
    active: 'is-active',
    target: '.js-dcaw-dropdown'
  };
  var dropdown = function () {
    var isClose = true;
    var toggle;
    var parent;
    var _closeHandler = function closeHandler(e) {
      if (!isClose && !parent.contains(e.target)) {
        parent.classList.remove(config.active);
        isClose = true;
        document.removeEventListener('click', _closeHandler, true);
      }
    };
    var clickHandler = function clickHandler(e) {
      toggle = e.target.closest(config.target);
      if (toggle) {
        e.preventDefault();
        e.stopPropagation();
        parent = toggle.parentNode;
        if (parent.classList.contains(config.active)) {
          parent.classList.remove(config.active);
          isClose = true;
        } else {
          parent.classList.add(config.active);
          isClose = false;
          document.addEventListener('click', _closeHandler, true);
        }
      }
    };
    return {
      mount: function mount() {
        document.addEventListener('click', clickHandler);
      }
    };
  }();

  var modalHub = function modalHub(selector) {
    var modal = document.querySelector(selector);
    if (!modal) return;
    var closeBtn = modal ? modal.querySelector(".compare-modal__close") : null;
    var overlay = modal ? modal.querySelector(".compare-modal__overlay") : null;
    var triggerSelector = modal.dataset.triggers.split(",");
    var triggers = document.querySelectorAll(triggerSelector);
    var isOpen = false;
    function openModal() {
      if (!modal) return;
      modal.classList.add("is-active");
      document.body.style.overflow = "hidden";
      isOpen = true;
    }
    function closeModal() {
      if (!modal) return;
      modal.classList.remove("is-active");
      document.body.style.overflow = "";
      isOpen = false;
    }

    /**
     * Unified event binding for all modal closing mechanisms:
     * - Close button
     * - Overlay click
     * - ESC key
     * - Background click
     */
    function bindCloseEvents() {
      if (closeBtn) {
        closeBtn.addEventListener("click", closeModal);
      }
      if (overlay) {
        overlay.addEventListener("click", closeModal);
      }
      document.addEventListener("click", function (e) {
        if (e.target === modal) {
          closeModal();
        }
      });
      document.addEventListener("keydown", function (e) {
        if (e.key === "Escape" && isOpen) {
          closeModal();
        }
      });
    }
    function bindTriggers() {
      triggers = document.querySelectorAll(triggerSelector);
      triggers.forEach(function (trigger) {
        trigger.addEventListener("click", function (e) {
          var btn = e.currentTarget;

          // Custom rule: do not open if button has active compare state
          if (btn.classList.contains("dcaw-compare-btn") && btn.classList.contains("is-active")) {
            return;
          }
          e.preventDefault();
          openModal();
        });
      });
    }
    return {
      init: function init() {
        if (!modal) return;
        bindCloseEvents();
        bindTriggers();
      }
    };
  };

  document.addEventListener("DOMContentLoaded", function () {
    var compareModal = modalHub(".compare-modal");
    if (compareModal) {
      compareModal.init();
    }
    dropdown.mount();
    if ((typeof dcawCompare === "undefined" ? "undefined" : _typeof(dcawCompare)) === "object" && (typeof dcawGeneral === "undefined" ? "undefined" : _typeof(dcawGeneral)) === "object") {
      var compare = new Compare(_objectSpread2(_objectSpread2({}, dcawGeneral), dcawCompare));
      compare.mount();
    }
  });
  var selectElement = document.getElementById("category-filter");
  if (selectElement && typeof NiceSelect__default["default"] === "function") {
    new NiceSelect__default["default"](selectElement, {});
  } else {
    console.warn("NiceSelect is not available or not a constructor.");
  }

}));
//# sourceMappingURL=main.js.map
