var appStart = function ($) {

    var screenWidth = $(window).width();
   
    // handleStickyHeader  =============
    var handleStickyHeader = function () {
        if ($(".sticky-nav").length > 0) {
            var navbar = $(".sticky-nav");
            var navbarOffset = navbar.offset().top;
            $(window).on("scroll", function () {
                var scrollTop = $(window).scrollTop();
                if (scrollTop > navbarOffset) {
                    navbar.addClass("sticky-menu");
                } else {
                    navbar.removeClass("sticky-menu");
                }
            });
        }
    }

    // Scroll To Top ============
    var handleScrollIndicator = function () {
        const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        const scrollProgress = document.querySelectorAll('.scrollup');

        if (scrollProgress.length > 0) {
            scrollProgress.forEach(el => {
                if (scrollTop > 500) {
                    el.classList.add('is-active');
                } else {
                    el.classList.remove('is-active');
                }
                // Add click listener
                el.addEventListener('click', function () {
                    window.scrollTo({
                        top: 0,
                        behavior: 'smooth'
                    });
                });
            });
        }
    }

    // handle Header Menu ============
    var handleHeaderMenu = function () {
        if ($(window).width() <= 991) {
            jQuery('.menu-wrap li > a, .dropdown-menu li > a')
                .off("click keypress")
                .on("click keypress", function (e) {
                    if (e.type === "keypress" && e.key !== "Enter") return;
                    // handleMenus(e, jQuery(this));
                });
            jQuery('.tabindex').attr("tabindex", "0");

            jQuery('.mobile-toggler button')
                .off('click')
                .on('click', function (e) {
                    e.preventDefault();
                    console.log(11);
                    let parentLi = jQuery(this).closest('li');
                    let dropdown = parentLi.find('.dropdown-menu').first();
                    if (parentLi.hasClass('open')) {
                        dropdown.slideUp('slow', function () {
                            jQuery(this).css('display', 'none');
                        });
                        parentLi.removeClass('open');
                    } else {
                        parentLi.siblings('li').removeClass('open')
                            .children('.dropdown-menu, .mega-menu').slideUp('slow').css('display', 'none');
                        dropdown.css('display', 'block').slideDown();
                        parentLi.addClass('open');
                    }
                });
        } else {
            jQuery('.tabindex').removeAttr("tabindex");
            jQuery('.dropdown-menu, .mega-menu').removeAttr('style');
            jQuery('.menu-wrap li').removeClass('open');
        }
    };

    // Handle Toggler Mobile Sidebar Menu ============
    var handleTogglerMobileMenu = function () {
        const menuToggler = document.querySelector('.menu-toggle');
        if (menuToggler) {
            const body = document.querySelector('body');
            const menuCloses = document.querySelectorAll('.menu-close');
            const target = menuToggler.getAttribute('data-target');
            const targetElement = document.querySelector(target);
            const toggleMenu = () => {
                if (window.innerWidth <= 991) {
                    menuToggler.addEventListener('click', openMenu);
                    menuCloses.forEach(btn => {
                        btn.addEventListener('click', closeMenu);
                    });
                } else {
                    menuToggler.removeEventListener('click', openMenu);
                    menuCloses.forEach(btn => {
                        btn.removeEventListener('click', closeMenu);
                    });
                    menuToggler.classList.remove('open');
                    body.classList.remove('fixed');
                    targetElement.classList.remove('show');
                    setTimeout(() => {
                        trapFocus(targetElement);
                    }, 1000);
                }
            };
            const openMenu = () => {
                menuToggler.classList.add('open');
                body.classList.add('fixed');
                targetElement.classList.add('show');
                setTimeout(() => {
                    trapFocus(targetElement);
                }, 1000);
            };
            const closeMenu = () => {
                menuToggler.classList.remove('open');
                body.classList.remove('fixed');
                targetElement.classList.remove('show');
                releaseTrap();
            };
            toggleMenu();
            window.addEventListener('resize', toggleMenu);
        }
    }

    // Handle Search Toggle ============ 
    var handleSearchToggle = function () {
        const toggleBtn = document.querySelector('.header-search-toggle');
        const popup = document.querySelector('.header-search-popup');
        if (!toggleBtn || !popup) {
            console.warn('Search popup or toggle button missing');
            return;
        }
        const closeBtn = popup.querySelector('.header-search-close');
        toggleBtn.addEventListener('click', () => {
            popup.classList.add('header-search-active');
            setTimeout(() => {
                trapFocus(popup);
            }, 1000);
        });
        if (closeBtn) {
            closeBtn.addEventListener('click', () => {
                popup.classList.remove('header-search-active');
                releaseTrap();
                toggleBtn.focus();
            });
        }
    };

    // handle Magnific Video Popup =============== 
    var handleMagnificVideoPopup = function () {
        if (jQuery('.popup-youtube, .popup-vimeo').length > 0) {
            $('.popup-youtube, .popup-vimeo').magnificPopup({
                disableOn: 700,
                type: 'iframe',
                mainClass: 'mfp-fade',
                removalDelay: 160,
                preloader: false,
                fixedContentPos: true
            });
        }
    }
	
	/* Main Slider */
	if (jQuery('.main-slider').length > 0) {
		var sync1 = $(".main-slider");
			sync1.owlCarousel({
				items: 1,
				rtl: $('html').attr('dir') == 'rtl' ? true : false,
				loop: false,
				margin: 0,
				autoplay: false,
				autoplayTimeout: 5000,
				autoplayHoverPause: false,
				smartSpeed: 1500,
				nav: true,
				dots: false,
				mouseDrag: false,
				autoHeight: false,
				animateOut: 'fadeOut',
				animateIn: 'fadeIn',
				navText: ["<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>"],
			});
	}
	
	/* Service Section */
	if (jQuery('.service-slider').length > 0) {
            $('.service-slider').owlCarousel({
                loop: true,
				rtl: $('html').attr('dir') == 'rtl' ? true : false,
                margin: 10,
                nav: true,
                dots: false,
                autoplay: true,
                autoplayTimeout: 5000,
                smartSpeed: 1000,
                navText: ["<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>"],
                responsive: {
                    0: {
                        items: 2
                    },
                    768: {
                        items: 3
                    },
                    992: {
                        items: 4,
                        margin: 25
                    }
                }
            });
        }
		
		/* Team */
		if ($('.team-slider').length > 0) {
			$('.team-slider').owlCarousel({
				loop: true,
				rtl: $('html').attr('dir') == 'rtl' ? true : false,
				margin: 10,
				nav: true,
				dots: false,
				autoplay: true,
				autoplayTimeout: 5000,
				smartSpeed: 1000,
				navText: ["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"
				],
				responsive: {
						0: {
							items: 2
						},
						768: {
							items: 3
						},
						992: {
							items: 4,
							margin: 25
						}
					}
			});
		}
		
		/* Award */
		if (jQuery('.award-slider').length > 0) {
			$('.award-slider').owlCarousel({
				loop: true,
				rtl: $('html').attr('dir') == 'rtl' ? true : false,
				margin: 12,
				nav: true,
				dots: false,
				autoplay: true,
				autoplayTimeout: 5000,
				smartSpeed: 1000,
				navText: ["<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>"],
				responsive: {
					0: {
						items: 3
					},
					768: {
						items: 4
					},
					992: {
						items: 6,
						margin: 20,
					}
				}
			});
		}
		
		/* Post Slider */
		if (jQuery('.post-slider').length > 0) {
            $('.post-slider').each(function () {
                $(this).owlCarousel({                    
                    loop: true,
					rtl: $('html').attr('dir') == 'rtl' ? true : false,
                    margin: 15,
					autoplay: true,
					autoplayTimeout: 5000,
                    autoplayHoverPause: true,
                    smartSpeed: 1000,
                    nav: false,
                    dots: false,
                    autoHeight: true,
                    animateOut: 'fadeOut',
                    animateIn: 'fadeIn',
                    responsive: {
                        0: {
                            items: 1
                        },
						768: {
                            items: 2
                        },
                        991: {
                            items: 3,
                            margin: 25
                        }
                    }
                });
            });
       }
	   
	   /* Service Three */
	   if (jQuery('.footer-service-slider').length > 0) {
		   $('.footer-service-slider').owlCarousel({
			loop: true,
			rtl: $('html').attr('dir') == 'rtl' ? true : false,
			margin: 10,
			nav: true,
			dots: false,
			autoplay: true,
			autoplayTimeout: 5000,
			smartSpeed: 1000,
			navText: ["<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>"],
			responsive: {
				0: {
					items: 3
				},
				768: {
					items: 4
				},
				992: {
					items: 5,
					margin: 18
				}
			}
		});
	}
	   
    // handle Rotating Text ===========
    var handleRotatingText = function () {
        if (jQuery('.rotating-text').length > 0) {
            const elements = document.querySelectorAll('.rotating-text');
            elements.forEach(el => {
                new CircleType(el);
            });
        }
    };

    // handle Highlight Feature Slider ============
    var handleHighlightFeatureSlider = function () {
        jQuery(document).ready(function ($) {
            $(".highlight-feature-slider").each(function () {
                var $slider = $(this);
                var rtlValue = $slider.data("rtl") ? $slider.data("rtl") : false;
                $slider.owlCarousel({
                    autoWidth: true,
					rtl: $('html').attr('dir') == 'rtl' ? true : false,
                    loop: true,
                    margin: 15,
                    autoplay: true,
                    smartSpeed: 1000,
                    autoplaySpeed: 5000,
                    autoplayTimeout: 5000,
                    autoplayHoverPause: true,
                    nav: false,
                    dots: false,
                    rtl: rtlValue,
                    autoHeight: true,
                    slideTransition: 'linear',
                    navText: ["<i class='fa fa-chevron-left'></i>", "<i class='fa fa-chevron-right'></i>"],
                    responsive: {
                        991: {
                            margin: 30
                        }
                    }
                });
            });
        });
    };

    // handle Masonry Filter  ============
    var handleMasonryFilter = function () {
        jQuery(document).ready(function ($) {
            $('.filter-group').each(function () {
                var $group = $(this);
                var $container = $group.find('.st-filter-init');
                var $filters = $group.find('.filter-tab .filter');
                // init MixItUp
                $container.mixItUp({
                    selectors: {
                        target: '.tile',
                        filter: $filters
                    },
                    animation: {
                        animateResizeContainer: false,
                        effects: 'fade scale'
                    }
                });

                // active class handling
                $filters.on('click', function () {
                    $filters.removeClass('active');
                    $(this).addClass('active');
                });

            });

        });
    };


    // handle Counter  ==============
    var handleCounter = function () {
        const counters = document.querySelectorAll('.odometer');
        if (!counters.length) return;
        const observer = new IntersectionObserver((entries, obs) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    let el = entry.target;
                    let countNumber = el.getAttribute("data-count");
                    el.innerHTML = countNumber;
                    $(el).fadeIn("slow");
                    obs.unobserve(el);
                }
            });
        }, {
            threshold: 0.3
        });
        counters.forEach(counter => observer.observe(counter));
    };

    // handle Select2 ==============
    var handleSelect2 = function () {
        const selects = document.querySelectorAll('.hb-form-field-input select');
        if (!selects.length) return;

        selects.forEach(select => {
            $(select).select2({
                maximumSelectionLength: 2
            });
        });
    }

    // handle Ripple Bg Effect ==============
    var handleRippleEffect = function () {
		jQuery(document).ready(function ($) {
			if ($(".ripple-area").length) {
				$(".ripple-area").ripples({
					resolution: 512,
					dropRadius: 20,
					perturbance: 0.04,
				});
			}
        })
    }

    // handle Box Aware Effect ==============
    var handleBoxAware = function () {
        if (jQuery('.hover-aware').length > 0) {
            $('.hover-aware').on('mouseenter', function (e) {
                var parentOffset = $(this).offset(),
                    relX = e.pageX - parentOffset.left,
                    relY = e.pageY - parentOffset.top;
                $(this).find('.effect').css({ top: relY, left: relX })
            }).on('mouseout', function (e) {
                var parentOffset = $(this).offset(),
                    relX = e.pageX - parentOffset.left,
                    relY = e.pageY - parentOffset.top;
                $(this).find('.effect').css({ top: relY, left: relX })
            });
        }
    }

    // handle Box Hover =============
    var handleBoxHover = function () {
        const boxHover = document.querySelectorAll('.box-hover');
        if (boxHover) {
            boxHover.forEach(function (element) {
                element.addEventListener('mouseenter', function () {
                    const selector = element.parentElement.parentElement;
                    selector.querySelectorAll('.box-hover').forEach(function (element) {
                        element.classList.remove('active');
                    });
                    element.classList.add('active');
                });
            });
        }
    }

    // Magnific Popup for Image Gallery ============
    var handleMagnificImagePopup = function () {
        if (jQuery('.image-popup').length > 0) {
            $('.image-popup').magnificPopup({
                type: 'image',
                mainClass: 'mfp-with-zoom',
                gallery: { enabled: true },
                zoom: {
                    enabled: true,
                    duration: 300, // duration of the effect, in milliseconds
                    easing: 'ease-in-out', // CSS transition easing function
                    opener: function (openerElement) {
                        return openerElement.is('img') ? openerElement : openerElement.find('img');
                    }
                }
            });
        }
    }

    // Custom Mouse Cursor ============
    var handleCustomMouseCursor = function () {
        if ($(".st-mouseCursor").length > 0) {
            var myCursor = jQuery(".st-mouseCursor");
            if (myCursor.length) {
                if ($("body")) {
                    const e = document.querySelector(".cursor-inner"),
                        t = document.querySelector(".cursor-outer");
                    let n,
                        i = 0,
                        o = !1;
                    (window.onmousemove = function (s) {
                        o ||
                            (t.style.transform =
                                "translate(" + s.clientX + "px, " + s.clientY + "px)"),
                            (e.style.transform =
                                "translate(" + s.clientX + "px, " + s.clientY + "px)"),
                            (n = s.clientY),
                            (i = s.clientX);
                    }),
                        $("body").on(
                            "mouseenter",
                            "button, a, .cursor-pointer",
                            function () {
                                e.classList.add("cursor-hover"),
                                    t.classList.add("cursor-hover");
                            }
                        ),
                        $("body").on(
                            "mouseleave",
                            "button, a, .cursor-pointer",
                            function () {
                                ($(this).is("a", "button") &&
                                    $(this).closest(".cursor-pointer").length) ||
                                    (e.classList.remove("cursor-hover"),
                                        t.classList.remove("cursor-hover"));
                            }
                        ),
                        (e.style.visibility = "visible"),
                        (t.style.visibility = "visible");
                }
            }
        }
    }

    // handle Autoptimize Effect =============
    var handleAutoptimizeEffect = function () {
        const elements = document.querySelectorAll(".st-autoptimize-left, .st-autoptimize-right");
        if (elements) {
            const observer = new IntersectionObserver((entries) => {
                entries.forEach((entry) => {
                    if (entry.isIntersecting) {
                        entry.target.classList.add("is-visible");
                        observer.unobserve(entry.target); // ek baar hi chale
                    }
                });
            }, {
                threshold: 0.4, // 40% element visible hone par
            });
            elements.forEach((el) => observer.observe(el));
        }
    }

    var handleTilt = function () {
        if (jQuery('.st-tilt').length > 0) {
            $('.st-tilt').tilt({
                glare: true,
                maxGlare: .5
            })
        }
    }

    // handle Trap Focus  ============
    let activeTrap = null;
    function trapFocus(container) {
        const focusableSelectors = `
        a[href],
        button:not([disabled]),
        textarea:not([disabled]),
        input:not([disabled]),
        select:not([disabled]),
        [tabindex]:not([tabindex="-1"])
    `;
        const focusable = container.querySelectorAll(focusableSelectors);
        if (!focusable.length) return;

        const first = focusable[0];
        const last = focusable[focusable.length - 1];

        // 🔥 Force focus into popup
        first.focus();
        activeTrap = function (e) {
            if (e.key !== 'Tab') return;
            if (e.shiftKey && document.activeElement === first) {
                e.preventDefault();
                last.focus();
            }
            if (!e.shiftKey && document.activeElement === last) {
                e.preventDefault();
                first.focus();
            }
        };
        document.addEventListener('keydown', activeTrap);
    }
    function releaseTrap() {
        if (activeTrap) {
            document.removeEventListener('keydown', activeTrap);
            activeTrap = null;
        }
    }

	var handlePackagesAmenities = function () {
			var showItems = 2;
			$(".packages-amenities").each(function () {
				var $list = $(this);
				var $items = $list.find("li");
				var totalItems = $items.length;
				var $button = $list.next(".more-link");
				$items.slice(showItems).hide();
				if (totalItems <= showItems) {
					$button.hide();
				}
				$button.off("click").on("click", function () {
					if ($(this).hasClass("expanded")) {
						$items.slice(showItems).slideUp();
						$(this).removeClass("expanded");
						$(this).html('Read More <i class="fa fa-plus-circle"></i>');
					} else {
						$items.slice(showItems).slideDown();
						$(this).addClass("expanded");
						$(this).html('Read Less <i class="fa fa-minus-circle"></i>');
					}
				});
			});
		};

    /* Function ============ */
    return {
        init: function () {
            handleStickyHeader();
            handleHeaderMenu();
            handleTogglerMobileMenu();
            handleSearchToggle();
            handleMagnificVideoPopup();
            handleRotatingText();
            handleHighlightFeatureSlider();
            handleMasonryFilter();
            handleRippleEffect();
            handleBoxAware();
            handleBoxHover();
            handleMagnificImagePopup();
            handleCustomMouseCursor();
            handleAutoptimizeEffect();
            handleTilt();
			handlePackagesAmenities();
        },

        load: function () {
            handleCounter();
            handleSelect2();
        },

        resize: function () {
            screenWidth = $(window).width();
            handleHeaderMenu();
            handleSelect2();
			handleRotatingText();
        },

        scroll: function () {
            handleScrollIndicator();
        }
    }
}(jQuery);


