(function ($) {
  "use strict";

  const { __, _x, _n, _nx } = wp.i18n;

  /* Tooltip */
  function edith_actions_tooltip() {
    new jBox("Tooltip", {
      attach: ".edith-tooltip",
    });
  }

  /* Delete a shortcode */
  function edith_delete_popup() {
    $("body").on("click", ".edith-shortcode-delete", function (e) {
      var btn = $(this),
        _nonce = btn.data("nonce"),
        shortcode = btn.closest(".edith-shortcodes-list-item-wrapper"),
        id = shortcode.data("id"),
        shortcode_items = btn.closest(".edith-shortcodes-list-items"),
        shortcode_item = shortcode_items.find(
          ".edith-shortcodes-list-item-wrapper"
        );

      e.preventDefault();

      var edith_delete_popup = new jBox("Confirm", {
        id: "edith-shortcode-delete-" + id,
        width: 480,
        height: "auto",
        addClass: "edith-modal",
        closeButton: "box",
        animation: "slide",
        content:
          "<h3>" +
          __(
            "Are you sure to delete this popup shortcode #",
            "edith-framework"
          ) +
          id +
          "?" +
          "</h3>",
        confirmButton: __("Yes", "edith-framework"),
        cancelButton: __("No", "edith-framework"),
        closeOnConfirm: true,
        confirm: function () {
          edith_delete_popup.destroy();
          wp.ajax.send({
            ajax_option: "fire_edith_delete_shortcode",
            data: {
              action: "edith_delete_shortcode",
              _edith_delete_nonce: _nonce,
              _edith_shortcode_id: id,
            },
            beforeSend: function (xhr) {
              btn.addClass("edith-btn-loading");
            },
            success: function (res) {
              btn.removeClass("edith-btn-loading");

              new jBox("Notice", {
                content: res,
                color: "green",
                autoClose: 1200,
                addClass: "edith-notice",
                position: {
                  x: "right",
                  y: "bottom",
                },
                offset: {
                  x: -30,
                  y: -30,
                },
              });

              shortcode.fadeOut(function () {
                shortcode.remove();
              });

              if (shortcode_item.length === 1) {
                shortcode_items.append(
                  '<div class="edith-alert edith-alert-error">' +
                    __(
                      "No Popup ShortCode Found. Please Add Some.",
                      "edith-framework"
                    ) +
                    "</div>"
                );
              }
            },
            error: function (error) {
              alert(error);
            },
          });
        },
      }).open();
    });
  }

  /* Duplicate a Shortcode */
  function edith_duplicate_shortcode() {
    $("body").on("click", ".edith-shortcode-duplicate", function (e) {
      var btn = $(this),
        _nonce = btn.data("nonce"),
        shortcode = btn.closest(".edith-shortcodes-list-item-wrapper"),
        id = shortcode.data("id");

      e.preventDefault();

      var edith_duplicate_shortcode = new jBox("Confirm", {
        id: "edith-shortcode-duplicate-" + id,
        width: 480,
        height: "auto",
        addClass: "edith-modal",
        closeButton: "box",
        animation: "slide",
        content:
          "<h3>" +
          __("Are you sure to duplicate this shortcode #", "edith-framework") +
          id +
          "?" +
          "</h3>",
        confirmButton: __("Yes", "edith-framework"),
        cancelButton: __("No", "edith-framework"),
        confirm: function () {
          edith_duplicate_shortcode.destroy();

          wp.ajax.send({
            ajax_option: "fire_edith_duplicate_shortcode",
            data: {
              action: "edith_duplicate_shortcode",
              _edith_duplicate_nonce: _nonce,
              _edith_shortcode_id: id,
            },
            beforeSend: function (xhr) {
              btn.addClass("edith-btn-loading");
            },
            success: function (res) {
              btn.removeClass("edith-btn-loading");

              new jBox("Notice", {
                content: __("Duplicated Successfully", "edith-framework"),
                color: "green",
                autoClose: 1200,
                addClass: "edith-notice",
                position: {
                  x: "right",
                  y: "bottom",
                },
                offset: {
                  x: -30,
                  y: -30,
                },
              });

              $(".edith-shortcodes-list-items").prepend(res);

              setTimeout(function () {
                $(".edith-c-ripple").remove();
              }, 400);
            },
            error: function (error) {
              alert(error);
            },
          });
        },
      }).open();
    });
  }

  /* Show ShortCode Popup */
  function edith_show_shortcode_popup() {
    $("body").on("click", ".edith-shortcode-popup-trigger", function (e) {
      e.preventDefault();

      var btn = $(this),
        id = btn.data("id"),
        _nonce = btn.data("nonce");

      wp.ajax.send({
        data: {
          action: "edith_fire_show_shortcode",
          _edith_show_shortcode_nonce: _nonce,
          _edith_shortcode_id: id,
        },
        beforeSend: function (xhr) {
          btn.addClass("edith-btn-loading");
        },
        success: function (res) {
          btn.removeClass("edith-btn-loading");

          new jBox("Modal", {
            width: 780,
            height: "auto",
            preventDefault: true,
            addClass:
              "edith-popup-modal edith-shortcode-popup edith-no-padding",
            closeButton: "box",
            animation: "slide",
            title: res.title,
            content: res.content,
          }).open();

          edith_show_shortcode_tabs();
          edith_copy_shortcode();
        },
        error: function (error) {
          alert(error);
        },
      });
    });
  }

  /**
   * Show ShortCode Popup tab
   */
  function edith_show_shortcode_tabs() {
    $(".edith-shortcode-tabs").each(function () {
      var t = $(this),
        nav_item = t.find(".edith-shortcode-tabs-nav ul li"),
        nav_first = t.find(".edith-shortcode-tabs-nav ul li:first-child"),
        content = t.find(".edith-shortcode-tab-content"),
        content_first = t.find(".edith-shortcode-tab-content:first");

      // Show the first tab and hide the rest
      nav_first.addClass("edith-shortcode-nav-active");
      content.hide();
      content_first.show();

      // Click function
      nav_item.click(function (e) {
        e.preventDefault();
        nav_item.removeClass("edith-shortcode-nav-active");
        $(this).addClass("edith-shortcode-nav-active");
        content.hide();

        var activeTab = $(this).find("a").attr("href");
        $(activeTab).fadeIn();
        return false;
      });
    });
  }

  /**
   * Copy ShortCode to clipboard
   */
  function edith_copy_shortcode() {
    $("body").on("click", ".edith-copy-shortcode", function (e) {
      var range = document.createRange();
      var sel = window.getSelection();
      range.setStartBefore(this.firstChild);
      range.setEndAfter(this.lastChild);
      sel.removeAllRanges();
      sel.addRange(range);

      try {
        var successful = document.execCommand("copy");
      } catch (err) {
        console.error(__("Unable to copy", "edith-framework"));
      }
    });
  }

  /**
   * Save Active Nav Tab for meta
   */
  function edith_switch_meta_nav_tabs(index){
    $('.edith-nav-metabox li a').removeClass('edith-active');
    $('.edith-nav-metabox li a[data-index='+index+']').addClass('edith-active');
    $('.edith-section').edith_reload_script();
    $('.edith-sections .edith-section').addClass('hidden');
    $('.edith-sections .edith-section[data-index='+index+']').removeClass('hidden');
  }

  function edith_save_meta_nav_tab(){
    if(typenow){
      $('.edith-nav-metabox li').each(function(index){
        $(this).find('a').attr('data-index', index + 1);
      });
      $('.edith-sections .edith-section').each(function(index){
        $(this).attr('data-index', index + 1);
      });


      $('.edith-nav-metabox li a').on('click', function(e) {
        localStorage.setItem('edith' + typenow + '_activeTab', $(this).data('index'));
        edith_switch_meta_nav_tabs($(this).data('index'));
      });
  
      var activeTab = localStorage.getItem('edith' + typenow + '_activeTab');
      if(activeTab){
        edith_switch_meta_nav_tabs(activeTab);
      }
    }
  }

  /**
   * Meta sidebar min height
   */
  $(window).resize(function () {
    var headerHeight = $("#post-body-content").outerHeight(),
      adminbarHeight = $("#wpadminbar").outerHeight();

    if ($(window).innerWidth() > 782) {
      $(".edith-wrapper").css(
        "min-height",
        $(window).height() - (headerHeight + adminbarHeight)
      );
    } else {
      $(".edith-wrapper").removeAttr("style");
    }
  });

  $(window).trigger("resize");

  /**
   * Image select tooltip
   */
  $(".edith--image-group .edith--image").each(function () {
    var $this = $(this),
        imgSrc = $this.find('img').prop('src');

        new jBox('Tooltip', {
            attach: $this,
            content: '<img style="max-width: 300px" src="'+imgSrc+'">',
        });
  });


  $(document).ajaxComplete(function (event, xhr, options) {});

  $(document).ready(function () {
    setTimeout(function () {
      $(".edith-c-ripple").remove();
    }, 400);
    edith_delete_popup();
    edith_duplicate_shortcode();
    edith_show_shortcode_popup();
    edith_actions_tooltip();
    edith_save_meta_nav_tab();
  });
})(jQuery);
