jQuery(document).ready(function($) {
    var currentPage = 1;
    var keyword = '';
    var department = '';

    $(document).on("click", "#removeOptionsBtn", function() {
        var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname;
        window.location.href = newurl;
        return false;
    });

    function updateUrl(department, keyword) {
        var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?department=' + department + '&key=' + keyword;
        window.history.pushState({
            path: newurl
        }, '', newurl);
    }

    // Function to get URL parameter value by name
    function getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }

    // Function to set the selected value of a select box
    function setSelectBoxValue(selectBoxId, value) {
        $('#' + selectBoxId).val(value);
    }

    // Get department and keyword from URL
    var departmentParam = getParameterByName('department');
    var keywordParam = getParameterByName('key');

    // Set values for department select box and keyword input field if they exist
    if (departmentParam) {
        setSelectBoxValue('departments', departmentParam); // Assuming you have a select with id 'departments'
    }

    if (keywordParam) {
        $('#keyword').val(keywordParam); // Assuming you have an input with id 'keyword'
    }

    if (departmentParam || keywordParam) {
        markations_directory_filter_pagination(currentPage, keywordParam, departmentParam);
    }

    // Pagination click handler
    jQuery(document).on('click', '.property-page a.page-numbers', function(e) {
        $('.loading-buffering-img').show();
        e.preventDefault();
        
        var activePage = parseInt(jQuery('.property-page .current').text());
        
        if (jQuery(this).hasClass('prev')) {
            currentPage = activePage - 1;
        } else if (jQuery(this).hasClass('next')) {
            currentPage = activePage + 1;
        } else {
            currentPage = parseInt(jQuery(this).text());
        }
        
        markations_directory_filter_pagination(currentPage, keyword, department);

        $('html, body').animate({
            scrollTop: $('.directory_content').offset().top - 50
        }, 500);
    });

    // Department change handler
    $('#departments').on('change', function() {
        department = $(this).val();
        var keyword = $('#keyword').val();
        currentPage = 1; // Reset to the first page when department changes
        var targetElement = $(".clear-filter-btn");
        if (targetElement.is(':empty')){
            targetElement.html('<button id="removeOptionsBtn">Clear</button>');
        }
        updateUrl(department, keyword);
        markations_directory_filter_pagination(currentPage, keyword, department);
    });

    // Keyword input handler
    $('#keyword').on('input', function() {
        keyword = $(this).val().trim();
        department = $('#departments').val();
        if (keyword.length >= 3 || keyword.length === 0) { // Trigger only on 3+ chars or when cleared
            currentPage = 1; // Reset to the first page whenever the keyword changes
            var targetElement = $(".clear-filter-btn");
            if (targetElement.is(':empty')){
                targetElement.html('<button id="removeOptionsBtn">Clear</button>');
            }
            updateUrl(department, keyword);
            markations_directory_filter_pagination(currentPage, keyword, department);
        }
    });

    // Combined filter function
    function markations_directory_filter_pagination(currentPage, keyword, department) {
        const d = new Date();
        let time = d.getTime();
        $('.paginatiom_dir').html('<div class="text-center" style="width:100%;"><img src="'+MARKARIONS_DIRECTORY.image+'" alt="Loading..." class="loader-image"/></div>');
        $.ajax({
            url: MARKARIONS_DIRECTORY.ajaxurl+"?time="+time,
            type: 'POST',
            data: {
                action: 'markations_directory_load_more_posts',
                nonce: MARKARIONS_DIRECTORY.nonce,
                term: department,
                keyword: keyword,
                paged: currentPage
            },
            beforeSend: function() {
                $('.loading-buffering-img').show();
            },
            success: function(response) {
                if (response) {
                    $('.paginatiom_dir').empty();
                    $('.loading-buffering-img').hide();
                    var filterResult = JSON.parse(response);

                    $('.directory__inner').html(filterResult.data);
                    $('.property-page').html(filterResult.filter_pagination);
                    
                    $('.next').addClass('nextpostslink');
                    $('.prev').addClass('previouspostslink');
                    
                    setTimeout(function() {
                        customPopup();
                    }, 100);

                    // SVG Create
                    jQuery(function() {
                        jQuery('img.svg').each(function() {
                        var $img = jQuery(this);
                        var imgID = $img.attr('id');
                        var imgClass = $img.attr('class');
                        var imgURL = $img.attr('src');
                        jQuery.get(imgURL, function(data) {
                        var $svg = jQuery(data).find('svg');
                        if (typeof imgID !== 'undefined') {
                        $svg = $svg.attr('id', imgID);
                        }
                        if (typeof imgClass !== 'undefined') {
                        $svg = $svg.attr('class', imgClass + ' replaced-svg');
                        }
                        $svg = $svg.removeAttr('xmlns:a');
                        if (!$svg.attr('viewBox') && $svg.attr('height') && $svg.attr('width')) {
                        $svg.attr('viewBox', '0 0 ' + $svg.attr('height') + ' ' + $svg.attr('width'));
                        }
                        $img.replaceWith($svg);
                        }, 'xml');
                        });
                    });
                }
            },
            error: function(errorThrown) {
                console.log(errorThrown);
            }
        });
    }

    // Custom popup functionality
    function customPopup() {
        let $btnShowPopup = jQuery('.js-open-popup');
        let $btnClosePopup = jQuery('.js-close-popup');
        let $popup = jQuery('.js-custom-popup');
        
        $btnShowPopup.on('click', function() {
            let targetPopup = jQuery(this).attr('data-target');
            jQuery("[data-popup=" + targetPopup + "]").addClass('is-active');
        });
        
        $btnClosePopup.on('click', function() {
            jQuery(this).parents('.is-active').removeClass('is-active');
        });
        
        $popup.on('click', function(event) {
            if (!jQuery(event.target).closest('.js-custom-popup-holder').length && !jQuery(event.target).is('js-custom-popup')) {
                if ($popup.hasClass('is-active')) {
                    $popup.removeClass('is-active');
                }
            }
        });
    }

    $('.next').addClass('nextpostslink');
    $('.prev').addClass('previouspostslink');
});
