"use strict";
(function ($) {
  // ==========================================
  //      Start Document Ready function
  // ==========================================
  $(document).ready(function () {
    //============================ Scroll To Top Icon Js Start =========
    (function () {
      $(window).on("scroll", function () {
        if ($(window).scrollTop() >= 200) {
          $(".header").addClass("fixed-header");
        } else {
          $(".header").removeClass("fixed-header");
        }
      });
    })();

    //============================ Scroll To Top Icon Js Start =========
    var btn = $(".scroll-top");

    $(window).scroll(function () {
      if ($(window).scrollTop() > 100) {
        btn.addClass("show");
      } else {
        btn.removeClass("show");
      }
    });

    btn.on("click", function (e) {
      e.preventDefault();
      $("html, body").animate({ scrollTop: 0 }, "300");
    });
    //========================= Scroll To Top Icon Js End ======================

    // show hide js start here ================
    $(".command-item__title").on("click", function () {
      const item = $(this).closest(".command-item");
      const isActive = item.hasClass("active");

      $(".command-item").removeClass("active"); // Hide all

      if (!isActive) {
        item.addClass("active"); // Show clicked one if it wasn't already active
      }
    });
    // show hide js end here ================

    // ========================== Small Device Header Menu On Click Dropdown menu collapse Stop Js Start =====================
    $(".dropdown-item").on("click", function () {
      $(this).closest(".dropdown-menu").addClass("d-block");
    });
    // ========================== Small Device Header Menu On Click Dropdown menu collapse Stop Js End =====================

    // ========================== Add Attribute For Bg Image Js Start =====================
    $(".bg-img").css("background-image", function () {
      return `url(${$(this).data("background-image")})`;
    });
    // ========================== Add Attribute For Bg Image Js End =====================

    /*==================== custom dropdown select js ====================*/
    $(".custom--dropdown > .custom--dropdown__selected").on(
      "click",
      function () {
        $(this).parent().toggleClass("open");
      }
    );
    $(".custom--dropdown > .dropdown-list > .dropdown-list__item").on(
      "click",
      function () {
        $(
          ".custom--dropdown > .dropdown-list > .dropdown-list__item"
        ).removeClass("selected");
        $(this)
          .addClass("selected")
          .parent()
          .parent()
          .removeClass("open")
          .children(".custom--dropdown__selected")
          .html($(this).html());
      }
    );
    $(document).on("keyup", function (evt) {
      if ((evt.keyCode || evt.which) === 27) {
        $(".custom--dropdown").removeClass("open");
      }
    });
    $(document).on("click", function (evt) {
      if (
        $(evt.target).closest(".custom--dropdown > .custom--dropdown__selected")
          .length === 0
      ) {
        $(".custom--dropdown").removeClass("open");
      }
    });

    /*=============== custom dropdown select js end =================*/

    // ========================== add active class to ul>li top Active current page Js Start =====================
    function dynamicActiveMenuClass(selector) {
      if (!$(selector).length) return;

      let fileName = window.location.pathname.split("/").reverse()[0];
      selector.find("li").each(function () {
        let anchor = $(this).find("a");
        if ($(anchor).attr("href") == fileName) {
          $(this).addClass("active");
        }
      });
      // if any li has active element add class
      selector.children("li").each(function () {
        if ($(this).find(".active").length) {
          $(this).addClass("active");
        }
      });
      // if no file name return
      if ("" == fileName) {
        selector.find("li").eq(0).addClass("active");
      }
    }
    dynamicActiveMenuClass($("ul.sidebar-menu-list"));

    // ========================== add active class to ul>li top Active current page Js End =====================

    // ================== Password Show Hide Js Start ==========
    $(".toggle-password").on("click", function () {
      $(this).toggleClass("fa-eye");
      var input = $($(this).attr("id"));
      if (input.attr("type") == "password") {
        input.attr("type", "text");
      } else {
        input.attr("type", "password");
      }
    });
    // =============== Password Show Hide Js End =================

    // ================== Sidebar Menu Js Start ===============
    // Sidebar Dropdown Menu Start
    $(".has-dropdown > a").on("click", function () {
      $(".sidebar-submenu").slideUp(200);
      if ($(this).parent().hasClass("active")) {
        $(".has-dropdown").removeClass("active");
        $(this).parent().removeClass("active");
      } else {
        $(".has-dropdown").removeClass("active");
        $(this).next(".sidebar-submenu").slideDown(200);
        $(this).parent().addClass("active");
      }
    });
    // Sidebar Dropdown Menu End
    // Sidebar Icon & Overlay js
    $(".dashboard-body__bar-icon").on("click", function () {
      $(".sidebar-menu").addClass("show-sidebar");
      $(".sidebar-overlay").addClass("show");
    });
    $(".sidebar-menu__close, .sidebar-overlay").on("click", function () {
      $(".sidebar-menu").removeClass("show-sidebar");
      $(".sidebar-overlay").removeClass("show");
    });
    // Sidebar Icon & Overlay js
    // ===================== Sidebar Menu Js End =================

    // wow js
    new WOW().init();
    // wow js end

    // post sidebar show hide js
    $(".ai-btn").on("click", function () {
      $(".left-bar").addClass("show");
      $(".sidebar-overlay").addClass("show");
    });
    $(".close-icon, .sidebar-overlay").on("click", function () {
      $(".left-bar").removeClass("show");
      $(".sidebar-overlay").removeClass("show");
    });
    /*===================== action btn js start here =====================*/
    $(".action-btn__icon").on("click", function (event) {
      event.stopPropagation(); // Prevent click from bubbling to document
      $(".action-dropdown")
        .not($(this).parent().find(".action-dropdown"))
        .removeClass("show");
      $(this).parent().find(".action-dropdown").toggleClass("show");
    });
    $(document).on("click", function () {
      $(".action-dropdown").removeClass("show");
    });
    /*===================== action btn js end here =====================*/

    // ==================== Search Form Typing Effect JS Start ======================
    $(".search-form").each((index, el) => {
      let input = $(el).find(".search-form__input");

      if (input.length > 0) {
        let index = 0;
        const placeholderText = input.attr("placeholder");
        function typePlaceholder() {
          if (index < placeholderText.length) {
            input.attr("placeholder", placeholderText.substring(0, index + 1));
            index++;
            setTimeout(typePlaceholder, 100);
          } else {
            setTimeout(() => {
              input.attr("placeholder", "");
              index = 0;
              typePlaceholder();
            }, 2000);
          }
        }
        typePlaceholder();
      }
    });
    // ==================== Search Form Typing Effect JS End ========================

    // ==================== Dashboard User Profile Dropdown Start ==================
    $(".user-info__button").on("click", function () {
      $(".user-info-dropdown").toggleClass("show");
    });
    $(".user-info__button").attr("tabindex", -1).focus();

    $(".user-info__button").on("focusout", function () {
      $(".user-info-dropdown").removeClass("show");
    });
    // ==================== Dashboard User Profile Dropdown End ==================

    //Plugin Customization Start
    // ========================= Select2 Js Start ==============
    (function () {
      $(".select2").each((index, select) => {
        $(select)
          .wrap('<div class="select2-wrapper"></div>')
          .select2({
            dropdownParent: $(select).closest(".select2-wrapper"),
          });
      });
    })();
    // ========================= Select2 Js End ==============

    /*================ datepicker js start here ================*/
    if ($(".datepicker2").length > 0) {
      $(".datepicker2").flatpickr({
        // mode: "range",
        dateFormat: "Y-m-d",
      });
    }
    /*================ datepicker js start here ================*/

    // ========================= Slick Slider Js Start ==============

    if ($(".feature-wrapper").length > 0) {
      $(".feature-wrapper").slick({
        slidesToShow: 4,
        slidesToScroll: 1,
        autoplay: true,
        autoplaySpeed: 2000,
        speed: 1500,
        dots: true,
        pauseOnHover: true,
        arrows: false,
        prevArrow:
          '<button type="button" class="slick-prev"><i class="fas fa-long-arrow-alt-left"></i></button>',
        nextArrow:
          '<button type="button" class="slick-next"><i class="fas fa-long-arrow-alt-right"></i></button>',
        responsive: [
          {
            breakpoint: 1399,
            settings: {
              arrows: false,
              slidesToShow: 3,
              dots: true,
            },
          },
          {
            breakpoint: 991,
            settings: {
              arrows: false,
              slidesToShow: 2,
            },
          },
          {
            breakpoint: 574,
            settings: {
              arrows: false,
              slidesToShow: 1,
            },
          },
        ],
      });
    }
    // ========================= Slick Slider Js End ===================

    if ($(".testimonial-card").length > 0) {
      $(".testimonial-card").slick({
        slidesToShow: 1,
        slidesToScroll: 1,
        arrows: false,
        dots: true,
        asNavFor: ".testimonial-thumb-wrapper",
        prevArrow:
          '<button type="button" class="slick-prev gig-details-thumb-arrow"><i class="las la-long-arrow-alt-left"></i></button>',
        nextArrow:
          '<button type="button" class="slick-next gig-details-thumb-arrow"><i class="las la-long-arrow-alt-right"></i></button>',
      });
    }

    if ($(".testimonial-thumb-wrapper").length > 0) {
      $(".testimonial-thumb-wrapper").slick({
        slidesToShow: 4,
        slidesToScroll: 1,
        asNavFor: ".testimonial-card",
        arrows: false,
        centerMode: true,
        centerPadding: "0px",
        focusOnSelect: true,
        prevArrow:
          '<button type="button" class="slick-prev gig-details-arrow"><i class="las la-long-arrow-alt-left"></i></button>',
        nextArrow:
          '<button type="button" class="slick-next gig-details-arrow"><i class="las la-long-arrow-alt-right"></i></button>',
        responsive: [
          {
            breakpoint: 1200,
            settings: {
              slidesToShow: 3,
              slidesToScroll: 1,
            },
          },
          {
            breakpoint: 991,
            settings: {
              slidesToShow: 2,
              slidesToScroll: 1,
            },
          },
          {
            breakpoint: 768,
            settings: {
              slidesToShow: 2,
              slidesToScroll: 1,
            },
          },
          {
            breakpoint: 574,
            settings: {
              slidesToShow: 2,
              centerMode: false,
              centerPadding: false,
              slidesToScroll: 1,
            },
          },
        ],
      });
    }
    // ========================= Odometer Counter Up Js End ==========
    if ($(".counterup-item").length > 0) {
      $(".counterup-item").each(function () {
        $(this).isInViewport(function (status) {
          if (status === "entered") {
            for (
              var i = 0;
              i < document.querySelectorAll(".odometer").length;
              i++
            ) {
              var el = document.querySelectorAll(".odometer")[i];
              el.innerHTML = el.getAttribute("data-odometer-final");
            }
          }
        });
      });
    }
    // collapse
    if ($(".testimonial-slide").length > 0) {
      $(".testimonial-slide").slick({
        dots: true,
        infinite: false,
        speed: 300,
        slidesToShow: 3,
        slidesToScroll: 1,
        appendArrows: false,
        responsive: [
          {
            breakpoint: 1200,
            settings: {
              slidesToShow: 3,
            },
          },
          {
            breakpoint: 1199,
            settings: {
              slidesToShow: 2,
            },
          },
          {
            breakpoint: 991,
            settings: {
              slidesToShow: 1,
            },
          },
          {
            breakpoint: 480,
            settings: {
              slidesToShow: 1,
            },
          },
        ],
      });
    }

    /*============== clients slider js start here ==============*/
    $(".brand-slider").slick({
      slidesToShow: 7,
      slidesToScroll: 1,
      speed: 2000,
      cssEase: "linear",
      autoplay: true,
      autoplaySpeed: 0,
      adaptiveHeight: false,
      pauseOnDotsHover: false,
      pauseOnHover: true,
      pauseOnFocus: true,
      dots: false,
      arrows: false,
      responsive: [
        {
          breakpoint: 1199,
          settings: {
            slidesToShow: 6,
            arrows: false,
          },
        },
        {
          breakpoint: 767,
          settings: {
            slidesToShow: 5,
            arrows: false,
          },
        },
        {
          breakpoint: 575,
          settings: {
            slidesToShow: 3,
            arrows: false,
          },
        },
      ],
    });
    /*============ clients slider js end here ==============*/

    Fancybox.bind("[data-fancybox]", {
      // Your custom options
    });

    // ========================= Odometer Up Counter Js End =====================
  });

  // ==========================================
  //      End Document Ready function
  // ==========================================

  gsap.registerPlugin(ScrollTrigger);

  if (window.innerWidth > 768) {
    document.addEventListener("DOMContentLoaded", () => {
      const items = document.querySelectorAll(".how-work__item");

      items.forEach((item) => {
        const computedStyle = window.getComputedStyle(item);
        const matrix = computedStyle.transform;

        let currentRotation = 0;
        if (matrix !== "none") {
          const values = matrix.split("(")[1].split(")")[0].split(",");
          const a = values[0];
          const b = values[1];
          const angle = Math.round(Math.atan2(b, a) * (180 / Math.PI));
          currentRotation = angle;
        }

        gsap.fromTo(
          item,
          { rotation: currentRotation, y: 30 },
          {
            rotation: 0,
            opacity: 1,
            y: 0,
            duration: 2,
            ease: "power3.out",
            scrollTrigger: {
              trigger: item,
              start: "top 85%",
              end: "bottom 20%",
              scrub: true,
              // markers: true,
            },
          }
        );
      });
    });
    document.addEventListener("DOMContentLoaded", () => {
      const missionItems = document.querySelectorAll(".mission-item");

      missionItems.forEach((item) => {
        const style = window.getComputedStyle(item);
        const matrix = new DOMMatrixReadOnly(style.transform);
        const currentRotation = Math.round(
          Math.atan2(matrix.b, matrix.a) * (180 / Math.PI)
        );
        const currentY = matrix.m42 || 0;

        gsap.fromTo(
          item,
          { rotation: currentRotation, y: currentY },
          {
            rotation: 0,
            y: 0,
            opacity: 1,
            ease: "power3.out",
            duration: 2,
            scrollTrigger: {
              trigger: item,
              start: "top 80%",
              end: "bottom 30%",
              scrub: true,
              // markers: true,
            },
          }
        );
      });
    });
  }

  // ========================= Preloader Js Start =====================
  $(window).on("load", function () {
    $(".preloader").fadeOut();
  });
  // ========================= Preloader Js End=====================

  $("[data-highlight-word]").each((index, el) => {
    var text = $(el).text().replace(/\s+/g, " ").trim();

    // Define the range (1-based index)
    var startWord =
      $(el).data("highlight-start") || $(el).data("highlight-word");
    var endWord = $(el).data("highlight-word");

    // Split the string into words
    var words = text.split(" ");

    // Build the result
    var result = "";

    for (var i = 0; i < words.length; i++) {
      if (i === startWord - 1) {
        result += `<span>`;
      }

      result += words[i];

      if (i === endWord - 1) {
        result += "</span>";
      }

      // Add space between words (except after last word)
      if (i < words.length - 1) {
        result += " ";
      }
    }

    // Set the result to an element
    $(el).html(result);
  });
})(jQuery);
