"use strict";
(function ($) {
  /* ==================== Ready Function Start ========================== */
  $(document).ready(function () {
    /* ==================== Dynamically Add BG Image JS Start ====================== */
    $(".bg-img").css("background-image", function () {
      return `url(${$(this).data("background-image")})`;
    });
    /* ==================== Dynamically Add BG Image JS End ========================= */

    /* ==================== Dynamically Add Mask Image JS Start ====================== */
    $(".mask-img").css("mask-image", function () {
      return `url(${$(this).data("mask-image")})`;
    });
    /* ==================== Dynamically Add Mask Image JS End ======================== */

    /* ==================== Add A Class In Select Input JS Start ===================== */
    $(".form-select.form--select").each((index, select) => {
      if ($(select).val()) {
        $(select).addClass("selected");
      }

      $(select).on("change", function () {
        if ($(this).val()) {
          $(this).addClass("selected");
        } else {
          $(this).removeClass("selected");
        }
      });
    });
    /* ==================== Add A Class In Select Input JS End ======================== */

    /* ==================== Select2 Initialization JS Start ==================== */
    $(".select2").each((index, select) => {
      $(select)
        .wrap('<div class="s2-wrap"></div>')
        .select2({
          dropdownParent: $(select).closest(".s2-wrap"),
        });
    });

    $(".select2-v2").each((index, select) => $(select).select2());

    $(".select2-v2").each(function () {
      let label = $(this).data("label");
      let required = $(this).attr("required");
      let selection = $(this)
        .data("select2")
        .$container.find(".select2-selection--single");

      if (!selection.length) {
        selection = $(this)
          .data("select2")
          .$container.find(".select2-selection--multiple");
      }

      selection.prepend(
        `<span class="select2-selection__label ${
          required ? "required" : ""
        }">${label}</span>`,
      );
    });
    /* ==================== Select2 Initialization JS End ==================== */

    /* ==================== Slick Slider Initialization JS Start ==================== */
    $(".testimonial").each((index, el) => {
      let slider = $(el).find(".testimonial-slider");
      let sliderCTRL = $(el).find(".testimonial-slider-ctrl");

      slider.slick({
        slidesToScroll: 1,
        slidesToShow: 5,
        speed: 1500,
        dots: false,
        pauseOnHover: true,
        dots: true,
        arrows: true,
        appendArrows: sliderCTRL,
        appendDots: sliderCTRL,
        prevArrow:
          '<button type="button" class="slick-prev"><i class="las la-arrow-left"></i></button>',
        nextArrow:
          '<button type="button" class="slick-next"><i class="las la-arrow-right"></i></button>',
        centerMode: (() => $(".testimonial-slider__slide").length > 5)(),
        responsive: [
          {
            breakpoint: 1600,
            settings: {
              slidesToShow: 4,
            },
          },
          {
            breakpoint: 1200,
            settings: {
              slidesToShow: 3,
            },
          },
          {
            breakpoint: 768,
            settings: {
              dots: false,
              slidesToShow: 2,
            },
          },
          {
            breakpoint: 576,
            settings: {
              dots: false,
              slidesToShow: 1,
            },
          },
        ],
      });
    });

    $(".banner-slider").slick({
      variableWidth: true,
      slidesToScroll: 1,
      autoplay: true,
      autoplaySpeed: 2000,
      speed: 1500,
      pauseOnHover: true,
      arrows: false,
    });

    const accountSliderConfig = {
      autoplay: true,
      autoplaySpeed: 0,
      speed: 15000,
      arrows: false,
      swipe: false,
      dots: false,
      slidesToScroll: 1,
      variableWidth: true,
      cssEase: "linear",
      pauseOnFocus: false,
      pauseOnHover: false,
      // responsive: [
      //     {
      //         breakpoint: 1399,
      //         settings: {
      //             slidesToShow: 4,
      //         }
      //     },
      //     {
      //         breakpoint: 992,
      //         settings: {
      //             slidesToShow: 3,
      //         }
      //     },
      //     {
      //         breakpoint: 576,
      //         settings: {
      //             slidesToShow: 2,
      //         }
      //     },
      // ]
    };

    $(".account-slider-one").slick(accountSliderConfig);

    $(".account-slider-two").slick({
      ...accountSliderConfig,
      rtl: true,
    });
    /* ==================== Slick Slider Initialization JS End ====================== */

    /* ==================== Password Toggle JS Start ================================ */
    $(".input--group-password").each(function (index, inputGroup) {
      let inputGroupBtn = $(inputGroup).find(".input-group-btn");
      let formControl = $(inputGroup).find(".form-control.form--control");

      inputGroupBtn.on("click", function () {
        if (formControl.attr("type") === "password") {
          formControl.attr("type", "text");
          $(this).find("i").removeClass("fa-eye-slash").addClass("fa-eye");
        } else {
          formControl.attr("type", "password");
          $(this).find("i").removeClass("fa-eye").addClass("fa-eye-slash");
        }
      });
    });
    /* ==================== Password Toggle JS End ================================== */

    /* ==================== Odometer Initialize JS Start ===================== */
    function InitOdometer() {
      function isInViewport(element) {
        var rect = element.getBoundingClientRect();
        return (
          rect.top >= 0 &&
          rect.left >= 0 &&
          rect.bottom <=
            (window.innerHeight || document.documentElement.clientHeight) &&
          rect.right <=
            (window.innerWidth || document.documentElement.clientWidth)
        );
      }

      const odometers = document.querySelectorAll(".odometer");

      odometers.forEach(function (el) {
        // initialize with 0
        el.innerHTML = 0;

        function runOdometer() {
          if (isInViewport(el) && !el.classList.contains("odometer-done")) {
            el.classList.add("odometer-done");
            el.innerHTML = el.dataset.odometerStop;
          }
        }

        // check on scroll + load
        window.addEventListener("scroll", runOdometer);
        window.addEventListener("load", runOdometer);
      });
    }

    InitOdometer();
    /* ==================== Odometer Initialize JS End ======================= */

    /* ==================== Input Group Copy JS Start =============================== */
    $(".input--group-copy").each((index, element) => {
      let copyBtn = $(element).find(".copy-btn");
      let copyInput = $(element).find(".copy-input");

      copyBtn.on("click", function () {
        // Select the text field
        copyInput.select();
        copyInput[0].setSelectionRange(0, 99999); // For mobile devices

        // Copy the text inside the text field
        if (navigator.clipboard.writeText(copyInput.val())) {
          $(this).addClass("copied");

          let timer = setTimeout(() => {
            $(this).removeClass("copied");
            clearTimeout(timer);
          }, 1000);
        }
      });
    });
    /* ==================== Input Group Copy JS End ================================= */

    /*  ==================== Custom Color Pickr JS Start ================================= */
    function initColorPick(colorPickr) {
      let input = colorPickr.find(".color-pickr__input");
      let el = colorPickr.find(".color-pickr__el");
      let defaultColor = input.val() || "#2196F3";

      // Prevent double initialization
      if (colorPickr.data("pickr")) return;

      let pickr = Pickr.create({
        el: el[0],
        theme: "nano",
        default: defaultColor.startsWith("#")
          ? defaultColor
          : `#${defaultColor}`,
        components: {
          preview: true,
          hue: true,
        },
      });

      colorPickr.data("pickr", pickr); // store instance

      pickr.on("change", (color) => {
        const selectedColor = color.toHEXA().toString();
        const buttonEl = pickr.getRoot().button;

        if (buttonEl) {
          buttonEl.style.setProperty("--pcr-color", selectedColor);
          input.val(selectedColor);
        }
      });

      input.on("input", function () {
        let selectedColor = $(this).val();
        const buttonEl = pickr.getRoot().button;
        // Update preview button
        if (buttonEl) {
          buttonEl.style.setProperty("--pcr-color", selectedColor);
        }
        // Update Pickr UI
        if (/^#?[0-9A-Fa-f]{3,6}$/.test(selectedColor)) {
          // Ensure '#' exists
          if (!selectedColor.startsWith("#")) {
            selectedColor = "#" + selectedColor;
          }
          pickr.setColor(selectedColor, true); // true = silent (no event trigger)
        }
      });
    }

    $(".color-pickr").each((index, el) => {
      initColorPick($(el));
    });

    $(".gen-form-field--color").on("click", function () {
      let colorWrapper = $(this).find(".color-pickr");
      let pickr = colorWrapper.data("pickr");

      if (!pickr) {
        initColorPick(colorWrapper);
        pickr = colorWrapper.data("pickr");
      }
      pickr.show();
    });
    /*  ==================== Custom Color Pickr JS End =================================== */

    /*  ==================== Custom Checkbox Click JS Start ================================= */
    $(".custom-check").each((index, el) => {
      let input = $(el).find(".custom-check__input");
      input.prop("checked", false);
      input.on("change", function () {
        let selector = $(el).data("target");
        $(selector).toggleClass("d-none");

        if (window.innerWidth < 768) {
          window.scrollTo({
            top: $(".gen-form")[0].offsetTop,
            behavior: "smooth",
          });
        }
      });
    });
    /*  ==================== Custom Checkbox Click JS End =================================== */

    /* ==================== BS Tooltip Initialize JS Start ===================== */
    const tooltipTriggerList = document.querySelectorAll(
      '[data-bs-toggle="tooltip"]',
    );
    const tooltipList = [...tooltipTriggerList].map(
      (tooltipTriggerEl) => new bootstrap.Tooltip(tooltipTriggerEl),
    );
    /* ==================== BS Tooltip Initialize JS End ======================= */

    /* ===================== Height Calculation JS Start =================== */
    const headerHeight = document.querySelector(".header")?.offsetHeight || 0;
    const dashboardHeaderHeight =
      document.querySelector(".dashboard-header")?.offsetHeight || 0;
    const couponWrapperHeight =
      document.querySelector(".coupon-wrapper")?.offsetHeight || 0;

    document.documentElement.style.setProperty(
      "--header-height",
      `${headerHeight}px`,
    );
    document.documentElement.style.setProperty(
      "--dashboard-header-height",
      `${dashboardHeaderHeight}px`,
    );
    document.documentElement.style.setProperty(
      "--coupon-wrapper-height",
      `${couponWrapperHeight}px`,
    );
    /* ===================== Height Calculation JS End ===================== */

    /* ===================== Prompt Form Smooth Scrolling JS Start =================== */
    $('a[href="#gen-form"]').on("click", function (e) {
      e.preventDefault();
      const target = $("#gen-form")[0];
      const elementPosition = target.getBoundingClientRect().top;
      const offsetPosition =
        elementPosition + window.pageYOffset - (headerHeight + 100);

      window.scrollTo({
        top: offsetPosition,
        behavior: "smooth",
      });
    });
    /* ===================== Prompt Form Smooth Scrolling JS End ===================== */
  });
  /* ==================== Ready Function End ============================ */

  /* ==================== Header Fixed JS Start ========================= */
  $(window).on("scroll", function () {
    if ($(window).scrollTop() >= 300) {
      $(".header").addClass("fixed-header");
    } else {
      $(".header").removeClass("fixed-header");
    }
  });
  /* ==================== Header Fixed JS End ============================= */

  /* ==================== Scroll To Top Button JS Start ==================== */
  let scrollTopBtn = $(".scroll-top");

  if (scrollTopBtn.length) {
    let progressPath = scrollTopBtn.find(".scroll-top-progress path");
    let pathLength = progressPath[0].getTotalLength();
    let offset = 250;
    let duration = 550;

    progressPath.css({
      transition: "none",
      WebkitTransition: "none",
      strokeDasharray: `${pathLength} ${pathLength}`,
      strokeDashoffset: pathLength,
      transition: "stroke-dashoffset 10ms linear",
      WebkitTransition: "stroke-dashoffset 10ms linear",
    });

    function updateProgress() {
      let scroll = $(window).scrollTop();
      let height = $(document).height() - $(window).height();
      let progress = pathLength - (scroll * pathLength) / height;
      progressPath.css("strokeDashoffset", progress);
    }

    updateProgress();

    $(window).on("scroll", function () {
      updateProgress();
      if ($(this).scrollTop() > offset) {
        scrollTopBtn.addClass("active");
      } else {
        scrollTopBtn.removeClass("active");
      }
    });

    scrollTopBtn.on("click", function (e) {
      e.preventDefault();
      $("html, body").animate({ scrollTop: 0 }, duration);
      return false;
    });
  }

  // Disabled scroll top for account pages
  if ($(scrollTopBtn).next(":is(.page-wrapper)").find(".account").length) {
    $(scrollTopBtn).hide();
  }
  /* ==================== Scroll To Top Button JS End ==================== */

  /* ==================== Preloader JS Start ============================== */
  $(window).on("load", () => {
    $(".preloader").fadeOut();
    AOS.init({
      offset: 0,
      once: true,
      disable() {
        var maxWidth = 1200; // breakpoint for mobile
        return window.innerWidth < maxWidth;
      },
    });
  });
  /* ==================== Preloader JS End ================================ */
})(jQuery);
