/**
 * Property Filters JavaScript
 *
 * AJAX filtering for property archive
 *
 * @package HomeProz
 */

(function($) {
    'use strict';

    var PropertyFilters = {
        // Elements
        $form: null,
        $results: null,
        $filters: null,

        // State
        isFirstLoad: true,
        isLoading: false,

        /**
         * Initialize
         */
        init: function() {
            this.$form = $('.filters-form');
            this.$results = $('#property-results');
            this.$filters = $('#property-filters');

            if (!this.$form.length || !this.$results.length) {
                return;
            }

            this.bindEvents();
            this.initFromUrl();
        },

        /**
         * Bind events
         */
        bindEvents: function() {
            var self = this;

            // Form submission (Search button)
            this.$form.on('submit', function(e) {
                e.preventDefault();
                self.filterProperties(1);
            });

            // Filter changes (auto-submit on select change)
            this.$form.find('select').on('change', function() {
                self.filterProperties(1);
            });

            // Reset button
            $('.filters-reset').on('click', function(e) {
                e.preventDefault();
                self.resetFilters();
            });

            // Pagination clicks (delegated)
            this.$results.on('click', '.pagination a', function(e) {
                e.preventDefault();
                var page = self.getPageFromUrl($(this).attr('href'));
                self.filterProperties(page);
            });

            // Handle browser back/forward
            $(window).on('popstate', function(e) {
                if (e.originalEvent.state && e.originalEvent.state.propertyFilters) {
                    self.setFormFromState(e.originalEvent.state.propertyFilters);
                    self.filterProperties(e.originalEvent.state.page || 1, false);
                }
            });
        },

        /**
         * Initialize filters from URL params
         */
        initFromUrl: function() {
            var params = new URLSearchParams(window.location.search);
            var hasFilters = false;

            // Set form values from URL
            this.$form.find('select').each(function() {
                var name = $(this).attr('name');
                if (params.has(name)) {
                    $(this).val(params.get(name));
                    hasFilters = true;
                }
            });

            // Save initial state
            if (hasFilters) {
                var state = this.getFormState();
                state.page = parseInt(params.get('paged')) || 1;
                history.replaceState({ propertyFilters: state, page: state.page }, '', window.location.href);
            }
        },

        /**
         * Filter properties via AJAX
         */
        filterProperties: function(page, updateHistory) {
            if (this.isLoading) {
                return;
            }

            updateHistory = updateHistory !== false;
            page = page || 1;

            var self = this;
            var formData = this.getFormData();
            formData.paged = page;

            // Show loading state
            this.isLoading = true;
            this.$filters.addClass('is-loading');

            // Show spinner only on first load
            if (this.isFirstLoad) {
                this.$results.html('<div class="property-results-loading"><div class="spinner"></div></div>');
            }

            $.ajax({
                url: homeprozAjax.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'homeproz_filter_properties',
                    nonce: homeprozAjax.nonce,
                    property_type: formData.property_type,
                    property_status: formData.property_status,
                    property_location: formData.property_location,
                    min_price: formData.min_price,
                    max_price: formData.max_price,
                    beds: formData.beds,
                    sort: formData.sort,
                    paged: page
                },
                success: function(response) {
                    if (response.success) {
                        self.$results.html(response.data.html);
                        self.isFirstLoad = false;

                        // Update URL
                        if (updateHistory) {
                            self.updateUrl(formData, page);
                        }

                        // Scroll to top of results on page change
                        if (page > 1) {
                            $('html, body').animate({
                                scrollTop: self.$filters.offset().top - 100
                            }, 300);
                        }
                    }
                },
                error: function() {
                    self.$results.html('<div class="no-properties"><h3>Error</h3><p>Something went wrong. Please try again.</p></div>');
                },
                complete: function() {
                    self.isLoading = false;
                    self.$filters.removeClass('is-loading');
                }
            });
        },

        /**
         * Get form data as object
         */
        getFormData: function() {
            return {
                property_type: this.$form.find('[name="property_type"]').val() || '',
                property_status: this.$form.find('[name="property_status"]').val() || '',
                property_location: this.$form.find('[name="property_location"]').val() || '',
                min_price: this.$form.find('[name="min_price"]').val() || '',
                max_price: this.$form.find('[name="max_price"]').val() || '',
                beds: this.$form.find('[name="beds"]').val() || '',
                sort: this.$form.find('[name="sort"]').val() || 'newest'
            };
        },

        /**
         * Get form state for history
         */
        getFormState: function() {
            return this.getFormData();
        },

        /**
         * Set form from state
         */
        setFormFromState: function(state) {
            for (var key in state) {
                this.$form.find('[name="' + key + '"]').val(state[key]);
            }
        },

        /**
         * Update browser URL
         */
        updateUrl: function(formData, page) {
            var url = new URL(homeprozAjax.archiveUrl);

            // Add non-empty filters to URL
            for (var key in formData) {
                if (formData[key] && formData[key] !== 'newest') {
                    url.searchParams.set(key, formData[key]);
                }
            }

            // Add page if > 1
            if (page > 1) {
                url.searchParams.set('paged', page);
            }

            var state = { propertyFilters: formData, page: page };
            history.pushState(state, '', url.toString());
        },

        /**
         * Get page number from pagination URL
         */
        getPageFromUrl: function(url) {
            var match = url.match(/[?&]paged=(\d+)/);
            return match ? parseInt(match[1]) : 1;
        },

        /**
         * Reset filters
         */
        resetFilters: function() {
            this.$form.find('select').val('');
            this.$form.find('[name="sort"]').val('newest');
            this.filterProperties(1);
        }
    };

    // Initialize on document ready
    $(function() {
        PropertyFilters.init();
    });

})(jQuery);
