/** ============================================================
 *  JS File for Kipya Template
 *===============================================================*/
$(document).ready(function() {
    $('.menu-item').hover(
        function() {
            $(this).children('.sub-menu').stop(true, true).slideDown(200); // Adjust the speed as needed
        },
        function() {
            $(this).children('.sub-menu').stop(true, true).slideUp(200);
        }
    );
});

jQuery(document).ready(function ($) {
    console.log("GLightbox script loaded!"); // Debugging log

    $('.home-gallery-item .wp-block-image').each(function () {
        var img = $(this).find('img');

        if (img.length) {
            var src = img.attr('src');
            var parentLink = img.parent('a');

            if (!parentLink.length) {
                console.log("Wrapping image:", src);
                img.wrap('<a href="' + src + '" class="gallery-lightbox" data-glightbox="gallery"></a>');
            }
        }
    });

    // Initialize GLightbox
    const lightbox = GLightbox({
        selector: '.gallery-lightbox',
        touchNavigation: true,
        loop: true,
        closeButton: true,
        autoplayVideos: false
    });

    console.log("GLightbox initialized!");
});



/** ============================================================================
 * MENU JS
*=============================================================================*/


// Sticky header effect
let lastScrollTop = 0;
window.addEventListener('scroll', function() {
    const currentScroll = window.pageYOffset || document.documentElement.scrollTop;
    const header = document.querySelector('.main-header').parentElement;
    
    if (currentScroll > 50) {
        header.classList.add('header-sticky');
    } else {
        header.classList.remove('header-sticky');
    }
    
    lastScrollTop = currentScroll <= 0 ? 0 : currentScroll;
}, false);

// Active menu item highlighting
document.addEventListener('DOMContentLoaded', function() {
    const currentUrl = window.location.pathname;
    const menuItems = document.querySelectorAll('.navbar-nav .nav-link, .mobile-nav .nav-link');
    
    menuItems.forEach(item => {
        const href = item.getAttribute('href');
        if (href) {
            if (href === currentUrl || 
                (href !== '/' && currentUrl.includes(href.replace(/^.*\//, ''))) ||
                (href === home_url && (currentUrl === '/' || currentUrl === ''))) {
                item.classList.add('active');
            }
        }
    });
});

// Enhanced dropdown functionality - SIMPLIFIED AND FIXED
document.addEventListener('DOMContentLoaded', function() {
    // Remove Bootstrap dropdown interference completely
    document.querySelectorAll('[data-bs-toggle="dropdown"]').forEach(element => {
        element.removeAttribute('data-bs-toggle');
        element.removeAttribute('data-bs-auto-close');
        element.removeAttribute('role');
        element.removeAttribute('aria-expanded');
        element.classList.remove('dropdown-toggle');
    });
    
    // Ensure all dropdown items have the right classes
    document.querySelectorAll('.navbar-nav .nav-item').forEach(item => {
        const link = item.querySelector('.nav-link');
        const hasChildren = item.classList.contains('menu-item-has-children') || 
                           item.classList.contains('dropdown') ||
                           item.querySelector('.dropdown-menu, .sub-menu');
        
        if (hasChildren) {
            item.classList.add('dropdown', 'hover-dropdown');
            const subMenu = item.querySelector('.sub-menu');
            if (subMenu) {
                subMenu.classList.add('dropdown-menu');
            }
        }
    });
    
    // Force show dropdowns on hover with JavaScript backup
    document.querySelectorAll('.navbar-nav .dropdown, .navbar-nav .hover-dropdown').forEach(item => {
        const dropdown = item.querySelector('.dropdown-menu');
        
        if (dropdown) {
            item.addEventListener('mouseenter', function() {
                dropdown.style.opacity = '1';
                dropdown.style.visibility = 'visible';
                dropdown.style.transform = 'translateY(0) translateX(-50%)';
                dropdown.style.display = 'block';
            });
            
            item.addEventListener('mouseleave', function() {
                dropdown.style.opacity = '0';
                dropdown.style.visibility = 'hidden';
                dropdown.style.transform = 'translateY(10px) translateX(-50%)';
                setTimeout(() => {
                    if (dropdown.style.opacity === '0') {
                        dropdown.style.display = 'none';
                    }
                }, 300);
            });
        }
    });
});

// Mobile dropdown toggle functionality
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.mobile-dropdown-toggle').forEach(toggle => {
        toggle.addEventListener('click', function(e) {
            e.preventDefault();
            const parent = this.parentElement;
            const menu = parent.querySelector('.mobile-dropdown-menu');
            
            if (menu) {
                const isVisible = menu.style.display === 'block';
                
                // Hide all other open dropdowns
                document.querySelectorAll('.mobile-dropdown-menu').forEach(m => {
                    m.style.display = 'none';
                    m.parentElement.classList.remove('active');
                });
                
                // Toggle current dropdown
                if (!isVisible) {
                    menu.style.display = 'block';
                    parent.classList.add('active');
                } else {
                    menu.style.display = 'none';
                    parent.classList.remove('active');
                }
            }
        });
    });
});