/* Document.ready Start */
document.addEventListener('DOMContentLoaded', function () {
    appStart.init();
});
/* Document.ready END */

/* Window Load START */
window.addEventListener('load', function () {
    appStart.load();
	
});
/* Window Load END */

/* Window Resize START */
window.addEventListener('resize', function () {
    appStart.resize();
});
/*  Window Resize END */

/* Window Scroll START */
window.addEventListener("scroll", function () {
    appStart.scroll();
});
/*  Window Scroll END */

jQuery(document).ready(function ($) {
	if (typeof flatpickr !== "undefined") {
	  const checkinInput = $("input[name='check_in_date']");
	  const checkoutInput = $("input[name='check_out_date']");

	  $(".booking-section .hb-form-field-input:not(.theme-2 .booking-section .hb-form-field-input)").append('<span class="wphb_date"></span><span class="wphb_month"></span>');
	  $(".booking-section .hb-form-field-input:not(.theme-2 .booking-section .hb-form-field-input):not(:has(.nav-guest,.hb_input_date_check)),.booking-section .hb-form-field-input:not(.theme-2 .booking-section .hb-form-field-input):has(.select2)").append(`<div class="nav-guest"><span class="goUp"><i class="fa fa-chevron-up" aria-hidden="true"></i></span><span class="goDown"><i class="fa fa-chevron-down" aria-hidden="true"></i></span></div>`);

	  function updateDate(input, date, instance) {
		let full = instance.formatDate(date, "Y-m-d");
		let day = instance.formatDate(date, "d");
		let month = instance.formatDate(date, "M");

		input.val(full).attr("value", full);

		let wrapper = input.closest(".hb-form-field-input");
		wrapper.find(".wphb_date").text(day);
		wrapper.find(".wphb_month").text(month);
	  }

	  flatpickr(".hb_input_field", {
		mode: "range",
		dateFormat: "Y-m-d",
		minDate: "today",

		onReady: function (selectedDates, dateStr, instance) {

		  let today = new Date();
		  let tomorrow = new Date();
		  tomorrow.setDate(today.getDate() + 6);

		  updateDate(checkinInput, today, instance);
		  updateDate(checkoutInput, tomorrow, instance);
		},

		onChange: function (selectedDates, dateStr, instance) {

		  if (selectedDates.length > 0) {
			updateDate(checkinInput, selectedDates[0], instance);
		  }

		  if (selectedDates.length > 1) {
			updateDate(checkoutInput, selectedDates[1], instance);
		  }

		}
	  });
	}
	
	
	/* == Toggle Count Arrow Functioning == */
    $('select').select2({
        templateSelection: function (data) {
            if (!data.id) return data.text; // placeholder
            return String(data.text).padStart(2, '0');
        },
        templateResult: function (data) {
            if (!data.id) return data.text;
            return String(data.text).padStart(2, '0');
        },
        minimumResultsForSearch: -1 // optional: hide search
    });

    // ✅ Set default value (avoid "Adults"/"Children")
    $('.hb-form-field-input select').each(function () {
        const $select = $(this);
        if (!$select.val()) {
            const firstValue = $select.find('option[value!=""]').first().val();
            if (firstValue) {
                $select.val(firstValue).trigger('change');
            }
        }
    });

    // ✅ Increment / Decrement logic
    $('.goUp, .goDown').on('click', function () {
        const $wrapper = $(this).closest('.hb-form-field-input');
        const $select  = $wrapper.find('select');
        const values = $select.find('option')
            .map(function () { return $(this).val(); })
            .get()
            .filter(v => v !== '') // remove placeholder
            .map(Number);
        let current = Number($select.val());
        if (!current) current = values[0];
        let index = values.indexOf(current);
        if ($(this).hasClass('goDown')) {
            if (index > 0) index--;
        } else {
            if (index < values.length - 1) index++;
        }
        const newValue = values[index];
        // ✅ Update select (Select2 auto updates UI)
        $select.val(newValue).trigger('change');
    });
	
	
	/* == Related Room Slider Navigation == */
	const $carousel = $('.hb_related_other_room');
    const $next = $carousel.find('.next');
    const $prev = $carousel.find('.prev');
    $next.on('click', function () {
        $('.rooms.tp-hotel-booking').trigger('next.owl.carousel');
    });
    $prev.on('click', function () {
        $('.rooms.tp-hotel-booking').trigger('prev.owl.carousel');
    });

    function updateNavState() {

        const isFirst = $carousel.find('.owl-item:first').hasClass('active');
        const isLast  = $carousel.find('.owl-item:last').hasClass('active');

        if (!isFirst) {
            $prev.css('cursor', 'not-allowed');
        } else {
            $prev.css('cursor', 'pointer');
        }

        if (!isLast) {
            $next.css('cursor', 'not-allowed');
        } else {
            $next.css('cursor', 'pointer');
        }
    }

    $carousel.on('changed.owl.carousel', function () {
        updateNavState();
    });

    setTimeout(function () {
        updateNavState();
    }, 100);
});