(function ($) {
    "use strict";

    // ------- Prealoder ------
    $(window).on('load', function () {
        $("#preloader").delay(300).fadeOut("slow");
    });

    $(document).ready(function () {

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

            toggleSticky(); // Check on page load
            $(window).on("scroll", toggleSticky); // Check on scroll
        });

        // checbox
        $('.checkbox').click(function (e) {
            $(this).toggleClass('active');
        });

        // search_toggle
        $('.search_toggle').click(function (e) {
            $(this).closest(".search_area").toggleClass('active');
        });

        // =================== Dashboard Js ====================== //
        $('.select_btn').click(function (e) {
            // $(this).closest('.select_btns').find('.select_btn').not(this).removeClass("selected");
            $(this).toggleClass("selected");
        });

        // select_btns //
        $('.select_btns.v2 .select_btn').click(function (e) {
            $(this).closest('.select_btns.v2').find('.select_btn').not(this).removeClass("selected");
            $(this).addClass("selected");
        });

        // d_hamburger_btn 
        $(document).ready(function () {
            // Open sidebar
            $('.d_hamburger_btn').on('click', function (e) {
                e.stopPropagation();
                $('body').addClass('sidebar_active');
            });

            // Close sidebar on body click except sidebar or hamburger button
            $(document).on('click', function (e) {
                if (!$(e.target).closest('.dashboard_sidebar, .d_hamburger_btn').length) {
                    $('body').removeClass('sidebar_active');
                }
            });

            // Close sidebar when step_menu_btn clicked
            $('.dashboard_sidebar .step_menu_btn').on('click', function () {
                $('body').removeClass('sidebar_active');
            });
        });

        // step_buttons //
        $('.step_button').on('click', function () {
            var buttonId = $(this).attr('data-step');
            var $levels = $(this).closest('.levels');

            // Get all classes of the .levels element
            var classList = $levels.attr('class').split(/\s+/);

            // Remove all classes except 'levels'
            $.each(classList, function (index, item) {
                if (item !== 'levels') {
                    $levels.removeClass(item);
                }
            });

            // Add the buttonId as a class
            $levels.addClass(buttonId);

            // after 200ms, replace "step_level_seven" with "step_level_eight"
            if (buttonId === "step_level_nine") {
                setTimeout(function () {
                    window.location.href = 'results.html';
                }, 1000);
            }


            // if (buttonId === "step_level_ten") {

            //     var car_brand = $(this).find('.car_brand').attr('src');
            //     var percentage = $(this).find('.percentage_circle p').text();
            //     var product_img = $(this).find('.product_img img').attr('src');

            //     $('.get_car_brand').attr('src', car_brand);
            //     $('.car_details_left .percentage_circle p').text(percentage);
            //     $('.get_car').attr('src', product_img);


            // }
        });


        // price_range_slider
        $(document).ready(function () {
            let minPrice = 0;
            let maxPrice = 150000;
            let minPosition = 0;
            let maxPosition = 100;
            let rangeWidth = $('.range-container').width();
            let isDraggingMin = false, isDraggingMax = false;

            function updateSlider() {
                let minPercent = (minPosition / 100) * rangeWidth;
                let maxPercent = (maxPosition / 100) * rangeWidth;

                $('.min-handle').css('left', minPercent + 'px');
                $('.max-handle').css('left', maxPercent + 'px');
                $('.range-fill').css({ left: minPercent + 'px', width: (maxPercent - minPercent) + 'px' });

                let currentMin = Math.round(minPrice + ((maxPrice - minPrice) * (minPosition / 100)));
                let currentMax = Math.round(minPrice + ((maxPrice - minPrice) * (maxPosition / 100)));

                $('.min-price').text(currentMin.toLocaleString());
                $('.max-price').text(currentMax.toLocaleString());
            }

            function handleMove(e, isMinHandle) {
                // Support touch events: if touches exist, use the first touch point
                let pageX = e.pageX;
                if (e.originalEvent.touches && e.originalEvent.touches.length) {
                    pageX = e.originalEvent.touches[0].pageX;
                }
                let offset = $('.range-container').offset().left;
                let xPos = pageX - offset;
                let percent = (xPos / rangeWidth) * 100;
                percent = Math.max(0, Math.min(100, percent));

                if (isMinHandle) {
                    minPosition = Math.min(percent, maxPosition - 5);
                } else {
                    maxPosition = Math.max(percent, minPosition + 5);
                }

                updateSlider();
            }

            // Listen for both mouse and touch events
            $('.min-handle').on('mousedown touchstart', function (e) {
                e.preventDefault(); // Prevent default behavior on touch devices
                isDraggingMin = true;
            });
            $('.max-handle').on('mousedown touchstart', function (e) {
                e.preventDefault();
                isDraggingMax = true;
            });

            $(document).on('mousemove touchmove', function (e) {
                if (isDraggingMin) handleMove(e, true);
                if (isDraggingMax) handleMove(e, false);
            });

            $(document).on('mouseup touchend', function () {
                isDraggingMin = false;
                isDraggingMax = false;
            });

            updateSlider();
        });

        // append_div_btn
        $(document).on("click", ".append_div_btn", function (e) {
            e.preventDefault();

            let newDiv = $(this).closest(".append_div").clone();

            newDiv.find("input").val("");

            $(this).closest(".append_div").after(newDiv);
        });

        // custom_accordion_item
        $('.custom_accordion_item').click(function (e) {
            e.preventDefault();
            $(this).closest('.custom_accordion').find('.custom_accordion_item').not(this).removeClass("active");
            $(this).toggleClass("active");
        });

        // form_option
        $('.form_option').click(function (e) {
            e.preventDefault();
            $(this).closest('.form_options').find('.form_option').not(this).removeClass("active");
            $(this).toggleClass("active");
        });


        // Toggle dropdow
        $(document).ready(function () {

            // Toggle dropdown open (independent)
            $('.filter_form_wrap .filter_form').on('click', function (e) {
                e.stopPropagation();
                let $wrap = $(this).closest('.filter_form_wrap');

                // Close other dropdowns
                $('.dropdown_box').not($wrap.find('.dropdown_box')).fadeOut(200);

                // Toggle this one
                $wrap.find('.dropdown_box').fadeToggle(300);

                // Hide list until search clicked
                $wrap.find('.region_list').hide();
            });

            // Show list only when search input is clicked
            $('.filter_form_wrap .search_region').on('focus', function (e) {
                e.stopPropagation();
                let $wrap = $(this).closest('.filter_form_wrap');
                $wrap.find('.region_list').slideDown(300);
            });

            // Close dropdown (× button)
            $('.filter_form_wrap .close_btn').on('click', function () {
                $(this).closest('.dropdown_box').fadeOut(300);
            });

            // Close dropdown on apply button
            $('.filter_form_wrap .apply_btn').on('click', function () {
                $(this).closest('.dropdown_box').fadeOut(300);
            });

            // Click outside to close dropdowns and region lists (except search field)
            $(document).on('click', function (e) {
                if (!$(e.target).closest('.filter_form_wrap').length) {
                    $('.dropdown_box').fadeOut(300);
                    $('.region_list').hide();
                } else if (!$(e.target).is('.search_region')) {
                    // clicked inside but not on search field
                    $('.region_list').slideUp(200);
                }
            });

            // Search filter functionality (independent per box)
            $('.filter_form_wrap .search_region').on('keyup', function () {
                let value = $(this).val().toLowerCase();
                let $wrap = $(this).closest('.filter_form_wrap');
                $wrap.find('.region_list li').filter(function () {
                    $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
                });
            });

            // Selecting a region (independent)
            $('.filter_form_wrap .region_list li').on('click', function () {
                let $wrap = $(this).closest('.filter_form_wrap');
                let selectedText = $(this).find('.location_name').text();
                $wrap.find('.region_input').val(selectedText);
                $wrap.find('.dropdown_box').fadeOut(200);
            });

        });



        // mySwiper
        new Swiper(".mySwiper", {
            spaceBetween: 30,
            navigation: {
                nextEl: ".swiper-button-ne",
                prevEl: ".swiper-button-pr",
            },
            pagination: {
                el: ".swiper-pagination",
                clickable: true,
            },
        });

        // metropolitan_slider
        new Swiper(".metropolitan_slider", {
            spaceBetween: 10,
            pagination: {
                el: ".swiper-pagination",
                clickable: true,
            },
        });

    });



})(jQuery);