(function ($) {
  "use strict";

  // Utility: Debounce function for performance
  function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
      const later = () => {
        clearTimeout(timeout);
        func(...args);
      };
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
    };
  }

  // Utility: Throttle function for scroll events
  function throttle(func, limit) {
    let inThrottle;
    return function (...args) {
      if (!inThrottle) {
        func.apply(this, args);
        inThrottle = true;
        setTimeout(() => inThrottle = false, limit);
      }
    };
  }

  var $window = $(window);
  var lastScrollTop = 0,
    delta = 5,
    $mainNav = $("#sticky"),
    $mainNavHeight = $mainNav.outerHeight();

  // Optimized scroll handler with throttle
  const handleScroll = throttle(function () {
    const scrollTop = $(window).scrollTop();

    // Skip if scrolled less than delta
    if (Math.abs(lastScrollTop - scrollTop) <= delta) {
      return;
    }

    // Hide/show navbar based on scroll direction
    if (scrollTop > lastScrollTop && scrollTop > $mainNavHeight) {
      $mainNav.css("top", -$mainNavHeight);
    } else {
      if (scrollTop + $(window).height() < $(document).height()) {
        $mainNav.css("top", 0);
      }
    }

    lastScrollTop = scrollTop;
  }, 100);

  $window.on("scroll", handleScroll);

  //*============= menu sticky js =============*//
  function navbarFixed() {
    if ($("#sticky").length) {
      $(window).scroll(function () {
        var scroll = $(window).scrollTop();
        if (scroll) {
          $("#sticky").addClass("navbar_fixed");
        } else {
          $("#sticky").removeClass("navbar_fixed");
        }
      });
    }
  }
  navbarFixed();

  // Optimized body class toggle with debounce
  const handleBodyClass = debounce(function () {
    const scrollTop = $(document).scrollTop();
    $("body").toggleClass("test", scrollTop > 500);
  }, 150);

  $(document).ready(function () {
    $(window).on("scroll", handleBodyClass);
  });

  /*  Menu Click js  */
  function Menu_js() {
    if ($(".submenu").length) {
      $(".submenu > .dropdown-toggle").click(function () {
        var location = $(this).attr("href");
        window.location.href = location;
        return false;
      });
    }
  }

  Menu_js();

  $('a[href="#"]').on("click", function (event) {
    event.preventDefault();
  });

  function Click_menu_hover() {
    if ($(".tab-demo").length) {
      $.fn.tab = function (options) {
        var opts = $.extend({}, $.fn.tab.defaults, options);
        return this.each(function () {
          var obj = $(this);

          $(obj)
            .find(".tabHeader li")
            .on(opts.trigger_event_type, function () {
              $(obj).find(".tabHeader li").removeClass("active");
              $(this).addClass("active");

              $(obj).find(".tabContent .tab-pane").removeClass("active show");
              $(obj)
                .find(".tabContent .tab-pane")
                .eq($(this).index())
                .addClass("active show");
            });
        });
      };
      $.fn.tab.defaults = {
        trigger_event_type: "click", //mouseover | click Ã©Â»ËœÃ¨Â®Â¤Ã¦ËœÂ¯click
      };
    }
  }

  Click_menu_hover();

  function Tab_menu_activator() {
    if ($(".tab-demo").length) {
      $(".tab-demo").tab({
        trigger_event_type: "mouseover",
      });
    }
  }

  Tab_menu_activator();

  $(".mobile_menu_btn").on("click", function () {
    $(".side_menu").addClass("menu-opened");
    $("body").removeClass("menu-is-closed").addClass("menu-is-opened");
    $(".navbar-backdrop").addClass("show");
  });
  // Close handlers
  $(document).on("click", ".close_nav, .navbar-backdrop", function (e) {
    e.preventDefault();
    $(".navbar-backdrop").removeClass("show");
    $(".side_menu").removeClass("menu-opened");
    $("body").removeClass("menu-is-opened").addClass("menu-is-closed");
  });
  // /*--------------- mobile dropdown js--------*/

  $(".navbar-nav > li .mobile_dropdown_icon").on("click", function (e) {
    $(this).parent().find("ul").first().toggle(300);
    $(this).parent().siblings().find("ul").hide(300);
  });

  if ($(".submenu").length) {
    $(".submenu > .dropdown-toggle").on("click", function () {
      var location = $(this).attr("href");
      window.location.href = location;
      return false;
    });
  }
  /*--------------- counterUp js--------*/
  function counterUp() {
    if ($(".counter").length) {
      $(".counter").counterUp({
        delay: 1,
        time: 250,
      });
    }
  }

  counterUp();

  /*--------- WOW js-----------*/
  function bodyScrollAnimation() {
    var scrollAnimate = $("body").data("scroll-animation");
    if (scrollAnimate === true) {
      new WOW({
        mobile: false,
      }).init();
    }
  }
  bodyScrollAnimation();

  // === Back to Top Button with throttle
  var back_top_btn = $("#back-to-top");

  const handleBackToTop = throttle(function () {
    const scrollTop = $(window).scrollTop();
    back_top_btn.toggleClass("show", scrollTop > 300);
  }, 100);

  $(window).on("scroll", handleBackToTop);

  back_top_btn.on("click", function (e) {
    e.preventDefault();
    $("html, body").animate({
      scrollTop: 0
    }, {
      duration: 600,
      easing: 'swing'
    });
  });

  /*--------------- niceSelect js--------*/
  function select() {
    if ($(".custom-select, .nice_select").length) {
      $(".custom-select, .nice_select").niceSelect();
    }
    if ($("#mySelect").length) {
      $("#mySelect").selectpicker();
    }
  }
  select();

  /*--------------- Isotope js--------*/

  if ($(".match-member-isotope").length) {
    $(".match-member-isotope").imagesLoaded(function () {
      var $matchMmberIsotope = $(".match-member-isotope").isotope({
        itemSelector: ".singleIsotopeMember",
        layoutMode: "masonry",
        transformsEnabled: true,
        transitionDuration: "700ms",
      });

      $(".match-filter-widget").on("click", "button", function () {
        var filterValue = $(this).attr("data-filter");
        $matchMmberIsotope.isotope({
          filter: filterValue,
          animationOptions: {
            animationDuration: 750,
            easing: "linear",
            queue: false,
          },
        });
      });

      // change is-checked class on buttons
      $(".match-filter-widget").each(function (i, buttonGroup) {
        var $buttonGroup = $(buttonGroup);
        $buttonGroup.on("click", "button", function () {
          $buttonGroup.find(".active").removeClass("active");
          $(this).addClass("active");
        });
      });
    });
  }

  /*--------------- Slick Slider js--------*/
  if ($(".testimonial-one-slider").length) {
    $(".testimonial-one-slider").slick({
      autoplay: true,
      slidesToShow: 1,
      slidesToScroll: 1,
      autoplaySpeed: 3000,
      speed: 1000,
      dots: false,
      arrows: true,
      infinite: true,
      prevArrow:
        '<button type="button" class="slick-prev"><i class="fa fa-angle-double-left "></i></button>',
      nextArrow:
        '<button type="button" class="slick-next"><i class="fa fa-angle-double-right"></i></button>',
    });
  }

  if ($(".testimonial_three_slider").length) {
    $(".testimonial_three_slider").slick({
      dots: true,
      infinite: true,
      slidesToShow: 1,
      slidesToScroll: 1,
      variableWidth: true,
      autoplay: true,
      responsive: [
        {
          breakpoint: 576,
          settings: {
            centerMode: true,
            centerPadding: "0",
          },
        },
      ],
    });
  }
  if ($(".client_story_slider").length) {
    $(".client_story_slider").slick({
      autoplay: true,
      autoplaySpeed: 3000,
      dots: true,
      infinite: true,
      slidesToShow: 1,
      slidesToScroll: 1,
      asNavFor: ".client_story_slider_two",
      appendDots: ".client_story_slider_dots",
      waitForAnimate: false,
      fade: true,

      responsive: [
        {
          breakpoint: 576,
          settings: {
            fade: false,
          },
        },
      ],
    });
  }

  if ($(".client_story_slider_two").length) {
    $(".client_story_slider_two").slick({
      autoplay: true,
      autoplaySpeed: 3000,
      dots: false,
      infinite: true,
      vertical: true,
      verticalSwiping: true,
      slidesToShow: 2,
      slidesToScroll: 1,
      asNavFor: ".client_story_slider",
      adaptiveHeight: true,
    });
  }

  /*--------------- Fancybox js--------*/

  /*--------------- Parallax js--------*/
  if ($("#banner_animation").length > 0) {
    $("#banner_animation").parallax({
      scalarX: 7.0,
      scalarY: 9.0,
    });
  }

  /*--------------- Disable account confirmation --------*/
  $("#myCheckbox").click(function () {
    $("#myButton").prop("disabled", !$("#myCheckbox").prop("checked"));
  });

  var disableTermCheck;
  $(".deactivateTermCheck").change(function () {
    disableTermCheck = $(".deactivateTermCheck:checked").length < 1;
    $("#deactivateButton").prop("disabled", disableTermCheck);
  });

  $(".toggle-password").click(function () {
    $(this).toggleClass("fa-eye fa-eye-slash");
    var input = $($(this).attr("data-toggleTarget"));
    if (input.attr("type") == "password") {
      input.attr("type", "text");
    } else {
      input.attr("type", "password");
    }
  });

  var tooltipTriggerList = [].slice.call(
    document.querySelectorAll('[data-bs-toggle="tooltip"]')
  );
  var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
    return new bootstrap.Tooltip(tooltipTriggerEl);
  });
  $(".community-activity .replies-section .replies-toggle").on(
    "click",
    function () {
      $(this).toggleClass("shown");
      $(this).siblings(".replies-list").toggleClass("show");
    }
  );

  const $stickies = $(".chatbox-widget, .chat-right-bar");
  const $wrapper = $(".dashboard-wrapper");

  // store initial offsets
  $stickies.each(function () {
    const $el = $(this);
    $el.data({
      offsetTop: $el.offset().top,
      offsetLeft: $el.offset().left,
      width: $el.outerWidth(),
    });
  });

  function handleSticky() {
    const winWidth = $(window).width();
    const scrollTop = $(window).scrollTop();
    const wrapperTop = $wrapper.offset().top;
    const wrapperBottom = wrapperTop + $wrapper.outerHeight();

    $stickies.each(function () {
      const $el = $(this);
      const elTop = $el.data("offsetTop");
      const left = $el.data("offsetLeft");
      const width = $el.data("width");
      const elHeight = $el.outerHeight();

      if (winWidth >= 1200) {
        if (scrollTop >= elTop && scrollTop + elHeight < wrapperBottom) {
          // stick to top
          $el.css({ position: "fixed", top: 0, left: left, width: width });
        } else if (scrollTop + elHeight >= wrapperBottom) {
          // align to bottom of wrapper
          $el.css({
            position: "absolute",
            top: wrapperBottom - elHeight - wrapperTop,
            left: left,
            width: width,
          });
        } else {
          $el.css({ position: "", top: "", left: "", width: "" });
        }
      } else {
        // reset for small screens
        $el.css({ position: "", top: "", left: "", width: "" });
      }
    });
  }

  if ($(".chatbox-widget").length) {
    $(window).on("scroll resize", handleSticky);
  }
  $(".chat-right-bar .minimize-chat").on("click", function () {
    const $bar = $(this).closest(".chat-right-bar");
    const $msgs = $bar.find(".all-messages");
    const $icon = $(this).find("i");

    // slide toggle the messages section
    $msgs.slideToggle(200);

    // swap the icon class
    if ($icon.hasClass("icon_minus-06")) {
      $icon.removeClass("icon_minus-06").addClass("icon_plus");
    } else {
      $icon.removeClass("icon_plus").addClass("icon_minus-06");
    }
  });

  $(".trigger-content-editable .edit-pen-btn").on("click", function (e) {
    e.preventDefault(); // prevent default link behavior
    console.log("Edit button clicked");

    const $container = $(this).closest(".trigger-content-editable");

    // Make everything editable
    $container.attr("contenteditable", "true");

    // Make sure the edit-pen itself is NOT editable
    $container.find(".edit-pen-btn").attr("contenteditable", "false");

    // Optional: focus the container so user can start typing
    $container.focus();
  });

  $("[data-trigger-signup]").on("click", function (e) {
    e.preventDefault();

    const action = $(this).data("trigger-signup"); // 'signup' or 'login'
    const $modal = $(".signup-modal");

    if (action === "signup") {
      // show signup, hide login
      $modal.find(".signup-modal-content").show();
      $modal.find(".login-modal-content").hide();
    } else if (action === "login") {
      // show login, hide signup
      $modal.find(".login-modal-content").show();
      $modal.find(".signup-modal-content").hide();
    }
  });

  $(".filter-link-group").on("click", ".filter-link", function (e) {
    e.preventDefault();
    $(".filter-link-group .filter-link").removeClass("active");
    $(this).addClass("active");
  });

  // Ensure custom-modal dismisses on backdrop click
  $(document).on("click", ".modal.custom-modal", function (e) {
    if ($(e.target).hasClass("custom-modal")) {
      $(this).modal("hide");
    }
  });
})(jQuery);
