/** @format */

var THEMETAGS = THEMETAGS || {};
jQuery(function ($) {
  "use strict";

  //preloader
  $(window).ready(function () {
    $("#preloader").delay(100).fadeOut("fade");
  });

  //dropdown menu hover js
  $("ul.nav li.dropdown").hover(function () {
    $(this).find(".dropdown-menu").stop(true, true).delay(100).fadeIn(200);
  }, function () {
    $(this).find(".dropdown-menu").stop(true, true).delay(100).fadeOut(200);
  });

  //sticky header
  $(window).on("scroll", function () {
    var scroll = $(window).scrollTop();
    if (scroll < 2) {
      $("nav.sticky-header").removeClass("affix");
    } else {
      $("nav.sticky-header").addClass("affix");
    }
  });
  $(function () {
    $('[data-bs-toggle="tooltip"]').tooltip();
  });

  // 13. swiper slider for all carousel
  var sliderSelector = '.custom-swiper';
  var defaultOptions = {
    // breakpointsInverse removed (not a Swiper option)
    observer: true,
    observeParents: true,
    observeSlideChildren: true
  };
  $(sliderSelector).each(function () {
    var slider = this;

    // Read and safely parse data-swiper JSON
    var dataOptions = {};
    var dataAttr = $(slider).attr('data-swiper');
    if (typeof dataAttr === 'string' && dataAttr.trim()) {
      try {
        dataOptions = JSON.parse(dataAttr);
      } catch (err) {
        console.warn('Invalid JSON in data-swiper:', err);
      }
    }

    // Localize pagination selector to this slider (avoids cross-binding)
    if (dataOptions.pagination && typeof dataOptions.pagination.el === 'string') {
      var pagEl = $(slider).find(dataOptions.pagination.el)[0];
      if (pagEl) dataOptions.pagination.el = pagEl;
    }

    // Optional: localize navigation if you add it later via data-swiper
    if (dataOptions.navigation) {
      ['nextEl', 'prevEl'].forEach(function (k) {
        if (typeof dataOptions.navigation[k] === 'string') {
          var navEl = $(slider).find(dataOptions.navigation[k])[0];
          if (navEl) dataOptions.navigation[k] = navEl;
        }
      });
    }

    // Merge options (deep merge to preserve nested objects like autoplay/pagination)
    var options = $.extend(true, {}, defaultOptions, dataOptions);

    // Init Swiper
    var swiper = new Swiper(slider, options);

    // Pause on hover only when autoplay is enabled and API exists
    if (options.autoplay && swiper.autoplay) {
      slider.addEventListener('mouseenter', function () {
        swiper.autoplay.stop();
      });
      slider.addEventListener('mouseleave', function () {
        swiper.autoplay.start();
      });
    }
  });

  // === CONFIG ===
  const DURATION_MS = 12000; // your value

  // === ELEMENTS ===
  const accordion = document.getElementById('featuresAccordion');

  // Only run accordion code if the element exists on the page
  if (accordion) {
    const items = [...accordion.querySelectorAll('.accordion-item')];
    const panes = [...document.querySelectorAll('.pane')];
    let current = 0;
    let timer = null;
    let isProgrammatic = false; // prevents event recursion

    function activatePaneAndBar(i) {
      const item = items[i];

      // right pane
      const targetId = item.getAttribute('data-preview');
      panes.forEach(p => p.classList.toggle('active', p.id === targetId));

      // progress bars
      items.forEach(it => {
        const bar = it.querySelector('.acc-progress');
        if (!bar) return;
        bar.style.transitionDuration = '0ms';
        bar.style.transform = 'scaleY(0)';
      });
      const bar = item.querySelector('.acc-progress');
      if (bar) {
        void bar.offsetHeight; // reflow
        bar.style.transitionDuration = DURATION_MS + 'ms';
        bar.style.transform = 'scaleY(1)';
      }
    }
    function showPaneByItemIndex(i) {
      const item = items[i];
      const collapseEl = item.querySelector('.accordion-collapse');

      // Use API without toggling to avoid firing show -> toggle -> show loop
      const bs = bootstrap.Collapse.getOrCreateInstance(collapseEl, {
        toggle: false
      });
      isProgrammatic = true; // guard so event listener won't recurse
      bs.show(); // ensure open
      isProgrammatic = false;
      activatePaneAndBar(i);
    }
    function scheduleNext() {
      clearTimeout(timer);
      timer = setTimeout(() => {
        current = (current + 1) % items.length;
        showPaneByItemIndex(current);
        scheduleNext();
      }, DURATION_MS);
    }

    // --- Init: open first and start ---
    showPaneByItemIndex(current);
    scheduleNext();

    // Click: jump and restart
    items.forEach((item, idx) => {
      const btn = item.querySelector('.accordion-button');
      btn.addEventListener('click', () => {
        current = idx;
        showPaneByItemIndex(current);
        scheduleNext();
      });
    });

    // When a panel is opened manually (keyboard/mouse), just sync state,
    // but DO NOT call show()/toggle() again.
    accordion.addEventListener('show.bs.collapse', e => {
      if (isProgrammatic) return; // ignore programmatic .show()

      const idx = items.findIndex(it => it.contains(e.target));
      if (idx !== -1) {
        current = idx;
        activatePaneAndBar(current); // no collapse calls here
        scheduleNext();
      }
    });
  }

  //magnific popup js
  $(".popup-youtube, .popup-vimeo, .popup-gmaps").magnificPopup({
    disableOn: 700,
    type: "iframe",
    mainClass: "mfp-fade",
    removalDelay: 160,
    preloader: false,
    fixedContentPos: false
  });
  $(".popup-with-form").magnificPopup({
    type: "inline",
    preloader: false,
    focus: "#name"
  });

  // Date Range Picker
  $(function () {
    // Check if daterangepicker plugin exists and element is present
    if (typeof $.fn.daterangepicker !== 'undefined' && $('input[name="birthday"]').length > 0) {
      // Initialize the daterangepicker
      $('input[name="birthday"]').daterangepicker({
        singleDatePicker: true,
        showDropdowns: true,
        minYear: 1901,
        maxYear: parseInt(moment().format('YYYY'), 10),
        autoApply: true,
        parentEl: '.date_picker_wrapper',
        opens: 'right'
      }, function (start, end, label) {
        var years = moment().diff(start, 'years');
        alert("You are " + years + " years old!");
      });

      // Show calendar immediately on page load
      var picker = $('input[name="birthday"]').data('daterangepicker');
      if (picker) {
        picker.show();
      }

      // Override the plugin's hide method to prevent hiding
      var picker = $('input[name="birthday"]').data('daterangepicker');
      if (picker) {
        picker.hide = function () {}; // Empty function to prevent hiding
      }

      // Force display block with CSS and !important
      $('<style>').text(`
          .daterangepicker { 
              display: block !important; 
              opacity: 1 !important;
              visibility: visible !important;
          }
          .daterangepicker.single { 
              display: block !important; 
          }
          .daterangepicker.opensright { 
              display: block !important; 
          }
          .daterangepicker.show-calendar { 
              display: block !important; 
          }
      `).appendTo('head');

      // Prevent all hide events
      $('input[name="birthday"]').on('hide.daterangepicker', function (ev, picker) {
        ev.preventDefault();
        ev.stopPropagation();
        return false;
      });

      // Also prevent the show event from being toggled
      $('input[name="birthday"]').on('show.daterangepicker', function (ev, picker) {
        ev.preventDefault();
        ev.stopPropagation();
        return false;
      });

      // Stop propagation on all clicks within the picker
      $(document).on('click', '.daterangepicker, .daterangepicker *', function (e) {
        e.stopPropagation();
      });

      // Prevent clicking outside from hiding the picker (but allow normal navigation)
      $(document).on('mousedown', function (e) {
        if (!$(e.target).closest('.daterangepicker').length && !$(e.target).is('input[name="birthday"]') && !$(e.target).is('a') && !$(e.target).closest('a').length) {
          e.stopPropagation();
        }
      });

      // Additional safety: periodically check and force show if hidden
      setInterval(function () {
        var picker = $('input[name="birthday"]').data('daterangepicker');
        if (picker && !picker.container.is(':visible')) {
          picker.container.show();
          picker.container.css({
            'display': 'block !important',
            'opacity': '1 !important',
            'visibility': 'visible !important'
          });
        }
      }, 100);
    }
  });

  // Date Range Picker

  // File Upload
  document.querySelectorAll(".upload .upload-block").forEach(function (btn) {
    btn.addEventListener("click", function () {
      var input = this.nextElementSibling;
      if (input) {
        input.click();
      }
    });
  });
  document.querySelectorAll(".upload input").forEach(function (input) {
    input.addEventListener("change", function () {
      var file_name = this.files[0].name;
      var file_name_element = this.nextElementSibling.querySelector(".file_name");
      if (file_name_element) {
        file_name_element.textContent = file_name;
      }
    });
  });
  // File Upload

  //    dark light mood
  var setDarkMode = (active = false) => {
    var wrapper = document.querySelector(":root");
    if (active) {
      wrapper.setAttribute("data-bs-theme", "dark");
      localStorage.setItem("theme", "dark");
    } else {
      wrapper.setAttribute("data-bs-theme", "light");
      localStorage.setItem("theme", "light");
    }
  };
  var toggleDarkMode = () => {
    var theme = document.querySelector(":root").getAttribute("data-bs-theme");
    // If the current theme is "light", we want to activate dark
    setDarkMode(theme === "light");
  };
  var initDarkMode = () => {
    var theme = localStorage.getItem("theme");
    if (theme == "dark") {
      setDarkMode(true);
    } else {
      setDarkMode(false);
    }
    var toggleButton = document.querySelector(".tt-theme-toggle");
    toggleButton && toggleButton.addEventListener("click", toggleDarkMode);
  };
  initDarkMode();
});

// JavaScript Document

// Customer Sidebar
const dashBtn = document.querySelectorAll(".dashboard_btn");
const dashItems = document.querySelectorAll(".dashboard_item_wrapper");
for (let i = 0; i < dashBtn.length; i++) {
  dashBtn[i].addEventListener("click", function () {
    dashItems[i].classList.toggle("show");
  });
}
// Customer Sidebar