"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 ($, elementor, zyre) {
  var ZyreLibrary = {
    Views: {},
    Models: {},
    Collections: {},
    Behaviors: {},
    Layout: null,
    Manager: null,
    Icon3d:
      "data:image/svg+xml;base64, ",
  };

  ZyreLibrary.Models.Template = Backbone.Model.extend({
    defaults: {
      template_id: 0,
      title: "",
      type: "",
      thumbnail: "",
      url: "",
      tags: [],
    },
  });

  ZyreLibrary.Collections.Template = Backbone.Collection.extend({
    model: ZyreLibrary.Models.Template,
  });

  ZyreLibrary.Behaviors.InsertTemplate = Marionette.Behavior.extend({
    ui: {
      insertButton: ".zyre-TemplateLibrary_insert-button",
    },
    events: {
      "click @ui.insertButton": "onInsertButtonClick",
    },
    onInsertButtonClick: function onInsertButtonClick() {
      zyre.library.insertTemplate({
        model: this.view.model,
      });
    },
  });

  ZyreLibrary.Views.EmptyTemplateCollection = Marionette.ItemView.extend({
    id: "elementor-template-library-templates-empty",
    template: "#tmpl-zyre-TemplateLibrary_empty",
    ui: {
      title: ".elementor-template-library-blank-title",
      message: ".elementor-template-library-blank-message",
    },
    modesStrings: {
      empty: {
        title: zyreGetTranslated("templatesEmptyTitle"),
        message: zyreGetTranslated("templatesEmptyMessage"),
      },
      noResults: {
        title: zyreGetTranslated("templatesNoResultsTitle"),
        message: zyreGetTranslated("templatesNoResultsMessage"),
      },
    },
    getCurrentMode: function getCurrentMode() {
      if (zyre.library.getFilter("text")) {
        return "noResults";
      }
      return "empty";
    },
    onRender: function onRender() {
      var modeStrings = this.modesStrings[this.getCurrentMode()];
      this.ui.title.html(modeStrings.title);
      this.ui.message.html(modeStrings.message);
    },
  });

  ZyreLibrary.Views.Loading = Marionette.ItemView.extend({
    template: "#tmpl-zyre-TemplateLibrary_loading",
    id: "zyre-TemplateLibrary_loading",
  });

  ZyreLibrary.Views.Logo = Marionette.ItemView.extend({
    template: "#tmpl-zyre-TemplateLibrary_header-logo",
    className: "zyre-TemplateLibrary_header-logo",
    templateHelpers: function templateHelpers() {
      return {
        title: this.getOption("title"),
      };
    },
  });

  ZyreLibrary.Views.BackButton = Marionette.ItemView.extend({
    template: "#tmpl-zyre-TemplateLibrary_header-back",
    id: "elementor-template-library-header-preview-back",
    className: "zyre-TemplateLibrary_header-back",
    events: function events() {
      return {
        click: "onClick",
      };
    },
    onClick: function onClick() {
      zyre.library.showTemplatesView();
    },
  });

  ZyreLibrary.Views.Menu = Marionette.ItemView.extend({
    template: "#tmpl-zyre-TemplateLibrary_header-menu",
    id: "elementor-template-library-header-menu",
    className: "zyre-TemplateLibrary_header-menu",
    templateHelpers: function templateHelpers() {
      return zyre.library.getTabs();
    },
    ui: {
      menuItem: ".elementor-template-library-menu-item",
    },
    events: {
      "click @ui.menuItem": "onMenuItemClick",
    },
    onMenuItemClick: function onMenuItemClick(event) {
      zyre.library.setFilter("tags", "");
      zyre.library.setFilter("text", "");
      zyre.library.setFilter("type", event.currentTarget.dataset.tab, true);
      zyre.library.showTemplatesView();
    },
  });

  ZyreLibrary.Views.ResponsiveMenu = Marionette.ItemView.extend({
    template: "#tmpl-zyre-TemplateLibrary_header-menu-responsive",
    id: "elementor-template-library-header-menu-responsive",
    className: "zyre-TemplateLibrary_header-menu-responsive",
    ui: {
      items: "> .elementor-component-tab",
    },
    events: {
      "click @ui.items": "onTabItemClick",
    },
    onTabItemClick: function onTabItemClick(event) {
      var $target = $(event.currentTarget),
        device = $target.data("tab");
      zyre.library.channels.tabs.trigger("change:device", device, $target);
    },
  });

  ZyreLibrary.Views.Actions = Marionette.ItemView.extend({
    template: "#tmpl-zyre-TemplateLibrary_header-actions",
    id: "elementor-template-library-header-actions",
    ui: {
      sync: "#zyre-TemplateLibrary_header-sync i",
    },
    events: {
      "click @ui.sync": "onSyncClick",
    },
    onSyncClick: function onSyncClick() {
      var self = this;
      self.ui.sync.addClass("eicon-animation-spin");
      zyre.library.requestLibraryData({
        onUpdate: function onUpdate() {
          self.ui.sync.removeClass("eicon-animation-spin");
          zyre.library.updateBlocksView();
        },
        forceUpdate: true,
        forceSync: true,
      });
    },
  });

  ZyreLibrary.Views.InsertWrapper = Marionette.ItemView.extend({
    template: "#tmpl-zyre-TemplateLibrary_header-insert",
    id: "elementor-template-library-header-preview",
    behaviors: {
      insertTemplate: {
        behaviorClass: ZyreLibrary.Behaviors.InsertTemplate,
      },
    },
  });

  ZyreLibrary.Views.Preview = Marionette.ItemView.extend({
    template: "#tmpl-zyre-TemplateLibrary_preview",
    className: "zyre-TemplateLibrary_preview",
    ui: function ui() {
      return {
        iframe: "> iframe",
      };
    },
    onRender: function onRender() {
      this.ui.iframe.attr("src", this.getOption("url")).hide();
      var self = this,
        loadingScreen = new ZyreLibrary.Views.Loading().render();

      this.$el.append(loadingScreen.el);
      this.ui.iframe.on("load", function () {
        self.$el.find("#zyre-TemplateLibrary_loading").remove();
        self.ui.iframe.show();
      });
    },
  });

  ZyreLibrary.Views.Notice = Marionette.ItemView.extend({
    template: "#tmpl-zyre-TemplateLibrary_notice",
    className: "zyre-TemplateLibrary_notice-wrapper",
  });

  ZyreLibrary.Views.TemplateCollection = Marionette.CompositeView.extend({
    template: "#tmpl-zyre-TemplateLibrary_templates",
    id: "zyre-TemplateLibrary_templates",
    className: function className() {
      return (
        "zyre-TemplateLibrary_templates zyre-TemplateLibrary_templates--" +
        zyre.library.getFilter("type")
      );
    },
    childViewContainer: "#zyre-TemplateLibrary_templates-list",
    emptyView: function emptyView() {
      return new ZyreLibrary.Views.EmptyTemplateCollection();
    },
    ui: {
      templatesWindow: ".zyre-TemplateLibrary_templates-window",
      textFilter: "#zyre-TemplateLibrary_search",
      tagsFilter: "#zyre-TemplateLibrary_filter-tags",
      filterBar: "#zyre-TemplateLibrary_toolbar-filter",
      counter: "#zyre-TemplateLibrary_toolbar-counter",
    },
    events: {
      "input @ui.textFilter": "onTextFilterInput",
      "click @ui.tagsFilter li": "onTagsFilterClick",
    },
    getChildView: function getChildView(childModel) {
      return ZyreLibrary.Views.Template;
    },
    initialize: function initialize() {
      this.listenTo(
        zyre.library.channels.templates,
        "filter:change",
        this._renderChildren,
      );
    },
    filter: function filter(childModel) {
      var filterTerms = zyre.library.getFilterTerms(),
        passingFilter = true;
      _.each(filterTerms, function (filterTerm, filterTermName) {
        var filterValue = zyre.library.getFilter(filterTermName);
        if (!filterValue) {
          return;
        }
        if (filterTerm.callback) {
          var callbackResult = filterTerm.callback.call(
            childModel,
            filterValue,
          );
          if (!callbackResult) {
            passingFilter = false;
          }
          return callbackResult;
        }
      });
      return passingFilter;
    },
    setMasonrySkin: function setMasonrySkin() {
      if (zyre.library.getFilter("type") === "section") {
        var masonry = new elementorModules.utils.Masonry({
          container: this.$childViewContainer,
          items: this.$childViewContainer.children(),
        });
        this.$childViewContainer.imagesLoaded(masonry.run.bind(masonry));
      }
    },
    onRenderCollection: function onRenderCollection() {
      this.setMasonrySkin();
      this.updatePerfectScrollbar();
      this.setTemplatesFoundText();
    },
    setTemplatesFoundText: function setTemplatesFoundText() {
      var type = zyre.library.getFilter("type"),
        len = this.children.length,
        text = "<b>" + len + "</b>";
      text +=
        type === "section"
          ? " hero section"
          : type === "container"
            ? " block"
            : " " + type;
      if (len > 1) {
        text += "s";
      }
      text += " found";
      this.ui.counter.html(text);
    },
    onTextFilterInput: function onTextFilterInput() {
      var self = this;
      _.defer(function () {
        zyre.library.setFilter("text", self.ui.textFilter.val());
      });
    },
    onTagsFilterClick: function onTagsFilterClick(event) {
      var $select = $(event.currentTarget),
        tag = $select.data("tag");
      zyre.library.setFilter("tags", tag);
      $select.addClass("active").siblings().removeClass("active");
      if (!tag) {
        tag = "Filter";
      } else {
        tag = zyre.library.getTags()[tag];
      }
      this.ui.filterBar
        .find(".zyre-TemplateLibrary_filter-btn")
        .html(tag + ' <i class="eicon-caret-down"></i>');
    },
    updatePerfectScrollbar: function updatePerfectScrollbar() {
      if (!this.perfectScrollbar) {
        this.perfectScrollbar = new PerfectScrollbar(
          this.ui.templatesWindow[0],
          {
            suppressScrollX: true,
          },
        ); // The RTL is buggy, so always keep it LTR.
      }
      this.perfectScrollbar.isRtl = false;
      this.perfectScrollbar.update();
    },
    setTagsFilterHover: function setTagsFilterHover() {
      var self = this;
      self.ui.filterBar.hoverIntent(
        function () {
          self.ui.tagsFilter.css("display", "block");
          self.ui.filterBar
            .find(".zyre-TemplateLibrary_filter-btn i")
            .addClass("eicon-caret-down")
            .removeClass("eicon-caret-right");
        },
        function () {
          self.ui.tagsFilter.css("display", "none");
          self.ui.filterBar
            .find(".zyre-TemplateLibrary_filter-btn i")
            .addClass("eicon-caret-right")
            .removeClass("eicon-caret-down");
        },
        {
          sensitivity: 50,
          interval: 150,
          timeout: 100,
        },
      );
    },
    onRender: function onRender() {
      // Render notice before list
      var noticeView = new ZyreLibrary.Views.Notice();
      this.$el.prepend(noticeView.render().el);

      this.setTagsFilterHover();
      this.updatePerfectScrollbar();
    },
  });

  ZyreLibrary.Views.Template = Marionette.ItemView.extend({
    template: "#tmpl-zyre-TemplateLibrary_template",
    className: "zyre-TemplateLibrary_template",
    ui: {
      previewButton:
        ".zyre-TemplateLibrary_preview-button, .zyre-TemplateLibrary_template-preview",
    },
    events: {
      "click @ui.previewButton": "onPreviewButtonClick",
    },
    behaviors: {
      insertTemplate: {
        behaviorClass: ZyreLibrary.Behaviors.InsertTemplate,
      },
    },
    onPreviewButtonClick: function onPreviewButtonClick() {
      zyre.library.showPreviewView(this.model);
    },
  });

  ZyreLibrary.Modal = elementorModules.common.views.modal.Layout.extend({
    getModalOptions: function getModalOptions() {
      return {
        id: "zyre-TemplateLibrary_modal",
        hide: {
          onOutsideClick: false,
          onEscKeyPress: true,
          onBackgroundClick: false,
        },
      };
    },
    getTemplateActionButton: function getTemplateActionButton(templateData) {
      var templateName = "insert-button",
        viewId = "#tmpl-zyre-TemplateLibrary_" + templateName,
        template = Marionette.TemplateCache.get(viewId);
      return Marionette.Renderer.render(template);
    },
    showLogo: function showLogo(args) {
      this.getHeaderView().logoArea.show(new ZyreLibrary.Views.Logo(args));
    },
    showDefaultHeader: function showDefaultHeader() {
      this.showLogo({
        title: "TEMPLATES",
      });
      var headerView = this.getHeaderView();

      headerView.tools.show(new ZyreLibrary.Views.Actions());
      headerView.menuArea.show(new ZyreLibrary.Views.Menu());
      // headerView.menuArea.reset();
    },
    showPreviewView: function showPreviewView(templateModel) {
      var headerView = this.getHeaderView();

      headerView.menuArea.show(new ZyreLibrary.Views.ResponsiveMenu());
      headerView.logoArea.show(new ZyreLibrary.Views.BackButton());
      headerView.tools.show(
        new ZyreLibrary.Views.InsertWrapper({
          model: templateModel,
        }),
      );
      this.modalContent.show(
        new ZyreLibrary.Views.Preview({
          url: templateModel.get("url"),
        }),
      );
    },
    showTemplatesView: function showTemplatesView(templatesCollection) {
      this.showDefaultHeader();
      this.modalContent.show(
        new ZyreLibrary.Views.TemplateCollection({
          collection: templatesCollection,
        }),
      );
    },
  });

  ZyreLibrary.Manager = function () {
    var modal,
      tags,
      typeTags,
      self = this,
      templatesCollection,
      errorDialog,
      FIND_SELECTOR =
        ".elementor-add-new-section .elementor-add-section-drag-title",
      $openLibraryButton = `<div class="elementor-add-section-area-button elementor-add-zyre-button"><img src="${ZyreLibrary.Icon3d}" width="40"></div>`,
      devicesResponsiveMap = {
        desktop: "100%",
        tab: "768px",
        mobile: "360px",
      };
    this.atIndex = -1;
    this.channels = {
      tabs: Backbone.Radio.channel("tabs"),
      templates: Backbone.Radio.channel("templates"),
    };
    function addZyreTemplatesOpenButton(e, a) {
      var $elementorAddSection = $(e.target)
        .parents(a)
        .prev(".elementor-add-section");
      if (!$elementorAddSection.find(".elementor-add-zyre-button").length) {
        $elementorAddSection.find(FIND_SELECTOR).before($openLibraryButton);
      }
    }
    function addLibraryModalOpenButton($previewContents) {
      var $addNewSection = $previewContents.find(FIND_SELECTOR);
      if (
        $addNewSection.length &&
        !$previewContents.find(".elementor-add-zyre-button").length
      ) {
        $addNewSection.before($openLibraryButton);
      }
      $previewContents.on(
        "click.onZyreTemplatesOpenButton",
        ".elementor-editor-section-settings .elementor-editor-element-add",
        function (e) {
          addZyreTemplatesOpenButton(e, ".elementor-top-section");
        },
      );
      $previewContents.on(
        "click.onZyreTemplatesOpenButton",
        ".elementor-editor-container-settings .elementor-editor-element-add",
        function (e) {
          addZyreTemplatesOpenButton(e, ".e-parent");
        },
      );
    }
    function onDeviceChange(device, $target) {
      $target
        .addClass("elementor-active")
        .siblings()
        .removeClass("elementor-active");
      var width =
        devicesResponsiveMap[device] || devicesResponsiveMap["desktop"];
      $(".zyre-TemplateLibrary_preview").css("width", width);
    }
    function onPreviewLoaded() {
      var $previewContents = window.elementor.$previewContents,
        time = setInterval(function () {
          addLibraryModalOpenButton($previewContents);
          $previewContents.find(".elementor-add-new-section").length > 0 &&
            clearInterval(time);
        }, 100);
      $previewContents.on(
        "click.onZyreAddTemplateButton",
        ".elementor-add-zyre-button",
        self.showModal.bind(self),
      );
      this.channels.tabs.on("change:device", onDeviceChange);
    }
    this.updateBlocksView = function () {
      self.setFilter("tags", "", true);
      self.setFilter("text", "", true);
      self.getModal().showTemplatesView(templatesCollection);
    };
    this.setFilter = function (name, value, silent) {
      self.channels.templates.reply("filter:" + name, value);
      if (!silent) {
        self.channels.templates.trigger("filter:change");
      }
    };
    this.getFilter = function (name) {
      return self.channels.templates.request("filter:" + name);
    };
    this.getFilterTerms = function () {
      return {
        tags: {
          callback: function callback(value) {
            return _.any(this.get("tags"), function (tag) {
              return tag.indexOf(value) >= 0;
            });
          },
        },
        text: {
          callback: function callback(value) {
            value = value.toLowerCase();
            if (this.get("title").toLowerCase().indexOf(value) >= 0) {
              return true;
            }
            return _.any(this.get("tags"), function (tag) {
              return tag.indexOf(value) >= 0;
            });
          },
        },
        type: {
          callback: function callback(value) {
            return this.get("type") === value;
          },
        },
      };
    };
    this.showModal = function () {
      self.getModal().showModal();
      self.showTemplatesView();
    };
    this.closeModal = function () {
      this.getModal().hideModal();
    };
    this.getModal = function () {
      if (!modal) {
        modal = new ZyreLibrary.Modal();
      }
      return modal;
    };
    this.init = function () {
      self.setFilter("type", "section", true);
      elementor.on("preview:loaded", onPreviewLoaded.bind(this));
    };
    this.getTabs = function () {
      var type = this.getFilter("type"),
        tabs = {
          section: {
            title: "Hero Sections",
          },
          container: {
            title: "Blocks",
          },
          page: {
            title: "Pages",
          },
        };
      _.each(tabs, function (obj, key) {
        if (type === key) {
          tabs[type].active = true;
        }
      });
      return {
        tabs: tabs,
      };
    };
    this.getTags = function () {
      return tags;
    };
    this.getTypeTags = function () {
      var type = self.getFilter("type");
      return typeTags[type];
    };
    this.showTemplatesView = function () {
      self.setFilter("tags", "", true);
      self.setFilter("text", "", true);
      if (!templatesCollection) {
        self.loadTemplates(function () {
          self.getModal().showTemplatesView(templatesCollection);
        });
      } else {
        self.getModal().showTemplatesView(templatesCollection);
      }
    };
    this.showPreviewView = function (templateModel) {
      self.getModal().showPreviewView(templateModel);
    };
    this.loadTemplates = function (_onUpdate) {
      self.requestLibraryData({
        onBeforeUpdate: self.getModal().showLoadingView.bind(self.getModal()),
        onUpdate: function onUpdate() {
          self.getModal().hideLoadingView();
          if (_onUpdate) {
            _onUpdate();
          }
        },
      });
    };
    this.requestLibraryData = function (options) {
      if (templatesCollection && !options.forceUpdate) {
        if (options.onUpdate) {
          options.onUpdate();
        }
        return;
      }
      if (options.onBeforeUpdate) {
        options.onBeforeUpdate();
      }
      var ajaxOptions = {
        data: {},
        success: function success(data) {
          templatesCollection = new ZyreLibrary.Collections.Template(
            data.templates,
          );
          if (data.tags) {
            tags = data.tags;
          }
          if (data.type_tags) {
            typeTags = data.type_tags;
          }
          if (options.onUpdate) {
            options.onUpdate();
          }
        },
      };

      if (options.forceSync) {
        ajaxOptions.data.sync = true;
      }
      elementorCommon.ajax.addRequest("get_zyreladdons_library_data", ajaxOptions);
    };
    this.requestTemplateData = function (template_id, ajaxOptions) {
      var options = {
        unique_id: template_id,
        data: {
          edit_mode: true,
          display: true,
          template_id: template_id,
        },
      };
      if (ajaxOptions) {
        jQuery.extend(true, options, ajaxOptions);
      }
      elementorCommon.ajax.addRequest("get_zyreladdons_template_data", options);
    };
    this.insertTemplate = function (args) {
      var model = args.model,
        self = this;
      self.getModal().showLoadingView();
      self.requestTemplateData(model.get("template_id"), {
        success: function success(data) {
          self.getModal().hideLoadingView();
          self.getModal().hideModal();
          var options = {};
          if (self.atIndex !== -1) {
            options.at = self.atIndex;
          }
          $e.run("document/elements/import", {
            model: model,
            data: data,
            options: options,
          });
          self.atIndex = -1;
        },
        error: function error(data) {
          self.showErrorDialog(data);
        },
        complete: function complete(data) {
          self.getModal().hideLoadingView();
          window.elementor.$previewContents
            .find(".elementor-add-section .elementor-add-section-close")
            .click();
        },
      });
    };
    this.showErrorDialog = function (errorMessage) {
      if ("object" === _typeof(errorMessage)) {
        var message = "";
        _.each(errorMessage, function (error) {
          message += "<div>" + error.message + ".</div>";
        });
        errorMessage = message;
      } else if (errorMessage) {
        errorMessage += ".";
      } else {
        errorMessage = "<i>&#60;The error message is empty&#62;</i>";
      }
      self
        .getErrorDialog()
        .setMessage(
          "The following error(s) occurred while processing the request:" +
            '<div id="elementor-template-library-error-info">' +
            errorMessage +
            "</div>",
        )
        .show();
    };
    this.getErrorDialog = function () {
      if (!errorDialog) {
        errorDialog = elementorCommon.dialogsManager.createWidget("alert", {
          id: "elementor-template-library-error-dialog",
          headerMessage: "An error occurred",
        });
      }
      return errorDialog;
    };
  };

  zyre.library = new ZyreLibrary.Manager();
  zyre.library.init();
  window.zyre = zyre;
})(jQuery, window.elementor, window.zyre || {});
