/**
 * Havenlytics AJAX Main Controller 
 * 
 * @package     Havenlytics
 * @version     2.0.4
 */

(function($) {
    'use strict';

    class HavenlyticsAJAX {
        constructor() {
            this.ajaxUrl = window.hvnly_PROPERTY_ajax?.ajax_url || window.ajaxurl;
            this.nonce = window.hvnly_PROPERTY_ajax?.nonce || '';
            this.currentPage = parseInt(window.hvnly_PROPERTY_ajax?.current_page) || 1;
            this.maxPages = parseInt(window.hvnly_PROPERTY_ajax?.max_pages) || 1;
            this.isLoading = false;
            
            //  Use custom properties per page from settings
            // First try to get from PHP localized data, then fallback to 12
            this.postsPerPage = parseInt(window.hvnly_PROPERTY_ajax?.properties_per_page) || 
                                parseInt(window.hvnly_PROPERTY_ajax?.per_page) || 
                                12;
            
            // Detect pagination type from DOM
            this.paginationType = this.detectPaginationType();
            
            //  Changed from debug_mode to debug to match PHP
            this.hvnly_debug_mode = window.hvnly_PROPERTY_ajax?.debug === '1' || false;
            
            this.modules = {};
            this.initModules();
            this.init();
            
            // Log the per page value for debugging
            // this.hvnly_log('Havenlytics: Properties per page set to:', this.postsPerPage);
        }
        
        // Debug logging helper
        hvnly_log() {
            // if (this.hvnly_debug_mode && console && console.log) {
            //     console.log.apply(console, arguments);
            // }
        }
        
        // Detect pagination type
        detectPaginationType() {
            if ($('#hvnly-load-more').length && $('#hvnly-load-more').is(':visible')) {
                // this.hvnly_log('Havenlytics: Detected Load More pagination');
                return 'load-more';
            } else if ($('#hvnly-property-pagination').length && $('#hvnly-property-pagination').is(':visible')) {
                // this.hvnly_log('Havenlytics: Detected Traditional pagination');
                return 'traditional';
            }
            return 'load-more';
        }
        
        initModules() {
            this.modules.utils = new HavenlyticsUtils(this);
            this.modules.ui = new HavenlyticsUI(this);
            this.modules.url = new HavenlyticsURL(this);
            this.modules.pagination = new HavenlyticsPagination(this);
            this.modules.filters = new HavenlyticsFilters(this);
            this.modules.search = new HavenlyticsSearch(this);
        }
        
        init() {
            // this.hvnly_log('Havenlytics: Initializing with pagination type:', this.paginationType);
            // this.hvnly_log('Havenlytics: Posts per page:', this.postsPerPage);
            
            Object.values(this.modules).forEach(module => {
                if (typeof module.init === 'function') {
                    module.init();
                }
            });

            this.setDefaultActiveView();
        }
        
        setDefaultActiveView() {
            const urlParams = new URLSearchParams(window.location.search);
            const urlViewType = urlParams.get('hvnly_view_type') || urlParams.get('view_type'); // Backward compatibility
            const defaultViewType = urlViewType || 'grid';
            
            $(`.hvnly-property-view-btn[data-view="${defaultViewType}"]`).addClass('active');
            $('#hvnly-view-type-input').val(defaultViewType);
        }
        
        performAjaxSearch() {
            if (this.isLoading) return;
            
            if (this.modules.search && !this.modules.search.isLoadMore) {
                this.modules.search.isLoadMore = false;
            }
            
            this.modules.search.performAjaxSearch();
        }
        
        handleFilterChange() {
            this.currentPage = 1;
            if (this.modules.search) {
                this.modules.search.isLoadMore = false;
            }
            this.performAjaxSearch();
        }
        
        handleSearch() {
            this.currentPage = 1;
            if (this.modules.search) {
                this.modules.search.isLoadMore = false;
            }
            this.performAjaxSearch();
        }
        
        // FIX: ADDED MISSING getFormData METHOD
        getFormData() {
            if (this.modules.utils && typeof this.modules.utils.getFormData === 'function') {
                return this.modules.utils.getFormData();
            }
            return {};
        }
        
        reinitializeFrontend() {
            setTimeout(() => {
                // Safe check with multiple method name possibilities
                if (window.havenlyticsFrontend) {
                    // Try different possible method names for gallery carousels
                    if (typeof window.havenlyticsFrontend.initPropertyGalleryCarousels === 'function') {
                        window.havenlyticsFrontend.initPropertyGalleryCarousels();
                    } else if (typeof window.havenlyticsFrontend.hvnly_initGalleryCarousels === 'function') {
                        window.havenlyticsFrontend.hvnly_initGalleryCarousels();
                    } else if (typeof window.havenlyticsFrontend.initCarousels === 'function') {
                        window.havenlyticsFrontend.initCarousels();
                    }
                    
                    // Try different possible method names for favorite buttons
                    if (typeof window.havenlyticsFrontend.initFavoriteButtons === 'function') {
                        window.havenlyticsFrontend.initFavoriteButtons();
                    } else if (typeof window.havenlyticsFrontend.hvnly_initFavoriteButtons === 'function') {
                        window.havenlyticsFrontend.hvnly_initFavoriteButtons();
                    }
                    
                    // Try different possible method names for multi-select dropdowns
                    if (typeof window.havenlyticsFrontend.initMultiSelectDropdowns === 'function') {
                        window.havenlyticsFrontend.initMultiSelectDropdowns();
                    } else if (typeof window.havenlyticsFrontend.hvnly_initMultiSelectDropdowns === 'function') {
                        window.havenlyticsFrontend.hvnly_initMultiSelectDropdowns();
                    }
                    
                    // Try different possible method names for checkboxes
                    if (typeof window.havenlyticsFrontend.initCheckboxes === 'function') {
                        window.havenlyticsFrontend.initCheckboxes();
                    } else if (typeof window.havenlyticsFrontend.hvnly_initCheckboxes === 'function') {
                        window.havenlyticsFrontend.hvnly_initCheckboxes();
                    }
                    
                    // Generic fallback - try to call any init method
                    if (typeof window.havenlyticsFrontend.hvnly_reinitialize === 'function') {
                        window.havenlyticsFrontend.hvnly_reinitialize();
                    }
                }
                
                // Trigger custom event for other plugins to hook into
                $(document).trigger('hvnly_ajax_reinitialize_complete');
                
            }, 300);
        }
        
        // New method to reset all filters
        hvnly_resetFilters() {
            this.currentPage = 1;
            if (this.modules.search) {
                this.modules.search.isLoadMore = false;
            }
            
            // Clear filter inputs if filters module exists
            if (this.modules.filters && typeof this.modules.filters.hvnly_resetFilters === 'function') {
                this.modules.filters.hvnly_resetFilters();
            } else {
                // Fallback: reset common filter elements
                $('.hvnly-filter-input, .hvnly-filter-select, input.hvnly-filter').val('');
                $('.hvnly-filter-checkbox').prop('checked', false);
            }
            
            this.performAjaxSearch();
        }
        
        // New method to get current state
        hvnly_getCurrentState() {
            return {
                currentPage: this.currentPage,
                maxPages: this.maxPages,
                paginationType: this.paginationType,
                isLoading: this.isLoading,
                postsPerPage: this.postsPerPage
            };
        }
    }

    $(document).ready(function() {
        // Initialize main AJAX controller
        window.havenlyticsAJAX = new HavenlyticsAJAX();
        
        // Handle browser back/forward buttons
        window.addEventListener('popstate', function(event) {
            if (event.state && event.state.hvnly_path) {
                window.location.href = event.state.hvnly_path;
            }
        });
        
        // Listen for filter reset events
        $(document).on('hvnly_reset_filters', function() {
            if (window.havenlyticsAJAX && typeof window.havenlyticsAJAX.hvnly_resetFilters === 'function') {
                window.havenlyticsAJAX.hvnly_resetFilters();
            }
        });
    });

})(jQuery);