(function ($) {
  "use strict";

  /**
   * JavaScript code for admin dashboard.
   *
   */

  $(function () {
    /* Preloader */
    $("#eventful_view_options .eventful-metabox").css("visibility", "hidden");

    // Initial setup
    var layoutValue = $(
      ".eventful-layout-preset .eventful--sibling.eventful--active",
    )
      .find("input")
      .val();

    // Event listener for layout change
    $(".eventful-layout-preset .eventful--sibling").on(
      "change",
      "input",
      function (event) {
        layoutValue = $(this).val();
      },
    );

    // Get the last activated or selected layout.
    var lastSelectedOption = $(
      'input[name="eventful_layouts[eventful_layout_preset]"]:checked',
    ).val();
    $('input[name="eventful_layouts[eventful_layout_preset]"]').on(
      "change",
      function () {
        if (!$(this).is(":disabled")) {
          lastSelectedOption = $(this).val();
        }
      },
    );
    // Get the last activated or selected layout.
    var lastSelectedContentOrientation = "default";
    $('input[name="eventful_view_options[content_template_style]"]').on(
      "change",
      function () {
        if (!$(this).is(":disabled")) {
          lastSelectedContentOrientation = $(this).val();
        }
      },
    );

    // Revert the selection to the last valid activated option that was selected before if the disabled/pro option is chosen.
    $("#publishing-action").on("click", "#publish", function (e) {
      if (
        $('input[name="eventful_layouts[eventful_layout_preset]"]:checked').is(
          ":disabled",
        )
      ) {
        $(
          'input[name="eventful_layouts[eventful_layout_preset]"][value="' +
            lastSelectedOption +
            '"]',
        ).prop("checked", true);
      }
      if (
        $(
          'input[name="eventful_view_options[content_template_style]"]:checked',
        ).is(":disabled")
      ) {
        $(
          'input[name="eventful_view_options[content_template_style]"][value="' +
            lastSelectedContentOrientation +
            '"]',
        ).prop("checked", true);
      }
    });
    // Disable specific select options by their values
    var valuesToDisable = ["1", "2", "3", "4", "5"];

    valuesToDisable.forEach(function (value) {
      $(".pro-overlay-options-select")
        .find('select option[value="' + value + '"]')
        .attr("disabled", "disabled")
        .addClass("eventful_pro_only");
    });

    var eventful_layout_type = $(
      "#eventful-section-eventful_layouts_1 .eventful-field-layout_preset .eventful-siblings .eventful--sibling",
    );
    var eventful_get_layout_value = $(
      "#eventful-section-eventful_layouts_1 .eventful-field-layout_preset .eventful-siblings .eventful--sibling.eventful--active",
    )
      .find("input")
      .val();

    // Carousel Layout.
    if (
      eventful_get_layout_value !== "carousel_layout" ||
      eventful_get_layout_value === "slider"
    ) {
      $(
        ".display_options .eventful-field-section_tab a.section_tab_0",
      ).trigger("click");
      $(
        ".display_options .eventful-field-section_tab a.section_tab_2",
      ).hide();
      $(
        "#eventful_view_options .eventful-nav ul li.menu-item_eventful_view_options_3",
      ).show();
    } else {
      $(
        "#eventful_view_options .eventful-nav ul li.menu-item_eventful_view_options_3",
      ).hide();
      $(
        ".display_options .eventful-field-section_tab a.section_tab_2",
      ).show();
      $(
        "#eventful_view_options .eventful-nav ul li.menu-item_eventful_view_options_1 a",
      ).trigger("click");
    }

    /**
     * Show/Hide tabs on changing of layout.
     */
    $(eventful_layout_type).on("change", "input", function (event) {
      var eventful_get_layout_value = $(this).val();

      // Carousel Layout.
      if (
        eventful_get_layout_value !== "carousel_layout" ||
        eventful_get_layout_value === "slider"
      ) {
        $(
          ".display_options .eventful-field-section_tab a.section_tab_0",
        ).trigger("click");
        $(
          "#eventful_view_options .eventful-nav ul li.menu-item_eventful_view_options_3",
        ).show();
        $(
          ".display_options .eventful-field-section_tab a.section_tab_2",
        ).hide();
      } else {
        $(
          "#eventful_view_options .eventful-nav ul li.menu-item_eventful_view_options_3",
        ).hide();
        $(
          ".display_options .eventful-field-section_tab a.section_tab_2",
        ).show();
        $(
          "#eventful_view_options .eventful-nav ul li.menu-item_eventful_view_options_1 a",
        ).trigger("click");
      }
    });

    /* Preloader js */
    $("#eventful_view_options .eventful-metabox").css({
      backgroundImage: "none",
      visibility: "visible",
      minHeight: "auto",
    });
    $("#eventful_view_options .eventful-nav-metabox li").css("opacity", 1);

    /* Copy to clipboard */
    $(".eventful-shortcode-selectable").on("click", function (e) {
      e.preventDefault();
      eventful_copyToClipboard($(this));
      eventful_SelectText($(this));
      $(this).trigger("focus").select();
      $(".eventful-after-copy-text").animate(
        {
          opacity: 1,
          bottom: 25,
        },
        300,
      );
      setTimeout(function () {
        jQuery(".eventful-after-copy-text").animate(
          {
            opacity: 0,
          },
          200,
        );
        jQuery(".eventful-after-copy-text").animate(
          {
            bottom: 0,
          },
          0,
        );
      }, 2000);
    });
    $(".eventful_input").on("click", function (e) {
      e.preventDefault();
      /* Get the text field */
      var copyText = $(this);
      /* Select the text field */
      copyText.select();
      document.execCommand("copy");
      $(".eventful-after-copy-text").animate(
        {
          opacity: 1,
          bottom: 25,
        },
        300,
      );
      setTimeout(function () {
        jQuery(".eventful-after-copy-text").animate(
          {
            opacity: 0,
          },
          200,
        );
        jQuery(".eventful-after-copy-text").animate(
          {
            bottom: 0,
          },
          0,
        );
      }, 2000);
    });
    function eventful_copyToClipboard(element) {
      var $temp = $("<input>");
      $("body").append($temp);
      $temp.val($(element).text()).select();
      document.execCommand("copy");
      $temp.remove();
    }
    function eventful_SelectText(element) {
      var r = document.createRange();
      var w = element.get(0);
      r.selectNodeContents(w);
      var sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(r);
    }

    /**
     * Live Preview script.
     */

    var is_manage_preview = $("body").hasClass("post-type-eventful");
    var preview_box = $("#eventful_preview_box");

    if (is_manage_preview) {
      var preview_display = $("#eventful_live_preview").hide();
      var action = "eventful_admin_preview";
      var nonce = $("#eventful_metabox_nonceeventful_layouts").val();
    }

    $(document).on(
      "click",
      "#eventful-show-preview:contains(Hide)",
      function (e) {
        e.preventDefault();
        var _this = $(this);
        _this.html(
          '<i class="icofont-eye-open" aria-hidden="true"></i>Show Preview',
        );
        preview_box.html("");
        preview_display.hide();
      },
    );
    $(document).on(
      "click",
      "#eventful-show-preview:not(:contains(Hide))",
      function (e) {
        e.preventDefault();
        var previewJS = window.eventful_vars.previewJS;
        var _data = $("form#post").serialize();
        var _this = $(this);
        var data = {
          action: action,
          data: _data,
          ajax_nonce: nonce,
        };
        $.ajax({
          type: "POST",
          url: ajaxurl,
          data: data,
          error: function (response) {
            console.log(response);
          },
          success: function (response) {
            preview_display.show();
            preview_box.html(response);
            $.getScript(previewJS, function () {
              _this.html(
                '<i class="icofont-eye-blocked" aria-hidden="true"></i>Hide Preview',
              );
              $(document).on("keyup change", function (e) {
                e.preventDefault();
                _this.html(
                  '<i class="icofont-refresh" aria-hidden="true"></i>Update Preview',
                );
              });
              if (is_manage_preview) {
                $("html, body").animate(
                  { scrollTop: preview_display.offset().top - 50 },
                  "slow",
                );
                $(".eventful-preloader").animate({ opacity: 1 }, 600).hide();

                $(".wp-admin .eventful-pagination li").on(
                  "click",
                  function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    e.stopImmediatePropagation();
                    $(".eventful-pagination-not-work").animate(
                      {
                        opacity: 1,
                        bottom: 25,
                      },
                      300,
                    );
                    setTimeout(function () {
                      jQuery(".eventful-pagination-not-work").animate(
                        {
                          opacity: 0,
                        },
                        200,
                      );
                      jQuery(".eventful-pagination-not-work").animate(
                        {
                          bottom: 0,
                        },
                        0,
                      );
                    }, 2500);
                  },
                );
              }
            });
          },
        });
      },
    );
  });

  $(".theme_style_grid").on("change", function () {
    var str = "";
    $(".theme_style_grid option:selected").each(function () {
      str = $(this).val();
    });

    var src = $(".theme_style_grid .eventful-fieldset img").attr("src");
    var result = src.match(/theme\/grid\/(.+)\.webp/);
    src = src.replace(result[1], str);
    $(".theme_style_grid .eventful-fieldset img").attr("src", src);
  });

  $(".theme_style_minimal_list").on("change", function () {
    var str = "";
    $(".theme_style_minimal_list option:selected").each(function () {
      str = $(this).val();
    });

    var src = $(".theme_style_minimal_list .eventful-fieldset img").attr("src");
    var result = src.match(/theme\/minimal-list\/(.+)\.webp/);
    src = src.replace(result[1], str);
    $(".theme_style_minimal_list .eventful-fieldset img").attr("src", src);
  });
})(jQuery);