// Close mobile menu when clicking a link (not dropdown toggle)
document.querySelectorAll('.mobile-nav a:not(.mobile-dropdown-toggle)').forEach(link => {
    link.addEventListener('click', function(e) {
        const offcanvas = document.querySelector('#offcanvasNavbar');
        if (typeof bootstrap !== 'undefined') {
            const bsOffcanvas = bootstrap.Offcanvas.getInstance(offcanvas);
            if (bsOffcanvas) {
                bsOffcanvas.hide();
            }
        }
    });
});


/** ============================================================================
 * HEADER SCROLL
*=============================================================================*/
document.addEventListener("DOMContentLoaded", function() {
    var header = document.querySelector('.menu-section');
    var header2 = document.querySelector('.menu-section2');
    
    if (header && header2) { // Check if both headers are present
        window.addEventListener('scroll', function() {
            if (window.scrollY > 100) {
                header.classList.add('sticky-header');
                header2.classList.add('sticky-header');
            } else {
                header.classList.remove('sticky-header');
                header2.classList.remove('sticky-header');
            }
        });
    } else if (header) { // Only header1 is present
        window.addEventListener('scroll', function() {
            if (window.scrollY > 100) {
                header.classList.add('sticky-header');
            } else {
                header.classList.remove('sticky-header');
            }
        });
    } else if (header2) { // Only header2 is present
        window.addEventListener('scroll', function() {
            if (window.scrollY > 100) {
                header2.classList.add('sticky-header');
            } else {
                header2.classList.remove('sticky-header');
            }
        });
    }
});


/**====================================================
   * Slides - Animation JS
   *====================================================**/
function thmSwiperInit() {
    // swiper slider
    if ($(".thm-swiper__slider").length) {
      $(".thm-swiper__slider").each(function () {
        let elm = $(this);
        let options = elm.data('swiper-options');
        let thmSwiperSlider = new Swiper(elm, options);
      });
    }
  }
  if ($(".banner-bg-slide").length) {
    $(".banner-bg-slide").each(function () {
      var Self = $(this);
      var bgSlideOptions = Self.data("options");
      var bannerTwoSlides = Self.vegas(bgSlideOptions);
    });
  }
  if ($(".wow").length) {
    var wow = new WOW({
      boxClass: "wow", // animated element css class (default is wow)
      animateClass: "animated", // animation css class (default is animated)
      mobile: true, // trigger animations on mobile devices (default is true)
      live: true // act on asynchronously loaded content (default is true)
    });
    wow.init();
  }
    // window load event
    $(window).on("load", function () {

      thmSwiperInit();
      //thmOwlInit();
      //handlePreloader();
      //languageSwitcher();
      //projectMasonaryLayout();
  
  
      //Jquery Spinner / Quantity Spinner
      if ($('.quantity-spinner').length) {
        $("input.quantity-spinner").TouchSpin({
          verticalbuttons: true
        });
      }
  
    });

/**====================================
* AOS
=====================================**/
     document.addEventListener('DOMContentLoaded', function () {
    // Initialize AOS for each column
    if (typeof AOS !== 'undefined') {
        AOS.init({
            duration: 1000,
            easing: 'ease-in-out',
            once: true,
            mirror: false,
        });
    }
});
/** ===============================================
 * Back to Top
 *=================================================*/
function select(selector) {
    return document.querySelector(selector);
}

// Check if the back-to-top element exists
var backtotop = select('.back-to-top');
if (backtotop) {
    const toggleBacktotop = () => {
        if (window.scrollY > 400) { // Change threshold to 200
            backtotop.classList.add('active');
        } else {
            backtotop.classList.remove('active');
        }
    };

    window.addEventListener('load', toggleBacktotop);
    window.addEventListener('scroll', toggleBacktotop);
    
    // Scroll to top on click
    backtotop.addEventListener('click', () => {
        window.scrollTo({
            top: 0,
            behavior: 'smooth' // Smooth scroll to top
        });
    });
}
 /**====================================
     * HIDE OVERFLOW
=====================================**/
     
(function ($, root, undefined) {
	
	$(function () {
		
		'use strict';
		
		// DOM ready, take it away
		$("html").attr("style", "overflow-x:hidden;");
		
	});
	
})(jQuery, this);
