$(function () {
  $(".nav-toggle").on("click", function () {
    $(".offcanvas-menu").addClass("active");
  });

  $(".close-btn").on("click", function () {
    $(".offcanvas-menu").removeClass("active");
  });

  // helper to init slider
  function initSwiper(selector, config) {
    const elements = document.querySelectorAll(selector);
    if (!elements.length) return; // No slider found

    elements.forEach((el) => {
      // Prevent double init
      if (el.swiper) return;

      new Swiper(el, config);
    });
  }

  // hero banner
  if ($(".heroSwiper").length) {
    const swiper = new Swiper(".heroSwiper", {
      loop: true,
      autoplay: false,
      navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev",
      },
      on: {
        slideChange: function () {
          const index = this.realIndex;
          $(".custom-nav .nav-item").removeClass("active");
          $(".custom-nav .nav-item").eq(index).addClass("active");
          moveActiveBar();
          scrollActiveIntoView();
        },
      },
    });

    $(".custom-nav .nav-item").on("click", function () {
      var slideIndex = $(this).data("slide");
      swiper.slideToLoop(slideIndex);
    });
  }

  // Move the yellow triangle above active item
  function moveActiveBar() {
    const $active = $(".custom-nav .nav-item.active");
    const $bar = $(".custom-nav .active-bar");
    if( $active.length && $bar.length){
      $bar.css({
        left: $active.position().left + 30,
      });
    }
  }

  function scrollActiveIntoView() {
    const $nav = $(".custom-nav-wrapper");
    const $active = $(".custom-nav .nav-item.active");
    if (!$active.length) return;

    const navRect = $nav[0].getBoundingClientRect();
    const activeRect = $active[0].getBoundingClientRect();

    if (activeRect.left < navRect.left) {
      $nav.animate(
        {
          scrollLeft: $nav.scrollLeft() - (navRect.left - activeRect.left + 20),
        },
        300
      );
    } else if (activeRect.right > navRect.right) {
      $nav.animate(
        {
          scrollLeft:
            $nav.scrollLeft() + (activeRect.right - navRect.right + 20),
        },
        300
      );
    }
  }

  moveActiveBar();
  $(window).on("resize", moveActiveBar);

  // experince slider
  initSwiper(".experience_slider", {
    slidesPerView: 2.4,
    spaceBetween: 0,
    loop: false,
    pagination: {
      el: ".experience_slider_controls .item_count",
      type: "fraction",
      formatFractionCurrent: (n) => ("0" + n).slice(-2),
      formatFractionTotal: (n) => ("0" + n).slice(-2),
    },
    navigation: {
      nextEl: ".experience_slider_controls .experience_slide_next",
      prevEl: ".experience_slider_controls .experience_slide_prev",
    },
    breakpoints: {
      0: { slidesPerView: 1.2 },
      767: { slidesPerView: 1.2 },
      991: { slidesPerView: 2.4 },
      1440: { slidesPerView: 3.2 },
      2400: { slidesPerView: 4.4 },
    },
  });

  // popular deals slider
  initSwiper(".Popular_deals_slider", {
    slidesPerView: 3,
    spaceBetween: 35,
    loop: false,
    navigation: {
      nextEl: ".custom_slider_controls .deal_slide_next",
      prevEl: ".custom_slider_controls .deal_slide_prev",
    },
    breakpoints: {
      0: { slidesPerView: 1 },
      767: { slidesPerView: 2 },
      991: { slidesPerView: 3 },
    },
  });

  // images slider
  initSwiper(".images_slider", {
    slidesPerView: 3,
    spaceBetween: 20,
    loop: false,
    navigation: {
      nextEl: ".custom_slider_controls .images_slide_next",
      prevEl: ".custom_slider_controls .images_slide_prev",
    },
    breakpoints: {
      0: { slidesPerView: 1, spaceBetween: 5 },
      767: { slidesPerView: 2, spaceBetween: 10 },
      991: { slidesPerView: 3 },
    },
  });

  // map slider
  initSwiper(".map_slider",{
    slidesPerView: 3,
    spaceBetween: 20,
    loop: false,
    // autoplay:true,
    allowTouchMove: false,
    navigation: {
      nextEl: ".custom_slider_controls .map_slide_next",
      prevEl: ".custom_slider_controls .map_slide_prev",
    },
    breakpoints: {
      0: { slidesPerView: 1, spaceBetween: 5 },
      767: { slidesPerView: 2, spaceBetween: 10 },
      991: { slidesPerView: 3 , spaceBetween: 20 },
    },
  });

  // dynamically generate html in single modal images_slider.
  $(document).on("click", ".open-modal", function () {
    const href = $(this).data("href");
    const src = $(this).data("src");

    $("#imageModal .redirection_link").attr("href", href);
    $("#imageModal .modal-img").attr("src", src);

    $("#imageModal").modal("show");
  });

  // first type of category

  document.querySelectorAll(".category-wrapper").forEach((wrapper) => {
    const position = wrapper.dataset.position || "below";

    const itemElements = wrapper.querySelectorAll(".items .category");

    const mainRow = wrapper.querySelector(".main-row");
    const toggleMore = wrapper.querySelector(".toggle-more");
    const hiddenBox = wrapper.querySelector(".hidden-box");

    // Position hidden box
    hiddenBox.style[position] = "100%";

    if (itemElements.length === 0) return;

    // Insert first badge directly inside main-row BEFORE the toggleMore badge
    const firstClone = itemElements[0].cloneNode(true);

    mainRow.insertBefore(firstClone, toggleMore);

    // If only 1 category → done
    if (itemElements.length === 1) return;

    // Clone remaining badges into hidden-box
    for (let i = 1; i < itemElements.length; i++) {
      hiddenBox.appendChild(itemElements[i].cloneNode(true));
    }

    const count = itemElements.length - 1;

    toggleMore.style.display = "inline-block";
    toggleMore.textContent = `+${count}`;

    let open = false;

    toggleMore.addEventListener("click", () => {
      open = !open;

      hiddenBox.style.display = open ? "flex" : "none";
      toggleMore.textContent = open ? "-" : `+${count}`;
    });
  });

  // second type of tags.

  function initTagLimiter(selector, visibleCount = 2, itemSelector = ".tag") {
    document.querySelectorAll(selector).forEach(wrapper => {
      const items = wrapper.querySelectorAll(itemSelector);
      if (items.length <= visibleCount) return;

      const hiddenItems = Array.from(items).slice(visibleCount);
      hiddenItems.forEach(el => el.style.display = "none");

      const toggleBtn = document.createElement("span");
      const cleanClass = itemSelector.replace(/^[.#]/, "");
      toggleBtn.className = `tag-toggle text-CA2029 badge p-2 ${cleanClass}`;
      toggleBtn.textContent = `+${hiddenItems.length}`;
      wrapper.appendChild(toggleBtn);

      let expanded = false;

      toggleBtn.addEventListener("click", () => {
        expanded = !expanded;
        if (expanded) {
          hiddenItems.forEach(el => el.style.display = "inline-block");
          toggleBtn.textContent = "–";
        } else {
          hiddenItems.forEach(el => el.style.display = "none");
          toggleBtn.textContent = `+${hiddenItems.length}`;
        }
      });
    });
  }
  // init the limiter
  initTagLimiter(".detail_badges", 2, ".badge");

  // Toggle dropdown (open/close)
  $(document).on("click", ".custom_select_box_trigger", function (e) {
    e.stopPropagation();

    const dropdown = $(this).siblings(".custom-options");
    const arrow = $(this).find(".arrow");

    // Close all other open dropdowns
    $(".custom-options").not(dropdown).slideUp(200);
    $(".custom_select_box .arrow").not(arrow).css({
      transform: "rotate(0deg)",
      transition: "transform 0.3s",
    });

    // Stop current animation and toggle this dropdown
    dropdown.stop(true, true).slideToggle(200, function () {
      if (dropdown.is(":visible")) {
        arrow.css({
          transform: "rotate(-180deg)",
          transition: "transform 0.3s",
        });
      } else {
        arrow.css({
          transform: "rotate(0deg)",
          transition: "transform 0.3s",
        });
      }
    });
  });

  // Select an option
  $(document).on("click", ".custom-options li", function (e) {
    e.stopPropagation();

    const value = $(this).data("value");
    const parent = $(this).closest(".custom_select_box");
    const oldValue = parent.find(".selected-value").text();

    if (oldValue !== value) {
      parent.find(".selected-value").text(value);
      parent.trigger("customSelectChange", [value]);
    }

    // Close dropdown
    const dropdown = $(this).parent();
    dropdown.slideUp(200);
    parent.find(".arrow").css({
      transform: "rotate(0deg)",
      transition: "transform 0.3s",
    });
  });

  // Close all dropdowns if click outside
  $(document).on("click", function () {
    $(".custom-options").slideUp(200);
    $(".custom_select_box .arrow").css({
      transform: "rotate(0deg)",
      transition: "transform 0.3s",
    });
  });

  // Listen for value changes
  // When any selectbox value changes → Update URL & refresh
  $(".custom_select_box").on("customSelectChange", function (e, value) {

    const selectId = $(this).attr("id"); // interests / states

    // Get default value dynamically (first option <li>)
    const defaultValue = $(this)
      .find(".custom-options li")
      .first()
      .data("value");

    // Remove param only if selected value = default value
    const paramValue = value;

    const url = new URL(window.location.href);

    if (paramValue) {
      url.searchParams.set(selectId, paramValue);
    } else {
      url.searchParams.delete(selectId);
    }

    window.location.href = url.toString();
  });

  // Clear all query params
  $("#clearfilter").on("click", function () {
    const url = window.location.origin + window.location.pathname;
    window.location.href = url;
  });

  // scroll to explore section if we have interest or state params in the url

  function scrollToSectionIfParams(params = [], sectionId = "", delay = 500) {
    if (!params.length || !sectionId) return;

    const url = new URL(window.location.href);
    let shouldScroll = false;

    // Check if ANY of the params exist
    params.forEach((param) => {
      if (url.searchParams.has(param)) {
        shouldScroll = true;
      }
    });

    if (shouldScroll) {
      setTimeout(() => {
        const target = document.querySelector(sectionId);
        if (target) {
          target.scrollIntoView({
            behavior: "smooth",
            block: "start",
          });
        }
      }, delay);
    }
  }
  // home page.
  scrollToSectionIfParams(["interests", "states"], "#explore_section");
});
