(function ($) {
    "use strict";

    //Scroll back to top
    $(document).ready(function () {

        var progressPath = document.querySelector('.progress-wrap path');
        var pathLength = progressPath.getTotalLength();
        progressPath.style.transition = progressPath.style.WebkitTransition = 'none';
        progressPath.style.strokeDasharray = pathLength + ' ' + pathLength;
        progressPath.style.strokeDashoffset = pathLength;
        progressPath.getBoundingClientRect();
        progressPath.style.transition = progressPath.style.WebkitTransition = 'stroke-dashoffset 10ms linear';
        var updateProgress = function () {
            var scroll = $(window).scrollTop();
            var height = $(document).height() - $(window).height();
            var progress = pathLength - (scroll * pathLength / height);
            progressPath.style.strokeDashoffset = progress;
        }
        updateProgress();
        $(window).scroll(updateProgress);
        var offset = 50;
        var duration = 550;
        jQuery(window).on('scroll', function () {
            if (jQuery(this).scrollTop() > offset) {
                jQuery('.progress-wrap').addClass('active-progress');
            } else {
                jQuery('.progress-wrap').removeClass('active-progress');
            }
        });
        jQuery('.progress-wrap').on('click', function (event) {
            event.preventDefault();
            jQuery('html, body').animate({ scrollTop: 0 }, duration);
            return false;
        })

    });

    // Document Ready
    $(document).ready(function () {

        // menu_toggle
        $('.menu_toggle').on('click', function (event) {
            event.preventDefault();
            $("body").toggleClass('menu_active');
        });

        $(document).ready(function () {
            function toggleSticky() {
                if ($(window).scrollTop() >= 100) {
                    $(".site_header").addClass("sticky");
                } else {
                    $(".site_header").removeClass("sticky");
                }
            }

            // Run once on page load (handles refresh case)
            toggleSticky();

            // Run on scroll
            $(window).on("scroll", function () {
                toggleSticky();
            });
        });

        // accordion
        $('.accordion.v1').each(function () {
            const $accordion = $(this);

            // Hide all contents
            $accordion.find('.accordion_content').hide();

            // Open first item by default
            const $firstItem = $accordion.find('.accordion_item').first();
            $firstItem.addClass('active');
            $firstItem.find('.accordion_content').show();

            $accordion.find('.accordion_btn').on('click', function () {
                const $currentItem = $(this).closest('.accordion_item');
                const $currentContent = $currentItem.find('.accordion_content');

                if ($currentItem.hasClass('active')) {
                    $currentContent.stop(true, true).slideUp(300);
                    $currentItem.removeClass('active');
                } else {
                    $accordion.find('.accordion_item.active')
                        .removeClass('active')
                        .find('.accordion_content')
                        .stop(true, true)
                        .slideUp(300);

                    $currentItem.addClass('active');
                    $currentContent.stop(true, true).slideDown(300);
                }
            });
        });

        $('.accordion.v2').each(function () {
            const $accordion = $(this);

            // Optional: Open first item by default
            const $firstItem = $accordion.find('.accordion_item').first();
            $firstItem.addClass('active');
            $firstItem.find('.accordion_content').show();

            $accordion.find('.accordion_btn').on('click', function () {
                const $currentItem = $(this).closest('.accordion_item');
                const $currentContent = $currentItem.find('.accordion_content');

                // Toggle this item only
                if ($currentItem.hasClass('active')) {
                    $currentContent.stop(true, true).slideUp(300);
                    $currentItem.removeClass('active');
                } else {
                    $currentItem.addClass('active');
                    $currentContent.stop(true, true).slideDown(300);
                }
            });
        });


        // read more/less
        $(document).ready(function () {

            // Initial state
            $('.review_qoute').each(function () {
                $(this).find('.more_text').hide();
                $(this).find('.read_less').hide();
            });

            // Read More
            $(document).on('click', '.read_more', function () {
                const $parent = $(this).closest('.review_qoute');

                $parent.find('.more_text').slideDown(200);
                $(this).hide();
                $parent.find('.read_less').show();
            });

            // Read Less
            $(document).on('click', '.read_less', function () {
                const $parent = $(this).closest('.review_qoute');

                $parent.find('.more_text').slideUp(200);
                $(this).hide();
                $parent.find('.read_more').show();
            });

        });

        $(document).ready(function () {

            /* =========================
               DESKTOP (HOVER)
            ========================== */
            $('.dropdown_btn')
                .on('mouseenter.desktop', function () {
                    const id = $(this).data('btn');
                    $('[data-id="' + id + '"]').addClass('active_desktop');
                })
                .on('mouseleave.desktop', function () {
                    const id = $(this).data('btn');
                    const $menu = $('[data-id="' + id + '"]');

                    setTimeout(function () {
                        if (!$menu.is(':hover')) {
                            $menu.removeClass('active_desktop');
                        }
                    }, 10);
                });

            $('.dropdown_menu')
                .on('mouseenter.desktop', function () {
                    $(this).addClass('active_desktop');
                })
                .on('mouseleave.desktop', function () {
                    $(this).removeClass('active_desktop');
                });


            /* =========================
               MOBILE (CLICK)
            ========================== */
            $('.dropdown_btn').on('click', function (e) {
                e.preventDefault();

                const id = $(this).data('btn');
                $('[data-id="' + id + '"]').addClass('active_mobile');
            });

            $('.close_menu').on('click', function () {
                $('.dropdown_menu').removeClass('active_mobile');
            });

        });

        // select_btn
        $(document).on('click', '.dates .select_btn, .nav_style', function (e) {
            e.preventDefault();

            $('.dates .select_btn').removeClass('selected');
            $(this).addClass('selected');

            $('.nav_style').removeClass('active');
            $(this).addClass('active');

            const target = $(this).attr('href');
            const headerHeight = $('header').outerHeight() || 0;

            if (target && target.startsWith('#') && $(target).length) {
                $('html, body').animate({
                    scrollTop: $(target).offset().top - headerHeight - 20
                }, 600);
            }
        });

        // datepicker
        $(function () {

            let viewDate = new Date();
            const popup = $('#datepickerPopup');
            const daysBox = $('.datepicker-days');

            const monthNames = [
                "January", "February", "March", "April", "May", "June",
                "July", "August", "September", "October", "November", "December"
            ];

            function formatDate(d) {
                return String(d.getMonth() + 1).padStart(2, '0') + '/' +
                    String(d.getDate()).padStart(2, '0') + '/' +
                    d.getFullYear();
            }

            function render() {
                const y = viewDate.getFullYear();
                const m = viewDate.getMonth();

                $('.datepicker-month-year').text(monthNames[m] + ' ' + y);
                daysBox.empty();

                const firstDay = new Date(y, m, 1).getDay();
                const daysInMonth = new Date(y, m + 1, 0).getDate();
                const prevDays = new Date(y, m, 0).getDate();

                // PREV MONTH
                for (let i = firstDay - 1; i >= 0; i--) {
                    const d = prevDays - i;
                    $('<div class="datepicker-day other-month"></div>')
                        .text(d)
                        .data('date', new Date(y, m - 1, d))
                        .appendTo(daysBox);
                }

                // CURRENT MONTH
                for (let d = 1; d <= daysInMonth; d++) {
                    $('<div class="datepicker-day"></div>')
                        .text(d)
                        .data('date', new Date(y, m, d))
                        .appendTo(daysBox);
                }

                // NEXT MONTH
                while (daysBox.children().length < 42) {
                    const d = daysBox.children().length - (daysInMonth + firstDay) + 1;
                    $('<div class="datepicker-day other-month"></div>')
                        .text(d)
                        .data('date', new Date(y, m + 1, d))
                        .appendTo(daysBox);
                }
            }

            // OPEN
            $('.datepicker').on('click', function (e) {
                e.stopPropagation();
                popup.data('input', this).show();
                render();
            });

            // SELECT DATE (LOCKED – CANNOT FAIL)
            $(document).on('click', '.datepicker-day', function (e) {
                e.stopPropagation();

                const date = $(this).data('date');
                const input = popup.data('input');

                if (!date || !input) return;

                $(input).val(formatDate(date));
                popup.hide();
            });

            // NAV
            $('.prev-month').on('click', function (e) {
                e.stopPropagation();
                viewDate.setMonth(viewDate.getMonth() - 1);
                render();
            });

            $('.next-month').on('click', function (e) {
                e.stopPropagation();
                viewDate.setMonth(viewDate.getMonth() + 1);
                render();
            });

            // CLOSE ONLY WHEN CLICKING OUTSIDE
            $(document).on('click', function (e) {
                if (!$(e.target).closest('#datepickerPopup, .datepicker').length) {
                    popup.hide();
                }
            });

        });


        // fillter
        $(document).ready(function () {
            // Open filter sidebar
            $('.fillter_btn').on('click', function () {
                $('.filter-overlay').addClass('active');
                $('.filter-sidebar').addClass('active');
                $('body').css('overflow', 'hidden');
            });

            // Close filter sidebar
            function closeFilter() {
                $('.filter-overlay').removeClass('active');
                $('.filter-sidebar').removeClass('active');
                $('body').css('overflow', '');
            }

            $('.close-btn').on('click', closeFilter);
            $('.cancel-btn').on('click', closeFilter);
            $('.filter-overlay').on('click', closeFilter);

            // Prevent closing when clicking inside sidebar
            $('.filter-sidebar').on('click', function (e) {
                e.stopPropagation();
            });
        });


        // sort
         $(document).ready(function() {
            // Toggle dropdown
            $('.sort_btn').on('click', function(e) {
                e.stopPropagation();
                $(this).toggleClass('active');
                $('.sort-dropdown').toggleClass('active');
            });

            // Select sort option
            $('.sort-option').on('click', function() {
                // Remove selected class from all options
                $('.sort-option').removeClass('selected');
                
                // Add selected class to clicked option
                $(this).addClass('selected');
                
                // Get sort value
                const sortValue = $(this).data('sort');
                console.log('Sorting by:', sortValue);
                
                // Close dropdown
                $('.sort_btn').removeClass('active');
                $('.sort-dropdown').removeClass('active');
                
                // Optional: Update button text
                // $('.sort_btn p').text($(this).find('.sort-label').text());
            });

            // Close dropdown when clicking outside
            $(document).on('click', function(e) {
                if (!$(e.target).closest('.sort-container').length) {
                    $('.sort_btn').removeClass('active');
                    $('.sort-dropdown').removeClass('active');
                }
            });
        });


        // travels_slider
        new Swiper(".travels_slider", {
            loop: true,
            slidesPerView: 1,
            spaceBetween: 20,
            watchSlidesProgress: true,
            watchSlidesVisibility: true,
            pagination: {
                el: ".swiper-pagination",
                clickable: true,
            },
        });

        // review_slider
        new Swiper(".review_slider", {
            slidesPerView: 1,
            spaceBetween: 20,

            pagination: {
                el: ".swiper-pagination",
                clickable: true,
            },

            navigation: {
                nextEl: ".review_content .swiper-button-next",
                prevEl: ".review_content .swiper-button-prev",
            },
        });

        // dates_slider
        new Swiper(".dates_slider", {
            slidesPerView: 'auto',

            navigation: {
                nextEl: ".dates_slider .swiper-button-next",
                prevEl: ".dates_slider .swiper-button-prev",
            },
        });

        // nice-select Initialization
        $('.nice-select').niceSelect();

    });

})(jQuery);
