"use strict";

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); }
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 _objectSpread(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 _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 _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 _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 _superPropBase(t, o) { for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t));); return t; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
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 _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
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 _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, 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 _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
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 _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
!function () {
  "use strict";

  var React = window.React;
  jQuery(function ($) {
    var initialized = false;
    var log = function log() {
      var _console;
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      (_console = console).log.apply(_console, ["[HA Nested Accordion]:"].concat(args));
    };
    var initEditor = function initEditor() {
      var _ref, _$e, _$e$get, _$e2, _$e2$get, _elementor;
      if (initialized) {
        log("Already initialized");
        return true;
      }
      log("Init attempt...");
      if (typeof elementor === "undefined" || typeof $e === "undefined") {
        log("Elementor or $e not ready");
        return false;
      }
      log("Elementor detected");
      var nestedModule = ((_ref = ((_$e = $e) === null || _$e === void 0 || (_$e = _$e.components) === null || _$e === void 0 || (_$e$get = _$e.get) === null || _$e$get === void 0 ? void 0 : _$e$get.call(_$e, "nested-elements/nested-repeater")) || ((_$e2 = $e) === null || _$e2 === void 0 || (_$e2 = _$e2.components) === null || _$e2 === void 0 || (_$e2$get = _$e2.get) === null || _$e2$get === void 0 ? void 0 : _$e2$get.call(_$e2, "nested-elements"))) === null || _ref === void 0 ? void 0 : _ref.exports) || null;
      if (!nestedModule) {
        log("nestedModule not ready");
        return false;
      }
      log("nestedModule loaded");
      var NestedViewBase = nestedModule.NestedViewBase || nestedModule.NestedView;
      var NestedModelBase = nestedModule.NestedRepeaterModel || nestedModule.NestedModelBase;
      if (!NestedViewBase || !NestedModelBase) {
        log("View or Model base missing");
        return false;
      }
      log("View & Model ready");
      var NestedElementBase = (_elementor = elementor) === null || _elementor === void 0 || (_elementor = _elementor.modules) === null || _elementor === void 0 || (_elementor = _elementor.elements) === null || _elementor === void 0 || (_elementor = _elementor.types) === null || _elementor === void 0 ? void 0 : _elementor.NestedElementBase;
      if (typeof NestedElementBase !== "function" || !NestedElementBase.prototype) {
        log("NestedElementBase NOT ready", NestedElementBase);
        return false;
      }
      log("NestedElementBase ready");

      // ─────────────────────────────
      // VIEW
      // ─────────────────────────────
      var HappyNestedAccordionView = /*#__PURE__*/function (_NestedViewBase) {
        function HappyNestedAccordionView() {
          _classCallCheck(this, HappyNestedAccordionView);
          return _callSuper(this, HappyNestedAccordionView, arguments);
        }
        _inherits(HappyNestedAccordionView, _NestedViewBase);
        return _createClass(HappyNestedAccordionView, [{
          key: "getTemplate",
          value: function getTemplate() {
            return function (data) {
              var settings = data.settings || {};
              var items = settings.items || [];
              log("Rendering template", items);
              var accordionHtml = '';
              var defaultActive = settings.default_active || 'first';
              var customActive = parseInt(settings.default_active_custom || 1, 10);

              // items.forEach((item, index) => {
              //     const accordionCount = index + 1;
              //     const title = item?.item_title || `Item #${accordionCount}`;
              //     const isOpen = (defaultActive === 'first' && index === 0) || (defaultActive === 'custom' && customActive === accordionCount);

              //     accordionHtml += `
              //         <details class="ha-n-accordion-item${isOpen ? ' e-active' : ''}"${isOpen ? ' open' : ''} data-accordion-index="${accordionCount}">
              //             <summary class="ha-n-accordion-title"
              //                 role="button"
              //                 aria-expanded="${isOpen ? 'true' : 'false'}"
              //                 data-accordion-index="${accordionCount}"
              //                 tabindex="${index === 0 ? '0' : '-1'}">
              //                 <span class="ha-n-accordion-title-header">
              //                     <span class="ha-n-accordion-item-title-text">${title}</span>
              //                 </span>
              //             </summary>
              //             <div class="ha-n-accordion-content"></div>
              //         </details>
              //     `;
              // });
              items.forEach(function (item, index) {
                var _item$item_icon, _item$item_icon_activ;
                var accordionCount = index + 1;
                var title = (item === null || item === void 0 ? void 0 : item.item_title) || "Item #".concat(accordionCount);
                var titleTag = settings.item_title_tag || 'div';
                var isOpen = defaultActive === 'first' && index === 0 || defaultActive === 'custom' && customActive === accordionCount;
                var iconClass = (item === null || item === void 0 || (_item$item_icon = item.item_icon) === null || _item$item_icon === void 0 ? void 0 : _item$item_icon.value) || '';
                var activeIconClass = (item === null || item === void 0 || (_item$item_icon_activ = item.item_icon_active) === null || _item$item_icon_activ === void 0 ? void 0 : _item$item_icon_activ.value) || iconClass;
                accordionHtml += "\n                                <details class=\"ha-n-accordion-item ".concat(isOpen ? 'e-active' : '', "\"\n                                    ").concat(isOpen ? 'open' : '', "\n                                    data-accordion-index=\"").concat(accordionCount, "\">\n\n                                    <summary class=\"ha-n-accordion-title\"\n                                        role=\"button\"\n                                        aria-expanded=\"").concat(isOpen ? 'true' : 'false', "\"\n                                        data-accordion-index=\"").concat(accordionCount, "\"\n                                        tabindex=\"").concat(index === 0 ? '0' : '-1', "\">\n\n                                        <span class=\"ha-n-accordion-title-header\">\n                                            <").concat(titleTag, " class=\"ha-n-accordion-item-title-text\">\n                                                ").concat(title, "\n                                            </").concat(titleTag, ">\n                                        </span>\n\n                                        ").concat(iconClass ? "\n                                            <span class=\"ha-n-accordion-icon\">\n                                                <span class=\"ha-n-accordion-icon-normal\">\n                                                    <i class=\"".concat(iconClass, "\"></i>\n                                                </span>\n                                                <span class=\"ha-n-accordion-icon-active\">\n                                                    <i class=\"").concat(activeIconClass, "\"></i>\n                                                </span>\n                                            </span>\n                                        ") : '', "\n\n                                    </summary>\n\n                                    <div class=\"ha-n-accordion-content\"></div>\n\n                                </details>\n                            ");
              });
              return "\n                            <div class=\"ha-n-accordion\"\n                                data-default-active=\"".concat(defaultActive, "\"\n                                data-active-index=\"").concat(customActive, "\"\n                                data-multiple-open=\"").concat(settings.multiple_open || 'no', "\">\n                                ").concat(accordionHtml, "\n                            </div>\n                        ");
            };
          }
        }, {
          key: "filter",
          value: function filter(model, index) {
            log("Filter child:", index);
            if (typeof (model === null || model === void 0 ? void 0 : model.set) === 'function') {
              model.set('dataIndex', index + 1);
            } else if (model !== null && model !== void 0 && model.attributes) {
              model.attributes.dataIndex = index + 1;
            }
            return true;
          }
        }, {
          key: "onAddChild",
          value: function onAddChild(child) {
            log("Child added", child);
          }
        }]);
      }(NestedViewBase); // ─────────────────────────────
      // ELEMENT
      // ─────────────────────────────
      var HappyNestedAccordionElement = /*#__PURE__*/function (_NestedElementBase) {
        function HappyNestedAccordionElement() {
          _classCallCheck(this, HappyNestedAccordionElement);
          return _callSuper(this, HappyNestedAccordionElement, arguments);
        }
        _inherits(HappyNestedAccordionElement, _NestedElementBase);
        return _createClass(HappyNestedAccordionElement, [{
          key: "getType",
          value: function getType() {
            return "ha-happy-nested-accordion";
          }
        }, {
          key: "getView",
          value: function getView() {
            return HappyNestedAccordionView;
          }
        }, {
          key: "getModel",
          value: function getModel() {
            return NestedModelBase;
          }
        }, {
          key: "getInitialConfig",
          value: function getInitialConfig() {
            log("Initial config loaded");
            return _objectSpread(_objectSpread({}, _superPropGet(HappyNestedAccordionElement, "getInitialConfig", this, 3)([])), {}, {
              defaults: {
                repeater_title_setting: "item_title"
              }
            });
          }
        }]);
      }(NestedElementBase);
      elementor.elementsManager.registerElementType(new HappyNestedAccordionElement());
      initialized = true;
      log("SUCCESS: Widget Registered");
      return true;
    };

    // ─────────────────────────────
    // FRONTEND HANDLER
    // ─────────────────────────────
    var happynestedaccordion = function happynestedaccordion($scope) {
      var $accordion = $scope.find('.ha-n-accordion');
      if (!$accordion.length) {
        return;
      }
      $accordion.each(function () {
        var $currentAccordion = $(this);
        var multipleOpen = $currentAccordion.data('multiple-open') === 'yes';
        var $items = $currentAccordion.children('.ha-n-accordion-item');
        var setItemState = function setItemState($item, isOpen, animate) {
          var $title = $item.children('.ha-n-accordion-title');
          var $content = $item.children('.ha-n-accordion-content');
          $item.toggleClass('e-active', isOpen);
          $title.toggleClass('e-active', isOpen).attr('aria-expanded', isOpen ? 'true' : 'false');
          if (isOpen) {
            $item.attr('open', 'open');
            if (animate) {
              $content.stop(true, true).hide().slideDown(250);
            } else {
              $content.show();
            }
          } else if (animate) {
            $content.stop(true, true).slideUp(250, function () {
              $item.removeAttr('open');
            });
          } else {
            $content.hide();
            $item.removeAttr('open');
          }
        };
        $items.each(function () {
          var $item = $(this);
          setItemState($item, $item.is('[open]'), false);
        });
        $currentAccordion.off('click.haNestedAccordion keydown.haNestedAccordion');
        $currentAccordion.on('click.haNestedAccordion keydown.haNestedAccordion', '.ha-n-accordion-title', function (e) {
          if (e.type === 'keydown') {
            if (e.key !== 'Enter' && e.key !== ' ') {
              return;
            }
          }
          e.preventDefault();
          var $title = $(this);
          var $item = $title.closest('.ha-n-accordion-item');
          var willOpen = !$item.is('[open]');
          if (willOpen && !multipleOpen) {
            $items.not($item).each(function () {
              setItemState($(this), false, true);
            });
          }
          setItemState($item, willOpen, true);
        });
      });
    };

    // ─────────────────────────────
    // REGISTER FRONTEND HOOK
    // ─────────────────────────────
    if (typeof elementorFrontend !== 'undefined') {
      elementorFrontend.hooks.addAction("frontend/element_ready/ha-happy-nested-accordion.default", happynestedaccordion);
    }

    // ─────────────────────────────
    // INIT SYSTEM
    // ─────────────────────────────
    var startInit = function startInit() {
      log("Starting init loop...");
      var interval = setInterval(function () {
        if (initEditor()) {
          clearInterval(interval);
          log("Init loop stopped");
        }
      }, 150);
    };

    // Editor
    if (window.elementor && elementor.on) {
      log("Hooking into preview:loaded");
      elementor.on('preview:loaded', startInit);
    }

    // Frontend fallback
    jQuery(window).on('elementor/frontend/init', function () {
      log("Frontend init triggered");
      startInit();
    });
  });
}();