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 handleRemoveSectionIds = function () {
        if (!document.body.classList.contains('wp-hotel-booking-search-rooms')) return;
        var bookingSection = document.getElementById('booking-section');
        if (bookingSection) {
            bookingSection.querySelectorAll('[id], [class]').forEach(function (el) {
                el.removeAttribute('id');
                el.removeAttribute('class');
            });
            Array.from(bookingSection.children).forEach(function (child) {
                child.classList.add('container');
            });
            var formEl = bookingSection.querySelector('form');
            if (formEl) {
                var next = formEl.nextElementSibling;
                while (next) {
                    var sibling = next;
                    next = next.nextElementSibling;
                    sibling.remove();
                }
                formEl.outerHTML = '<form name="hb-search-form" action="" class="hb-form-table-wrapper"><h3>Check Availability</h3><ul class="hb-form-table"><li class="hb-form-field"><label>Check-in Date</label><div class="hb-form-field-input hb_input_field flatpickr-input" readonly="readonly"><input type="text" name="check_in_date" class="hb_input_date_check flatpickr-input" value="" placeholder="Check-in Date" autocomplete="off" readonly="readonly"><span class="wphb_date"></span><span class="wphb_month"></span></div></li><li class="hb-form-field"><label>Check-out Date</label><div class="hb-form-field-input hb_input_field flatpickr-input" readonly="readonly"><input type="text" name="check_out_date" class="hb_input_date_check flatpickr-input" value="" placeholder="Check-out Date" autocomplete="off" readonly="readonly"><span class="wphb_date"></span><span class="wphb_month"></span></div></li><li class="hb-form-field"><label>Adults</label><div class="hb-form-field-input"><select name="adults_capacity"><option value="">Adults</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option><option value="18">18</option><option value="19">19</option><option value="20">20</option></select><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></div></li><li class="hb-form-field"><label>Children</label><div class="hb-form-field-input"><select name="max_child"><option value="">Children</option></select><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></div></li><li class="hb-form-field"><label>Number of rooms</label><div class="hb-form-field-input"><select name="number-of-rooms"><option value="">Number of rooms</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option><option value="18">18</option><option value="19">19</option><option value="20">20</option></select><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></div></li></ul><input type="hidden" id="nonce" name="nonce" value="47a16dc431"><input type="hidden" name="_wp_http_referer" value="/nitinthemes/wordpress70/"><input type="hidden" name="hotel-booking" value="results"><input type="hidden" name="widget-search" value=""><input type="hidden" name="action" value="hotel_booking_parse_search_params"><input type="hidden" name="paged" value="1"><p class="hb-submit"><button type="submit" class="wphb-button">Check Availability</button></p></form>';

                window.__hbBookingFormHandled = true;

                setTimeout(function () {
                    if (typeof jQuery === 'undefined' || typeof flatpickr === 'undefined') return;
                    var $ = jQuery;
                    var newForm = bookingSection.querySelector('form[name="hb-search-form"]');
                    if (!newForm) return;

                    var checkinInput = $(newForm).find("input[name='check_in_date']");
                    var checkoutInput = $(newForm).find("input[name='check_out_date']");
                    var storedCheckin = '';
                    var storedCheckout = '';

                    function updateDateSpan(input, date, instance) {
                        var full = instance.formatDate(date, "Y-m-d");
                        var internal = instance.formatDate(date, "Y/m/d");
                        var day = instance.formatDate(date, "d");
                        var month = instance.formatDate(date, "M");
                        input.val(full).attr("value", full).trigger("change");
                        if (input.attr('name') === 'check_in_date') {
                            storedCheckin = internal;
                        } else {
                            storedCheckout = internal;
                        }
                        var wrapper = input.closest(".hb-form-field-input");
                        if (wrapper.length) {
                            wrapper.find(".wphb_date").text(day);
                            wrapper.find(".wphb_month").text(month);
                        }
                    }

                    $(newForm).find(".hb_input_field").flatpickr({
                        mode: "range",
                        dateFormat: "Y-m-d",
                        minDate: "today",
                        onReady: function (selectedDates, dateStr, instance) {
                            var today = new Date();
                            var tomorrow = new Date();
                            tomorrow.setDate(today.getDate() + 6);
                            updateDateSpan(checkinInput, today, instance);
                            updateDateSpan(checkoutInput, tomorrow, instance);
                        },
                        onChange: function (selectedDates, dateStr, instance) {
                            if (selectedDates.length > 0) {
                                updateDateSpan(checkinInput, selectedDates[0], instance);
                            }
                            if (selectedDates.length > 1) {
                                updateDateSpan(checkoutInput, selectedDates[1], instance);
                            }
                        }
                    });

                    document.addEventListener('submit', function (e) {
                        var form = e.target;
                        if (form.name !== 'hb-search-form') return;
                        if (form.id === 'hb-form-search-page') return;
                        e.preventDefault();
                        e.stopPropagation();
                        var checkinVal = storedCheckin || '';
                        var checkoutVal = storedCheckout || '';
                        if (!checkinVal || !checkoutVal) {
                            var ci = form.querySelector('input[name="check_in_date"]');
                            var co = form.querySelector('input[name="check_out_date"]');
                            if (ci) checkinVal = checkinVal || ci.value;
                            if (co) checkoutVal = checkoutVal || co.value;
                        }
                        if (!checkinVal || !checkoutVal) {
                            alert('please select checkin checkout date and search again');
                            return;
                        }
                        var adults = form.querySelector('select[name="adults_capacity"]');
                        var children = form.querySelector('select[name="max_child"]');
                        var data = {
                            check_in_date: checkinVal,
                            check_out_date: checkoutVal,
                            adults: adults ? adults.value : '',
                            max_child: children ? children.value : ''
                        };
                        try { localStorage.setItem('wphb_filter_rooms', JSON.stringify(data)); } catch (ex) {}
                        var pageSearch = (typeof hotel_settings !== 'undefined' && hotel_settings.url_page_search)
                            ? hotel_settings.url_page_search
                            : (form.getAttribute('action') || window.location.pathname);
                        var sep = pageSearch.indexOf('?') !== -1 ? '&' : '?';
                        var url = pageSearch + sep
                            + 'check_in_date=' + encodeURIComponent(checkinVal)
                            + '&check_out_date=' + encodeURIComponent(checkoutVal);
                        if (data.adults) url += '&adults=' + encodeURIComponent(data.adults);
                        if (data.max_child) url += '&max_child=' + encodeURIComponent(data.max_child);
                        window.location.href = url;
                    }, true);
                }, 0);
            }
        }
    };

	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();
			handleRemoveSectionIds();
			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 ($) {
	$('form[name="hb-search-form"]').each(function () {
		var action = $(this).attr('action');
		if (action && action.indexOf('localhost') !== -1) {
			$(this).attr('action', window.location.origin + window.location.pathname);
		}
	});

	if (!window.__hbBookingFormHandled && typeof flatpickr !== "undefined" && !document.querySelector('#hb-form-search-page')) {
	  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>`);

	  var storedCheckin = '';
	  var storedCheckout = '';

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

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

		if (input.attr('name') === 'check_in_date') {
			storedCheckin = internal;
		} else {
			storedCheckout = internal;
		}

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

		}
	  });

	  document.addEventListener('submit', function (e) {
		var form = e.target;
		if (form.name !== 'hb-search-form') return;
		if (form.id === 'hb-form-search-page') return;

		e.preventDefault();
		e.stopPropagation();

		var checkinVal = storedCheckin || '';
		var checkoutVal = storedCheckout || '';

		if (!checkinVal || !checkoutVal) {
			var ci = form.querySelector('input[name="check_in_date"]');
			var co = form.querySelector('input[name="check_out_date"]');
			if (ci) checkinVal = checkinVal || ci.value;
			if (co) checkoutVal = checkoutVal || co.value;
		}

		if (!checkinVal || !checkoutVal) {
			alert('please select checkin checkout date and search again');
			return;
		}

		var adults = form.querySelector('select[name="adults"]');
		var children = form.querySelector('select[name="children"]');

		var data = {
			check_in_date: checkinVal,
			check_out_date: checkoutVal,
			adults: adults ? adults.value : '',
			max_child: children ? children.value : ''
		};

		try { localStorage.setItem('wphb_filter_rooms', JSON.stringify(data)); } catch (ex) {}

		var pageSearch = (typeof hotel_settings !== 'undefined' && hotel_settings.url_page_search)
			? hotel_settings.url_page_search
			: (form.getAttribute('action') || window.location.pathname);

		var sep = pageSearch.indexOf('?') !== -1 ? '&' : '?';
		var url = pageSearch + sep
			+ 'check_in_date=' + encodeURIComponent(checkinVal)
			+ '&check_out_date=' + encodeURIComponent(checkoutVal);
		if (data.adults) url += '&adults=' + encodeURIComponent(data.adults);
		if (data.max_child) url += '&max_child=' + encodeURIComponent(data.max_child);

		window.location.href = url;
	  }, true);
	}
	
	
	/* == 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);
});