"use strict";

!function () {
  "use strict";

  /**
   * Live (no full re-render) editor updates for Visual Tabs.
   *
   * Elementor's default flow re-renders the whole widget (including the nested
   * child containers) on every setting change. For the controls below we
   * intercept renderChanges() on THIS widget's own view prototype, patch the
   * DOM/CSS directly, and return early so Elementor skips renderHTML().
   *
   * Controls patched live:
   *   - service_title              (repeater text -> active item title only)
   *   - prefix_text                (repeater text -> active item prefix only)
   *   - prefix_position            (attribute swap on all titles)
   */
  var WIDGET_TYPE = 'ha-visual-tabs';

  // NOTE: prefix_align_items_before/_after, title_col_width and column_gap are
  // intentionally excluded. They already use render_type => 'ui' (set in the
  // widget PHP), so Elementor applies their CSS live without a full re-render.
  // Only the controls that require custom DOM work are handled here.
  var LIVE_CONTROLS = ['service_title', 'prefix_text', 'prefix_position'];
  function inList(controlName) {
    return -1 !== LIVE_CONTROLS.indexOf(controlName);
  }
  function getWidgetRoot(view) {
    if (!view || !view.$el || !view.$el.length) {
      return null;
    }
    var $root = view.$el.closest('.elementor-widget-ha-visual-tabs');
    if (!$root.length) {
      $root = view.$el.find('.elementor-widget-ha-visual-tabs');
    }
    return $root.length ? $root : null;
  }
  function patchPrefixPosition($root, value) {
    if (!$root || !$root.length) {
      return;
    }
    $root.find('.ha-v-tabs-title-wrap').attr('data-prefix-position', value);
  }
  function getEditedItem(view, $root) {
    var activeIndex = 0;
    try {
      activeIndex = view.container.model.get('editSettings').get('activeItemIndex');
      activeIndex = typeof activeIndex !== 'undefined' ? parseInt(activeIndex, 10) - 1 : 0;
    } catch (e) {
      activeIndex = 0;
    }
    var $items = $root.find('.ha-v-tabs-item');
    if (activeIndex >= 0 && activeIndex < $items.length) {
      return $items.eq(activeIndex);
    }
    var $active = $root.find('.ha-v-tabs-item.e-active');
    return $active.length ? $active : $items.first();
  }
  function patchActiveItemText(view, controlName, value) {
    var $root = getWidgetRoot(view);
    if (!$root || !$root.length) {
      return;
    }
    var $activeItem = getEditedItem(view, $root);
    if (!$activeItem.length) {
      return;
    }
    var $titleWrap = $activeItem.find('.ha-v-tabs-title-wrap').first();
    if (!controlName) {
      return;
    }
    if ('service_title' === controlName) {
      $titleWrap.find('.ha-v-tabs-service-title').text(value);
    } else if ('prefix_text' === controlName) {
      var $number = $titleWrap.find('.ha-v-tabs-service-number');
      if (value) {
        if (!$number.length) {
          $number = jQuery('<span class="ha-v-tabs-service-number"></span>');
          $titleWrap.prepend($number);
        }
        $number.text(value);
      } else if ($number.length) {
        $number.remove();
      }
    }
  }
  function applyLive(view, controlName, value) {
    var $root = getWidgetRoot(view);
    if (!$root || !$root.length) {
      return;
    }
    switch (controlName) {
      case 'prefix_position':
        patchPrefixPosition($root, value);
        break;
      case 'service_title':
      case 'prefix_text':
        patchActiveItemText(view, controlName, value);
        break;
    }
  }
  function patchView() {
    var manager = elementor && elementor.elementsManager;
    if (!manager || !manager.elementTypes || !manager.elementTypes[WIDGET_TYPE]) {
      return false;
    }
    var elementClass = manager.elementTypes[WIDGET_TYPE];
    var ViewClass = elementClass.getView && elementClass.getView();
    if (!ViewClass || !ViewClass.prototype || typeof ViewClass.prototype.renderChanges !== 'function') {
      return false;
    }
    if (ViewClass.prototype.__haNslLivePatched) {
      return true;
    }
    var originalRenderChanges = ViewClass.prototype.renderChanges;
    ViewClass.prototype.renderChanges = function (settings) {
      try {
        // Only intercept when Elementor passes a settings model we can read.
        if (!settings || typeof settings.changedAttributes !== 'function') {
          return originalRenderChanges.apply(this, arguments);
        }
        var changed = settings.changedAttributes();
        var changedKeys = Object.keys(changed);
        if (!changedKeys.length) {
          return originalRenderChanges.apply(this, arguments);
        }
        var hasLive = false;
        var hasOther = false;
        changedKeys.forEach(function (key) {
          if (inList(key)) {
            hasLive = true;
          } else {
            hasOther = true;
          }
        });

        // Only live controls changed -> patch DOM and skip full re-render.
        if (hasLive && !hasOther) {
          var self = this;
          changedKeys.forEach(function (key) {
            applyLive(self, key, changed[key]);
          });
          return;
        }
      } catch (e) {
        // Never let a patching error block Elementor's normal render.
        return originalRenderChanges.apply(this, arguments);
      }

      // Mixed or other-only change -> let Elementor handle normally.
      return originalRenderChanges.apply(this, arguments);
    };
    ViewClass.prototype.__haNslLivePatched = true;
    return true;
  }
  function init() {
    if (typeof elementor === 'undefined') {
      return;
    }
    if (!patchView()) {
      setTimeout(init, 300);
    }
  }
  if (window.elementorCommon && elementorCommon.elements && elementorCommon.elements.$window) {
    elementorCommon.elements.$window.on('elementor:init', init);
  } else {
    jQuery(init);
  }
}();