/**
 * Owl Manager Module
 * Handles the interactive owl button that flies away on click
 */

define(["jquery"], function ($) {
  "use strict";

  var OwlManager = {
    init: function () {
      this.initOwlFlyButton();
      this.observeTabChanges();
    },

    initOwlFlyButton: function () {
      var self = this;

      $(document).on("click", "#owl-fly-button", function () {
        var $owl = $(this);

        $owl.removeClass("pulse-animation");
        $owl.addClass("fly-away");

        setTimeout(function () {
          var nextTarget = $owl.attr("data-next-target");
          var additionalButton = $owl.attr("data-additional-button");

          if (nextTarget) {
            var $targetTab = $(nextTarget);
            if ($targetTab.length) {
              $targetTab.click();
            }
          }

          if (additionalButton) {
            var $addBtn = $(additionalButton);
            if ($addBtn.length) {
              $addBtn.click();
            }
          }
        }, 500);
      });
    },

    observeTabChanges: function () {
      // Reset owl animation when tab becomes visible again
      $(document).on("shown.bs.tab", function (e) {
        var $owl = $("#owl-fly-button");
        if ($owl.length) {
          var $tabPane = $owl.closest(".tab-pane");
          if ($tabPane.hasClass("active")) {
            $owl.removeClass("fly-away");
            // Only add pulse animation if data-should-pulse is true
            if ($owl.data("should-pulse") === true || $owl.data("should-pulse") === "true") {
              $owl.addClass("pulse-animation");
            }
            $owl.css("opacity", "1");
          }
        }
      });
    },
  };

  return OwlManager;
});
