$(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 },
    },
  });

  // Top pick Slider
  // experince slider
  initSwiper(".toppick_slider", {
    slidesPerView: 2.4,
    spaceBetween: 40,
    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 },
      767: { slidesPerView: 1.2 },
      991: { slidesPerView: 1.5 },
    },
  });

  // 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 },
    },
  });

  // experience hero slider
  initSwiper(".hero_banner", {
    slidesPerView: 1,
    spaceBetween: 0,
    loop: false,
    navigation: {
      nextEl: ".custom_slider_controls .hero_slide_next",
      prevEl: ".custom_slider_controls .hero_slide_prev",
    },
  });

  // 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 (e) {
    e.preventDefault();
    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);
    }
  }
  // scroll to section according to query param.
  scrollToSectionIfParams(["interests", "states"], "#explore_section");
  scrollToSectionIfParams(["category", "state","search"], "#explore_by_interest");
  scrollToSectionIfParams(["category", "campaign","search"], "#campaign_section");
  scrollToSectionIfParams(["cat","s"], "#deals_section");

  // custom multi-selectbox.
  // Get all select boxes safely
  const multiSelects = document.querySelectorAll(".custom_multi_select");
  if (multiSelects.length) {
    multiSelects.forEach(initMultiSelect);
  }

  function initMultiSelect(wrapper) {
    if (!wrapper) return;

    const selectBox = wrapper.querySelector(".custom_selectbox");
    const dropdown = wrapper.querySelector(".custom_selectbox_dropdown");
    const tagsContainer = wrapper.querySelector(".custom_select_tag");
    const labelEl = wrapper.querySelector(".custom_select_label");
    const arrow = wrapper.querySelector(".custom_select_arrow");

    // If essential elements are missing → skip initialization safely
    if (!selectBox || !dropdown || !tagsContainer || !labelEl || !arrow) {
      console.warn("Missing required elements in:", wrapper);
      return;
    }

    const checkboxes = dropdown.querySelectorAll("input[type='checkbox']");
    const mainLabel = wrapper.dataset.label || "Items";

    /* ---------------------------
        Safe Slide Down Function
    ---------------------------- */
    function slideDown(el) {
      if (!el) return;

      el.style.display = "block";
      el.style.overflow = "hidden";
      el.style.height = "0px";

      const fullHeight = el.scrollHeight + "px";

      requestAnimationFrame(() => {
        el.style.transition = "height 0.25s ease";
        el.style.height = fullHeight;
      });

      el.addEventListener("transitionend", function end() {
        el.style.height = "auto";
        el.style.overflow = "visible";
        el.style.transition = "";
        el.removeEventListener("transitionend", end);
      });
    }

    /* ---------------------------
        Safe Slide Up Function
    ---------------------------- */
    function slideUp(el) {
      if (!el) return;

      el.style.overflow = "hidden";
      el.style.height = el.scrollHeight + "px";

      requestAnimationFrame(() => {
        el.style.transition = "height 0.25s ease";
        el.style.height = "0px";
      });

      el.addEventListener("transitionend", function end() {
        el.style.display = "none";
        el.style.transition = "";
        el.removeEventListener("transitionend", end);
      });
    }

    /* ---------------------------
        Toggle Dropdown
    ---------------------------- */
    function toggleDropdown() {
      if (!dropdown) return;

      // close all others
      document.querySelectorAll(".custom_selectbox_dropdown").forEach((d) => {
        if (d !== dropdown && d.style.display === "block") {
          slideUp(d);
          const otherArrow = d.closest(".custom_multi_select")
                            ?.querySelector(".custom_select_arrow");
          if (otherArrow) otherArrow.classList.remove("open");
        }
      });

      const isOpen = dropdown.style.display === "block";

      if (isOpen) {
        slideUp(dropdown);
        arrow.classList.remove("open");
      } else {
        slideDown(dropdown);
        arrow.classList.add("open");
      }
    }


    /* ---------------------------
        Select Box Click
    ---------------------------- */
    selectBox.addEventListener("click", (e) => {
      e.stopPropagation();
      toggleDropdown();
    });

    document.addEventListener("click", () => {
      if (dropdown.style.display === "block") {
        slideUp(dropdown);
        arrow.classList.remove("open");
      }
    });

    dropdown.addEventListener("click", (e) => e.stopPropagation());

    /* ---------------------------
        Checkbox Logic
    ---------------------------- */
    if (checkboxes.length) {
      checkboxes.forEach((cb) => cb.addEventListener("change", updateTags));
    }

    function updateTags() {
      if (!tagsContainer || !labelEl) return;

      const selected = [...checkboxes]
        .filter((cb) => cb.checked)
        .map((cb) => ({
          value: cb.value,
          label: cb.parentElement?.textContent.trim() || "",
        }));

      tagsContainer.innerHTML = "";

      // No items selected → show main label
      if (!selected.length) {
        labelEl.style.display = "block";
        tagsContainer.style.display = "none";
        return;
      }

      labelEl.style.display = "none";
      tagsContainer.style.display = "flex";

      if (selected.length <= 2) {
        selected.forEach((item) => addTag(item.value, item.label));
      } else {
        addTag(selected[0].value, selected[0].label);
        addTag("more", `+${selected.length - 1} ${mainLabel}`, false);
      }
    }

    /* ---------------------------
        Add Tag
    ---------------------------- */
    function addTag(value, label, removable = true) {
      if (!tagsContainer) return;

      const tag = document.createElement("div");
      tag.classList.add("custom_new_tag");
      tag.dataset.value = value;

      tag.innerHTML = `
        <span>${label}</span>
        ${
          removable
            ? `<span class="remove"><i class="fa-solid fa-xmark"></i></span>`
            : ""
        }
      `;

      if (removable) {
        tag.querySelector(".remove")?.addEventListener("click", (e) => {
          e.stopPropagation();

          const cb = [...checkboxes].find((c) => c.value === value);
          if (cb) cb.checked = false;

          updateTags();
        });
      }

      tagsContainer.appendChild(tag);
    }
    function restoreFromURL() {
      const paramKey = wrapper.dataset.param; // example: states / category
      if (!paramKey) return;

      const url = new URL(window.location.href);
      const paramValue = url.searchParams.get(paramKey);

      if (!paramValue) return;

      const selectedValues = paramValue.split(",");

      checkboxes.forEach((cb) => {
        cb.checked = selectedValues.includes(cb.value);
      });

      updateTags();
    }

    restoreFromURL();

  }
  


  // favorite functionality
  const FAVORITE_KEY = "favorite_articles";

  function getFavorites() {
    return JSON.parse(localStorage.getItem(FAVORITE_KEY)) || [];
  }

  function saveFavorites(favs) {
    localStorage.setItem(FAVORITE_KEY, JSON.stringify(favs));
  }

  function addFavorite(id) {
    let favs = getFavorites();
    if (!favs.includes(id)) {
      favs.push(id);
      saveFavorites(favs);
    }
  }

  function removeFavorite(id) {
    let favs = getFavorites().filter((f) => f !== id);
    saveFavorites(favs);
  }

  function toggleFavorite(id) {
    let favs = getFavorites();
    if (favs.includes(id)) {
      removeFavorite(id);
      return false;
    } else {
      addFavorite(id);
      return true;
    }
  }

  const fav = getFavorites();
  const has_fav = document.querySelector(".has-fav-item");
  const no_fav = document.querySelector(".no-fav-item");
  if (fav.length > 0) {
    if (has_fav) {
      has_fav.classList.add("d-block");
      has_fav.classList.remove("d-none");
    }
  } else {
    if (no_fav) {
      no_fav.classList.add("d-block");
      no_fav.classList.remove("d-none");
    }
  }
  document.addEventListener("click", function (e) {
    if (
      e.target.classList.contains("favorite-btn") ||
      e.target.closest(".favorite-btn")
    ) {
      e.preventDefault();
      const btn = e.target.closest(".favorite-btn");
      const id = btn.getAttribute("data-id");

      // Check if this button is inside favorite page
      const isFavPageItem = !!btn.closest(".favorite-card");

      // find child elements (safe fallback if not present)
      const btnTextEl = btn.querySelector(".btn-text");
      const spinnerEl = btn.querySelector(".fa-spinner");

      // Show loader on clicked button
      if (spinnerEl) spinnerEl.classList.remove("d-none");
      btn.classList.add("loading");

      setTimeout(() => {
        const added = toggleFavorite(id);

        // NORMAL PAGE: update text & active class on ALL buttons with same id,
        // but skip updating text for buttons that live inside .favorite-card
        document
          .querySelectorAll(`.favorite-btn[data-id="${id}"]`)
          .forEach((button) => {
            const insideFavCard = !!button.closest(".favorite-card");
            const textEl = button.querySelector(".btn-text");
            const sp = button.querySelector(".fa-spinner");

            // Only change text/active on non-favorite-page buttons
            if (!insideFavCard) {
              // toggle active class
              button.classList.toggle("active", added);

              // update the text span if present, otherwise fallback to textContent
              if (textEl) {
                textEl.textContent = added ? "Saved" : "SAVE AS A FAVOURITE";
              } else {
                // fallback: don't clobber spinner if present; only change textContent when no spinner exists
                if (!sp) {
                  button.textContent = added ? "Saved" : "SAVE AS A FAVOURITE";
                }
              }
            }
          });

        // Remove loader on clicked button (and ensure spinner hidden on clicked)
        if (spinnerEl) spinnerEl.classList.add("d-none");
        btn.classList.remove("loading");

        // FAVORITE PAGE: if this was on favorite-page and item was removed (unfavorited),
        // fade out and remove the card. Do not alter text on favorite page buttons.
        if (isFavPageItem && !added) {
          const innerCard = document.querySelector(
            `.favorite-card [data-id="${id}"]`
          );
          if (innerCard) {
            const cardContainer = innerCard.closest(".favorite-card");
            if (cardContainer) {
              cardContainer.classList.add("fade-out");
              setTimeout(() => {
                cardContainer.remove();

                // update empty-state UI (assuming has_fav & no_fav are defined globals)
                if (
                  typeof getFavorites === "function" &&
                  getFavorites().length === 0
                ) {
                  if (typeof has_fav !== "undefined") {
                    has_fav.classList.add("d-none");
                    has_fav.classList.remove("d-block");
                  }
                  if (typeof no_fav !== "undefined") {
                    no_fav.classList.add("d-block");
                    no_fav.classList.remove("d-none");
                  }
                }
              }, 400);
            }
          }
        }
      }, 500);
    }
  });

  //  document.addEventListener("DOMContentLoaded", () => {
  document.querySelectorAll(".favorite-btn").forEach((btn) => {
    const id = btn.getAttribute("data-id");

    // Check if this ID is already in favorites
    const isFavorite = getFavorites().includes(id);

    // Check if parent DOES NOT have .favorite-card
    const insideFavoriteCard = btn.closest(".favorite-card");

    if (isFavorite && !insideFavoriteCard) {
      btn.classList.add("active");
      btn.textContent = "Saved";
    }
  });

  // Filtering form submission
  document.addEventListener("submit", function (e) {
    const form = e.target.closest(".filter-form");
    if (!form) return;

    e.preventDefault(); // stop normal submit

    const params = new URLSearchParams();

    // Get all form fields
    const fields = form.querySelectorAll("[name]");

    // Temp storage for arrays
    const grouped = {};

    fields.forEach((field) => {
      const name = field.name.replace("[]", "");

      // Multi-checkbox
      if (field.type === "checkbox") {
        if (!grouped[name]) grouped[name] = [];
        if (field.checked) {
          grouped[name].push(field.value);
        }
      }

      // Text input / select
      else if (field.type === "text" || field.tagName === "SELECT") {
        if (field.value.trim() !== "") {
          params.set(name, field.value.trim());
        }
      }
    });

    // Add checkbox arrays to URL
    Object.keys(grouped).forEach((key) => {
      if (grouped[key].length > 0) {
        params.set(key, grouped[key].join(","));
      }
    });

    // FINAL URL
    const finalUrl = window.location.pathname + "?" + decodeURIComponent(params.toString()); // with , url
    // const finalUrl = window.location.pathname + "?" + params.toString(); // without , %2C url

    window.location.href = finalUrl;
  });
});

// nann

function showMoreImages(element) {
  var hiddenImages = document.querySelectorAll(".hidden-row");
  hiddenImages.forEach(function (imgCol) {
    imgCol.classList.remove("d-none");
    imgCol.classList.add("fade-in");
  });
  var overlay = element.querySelector(".more-overlay");
  if (overlay) {
    overlay.style.display = "none";
  }
  element.removeAttribute("onclick");
  element.style.cursor = "default";
}
