/**
 * Havenlytics AJAX Search Module 
 * 
 * @package     Havenlytics
 * @version     2.0.0
 */

(function($) {
    'use strict';

    class HavenlyticsSearch {
        constructor(main) {
            this.main = main;
            this.isLoadMore = false;
            // Track cumulative loaded count separately
            this.cumulativeLoadedCount = 0;
            // Track pagination type
            this.paginationType = 'load-more';
        }
        
        init() {
            this.utils = this.main.modules.utils;
            this.ui = this.main.modules.ui;
            this.bindSearchEvents();
            // Initialize cumulative count from DOM on page load
            this.initCumulativeCount();
            // Detect pagination type
            this.detectPaginationType();
        }
        
        // Detect which pagination type is present
        detectPaginationType() {
            if ($('#hvnly-load-more').length && $('#hvnly-load-more').is(':visible')) {
                this.paginationType = 'load-more';
            } else if ($('#hvnly-property-pagination').length && $('#hvnly-property-pagination').is(':visible')) {
                this.paginationType = 'traditional';
            }
        }
        
        // Initialize cumulative count
        initCumulativeCount() {
            const loadedCount = $('#loadedCount');
            if (loadedCount.length) {
                this.cumulativeLoadedCount = parseInt(loadedCount.text()) || 0;
            }
        }
        
        bindSearchEvents() {
            const self = this;
            
            $(document).on('submit', '#hvnly-property-search-form__box', function(e) {
                e.preventDefault();
                // console.log('Havenlytics: Search form submitted');
                self.main.handleSearch();
            });
            
            $(document).on('input', '.hvnly-ajax-search input[name="address_keyword"]', 
                this.utils.debounce(function(e) {
                    const searchValue = $(this).val();
                    const searchTerm = searchValue ? searchValue.trim() : '';
                    
                    // console.log('Havenlytics: Search input -', searchTerm);
                    
                    self.main.currentPage = 1;
                    self.isLoadMore = false;
                    self.main.performAjaxSearch();
                }, 300)
            );
        }
        
        performAjaxSearch() {
            if (this.main.isLoading) return;
            
            this.main.isLoading = true;
            this.ui.showLoading();
            
            const data = this.utils.getFormData();
            
            // console.log('Havenlytics: Performing AJAX search - page:', this.main.currentPage, 'isLoadMore:', this.isLoadMore);
            
            $.ajax({
                url: this.main.ajaxUrl,
                type: 'POST',
                data: data,
                success: (response) => {
                    // console.log('Havenlytics: AJAX success', response);
                    if (response.success) {
                        this.handleSearchSuccess(response.data);
                    } else {
                        this.ui.showError('Failed to load properties: ' + (response.data || 'Unknown error'));
                    }
                },
                error: (xhr, status, error) => {
                    // console.error('Havenlytics: AJAX error', error);
                    this.ui.showError('An error occurred while loading properties. Please try again.');
                },
                complete: () => {
                    this.main.isLoading = false;
                    this.ui.hideLoading();
                    if (this.isLoadMore) {
                        this.isLoadMore = false;
                    }
                }
            });
        }
        
        handleSearchSuccess(data) {
            // console.log('Havenlytics: Handling search success', data);
            
            this.updatePropertyGrid(data);
            
            if (this.main.modules.pagination && typeof this.main.modules.pagination.updatePaginationDisplay === 'function') {
                this.main.modules.pagination.updatePaginationDisplay(data);
            } else {
                this.updatePagination(data);
                this.updateLoadMoreSection(data);
            }
            
            this.updateResultsCount(data);
            this.updateCounts(data);
            this.main.modules.url.updateBrowserUrl();
            this.reinitializeFrontend();
            $(document).trigger('hvnly-properties-updated', [data]);
        }
        
        updatePropertyGrid(data) {
            const propertyGrid = $('#hvnly-property-grid');
            if (propertyGrid.length && data.html) {
                if (this.isLoadMore && this.main.currentPage > 1) {
                    // console.log('Havenlytics: Appending properties for load more');
                    propertyGrid.append(data.html);
                } else {
                    // console.log('Havenlytics: Replacing properties for new search/page');
                    propertyGrid.html(data.html);
                }
                
                this.updateGridDisplayStyle();
            }
        }

        updateGridDisplayStyle() {
            const propertyGrid = $('#hvnly-property-grid');
            const activeView = $('.hvnly-property-view-btn.active');
            
            if (activeView.length && propertyGrid.length) {
                const viewType = activeView.data('view');
                
                propertyGrid.removeAttr('style');
                
                if (viewType === 'grid') {
                    propertyGrid.css({
                        'display': 'grid',
                        'gridTemplateColumns': 'repeat(auto-fill, minmax(350px, 1fr))',
                        'gap': '20px'
                    });
                } else if (viewType === 'list') {
                    propertyGrid.css({
                        'display': 'flex',
                        'flexDirection': 'column',
                        'gap': '20px'
                    });
                } else if (viewType === 'map') {
                    propertyGrid.css('display', 'none');
                }
            }
        }
        
        updatePagination(data) {
            const paginationContainer = $('#hvnly-property-pagination');
            if (paginationContainer.length && data.pagination_html) {
                // console.log('Havenlytics: Updating pagination HTML');
                paginationContainer.html(data.pagination_html);
            }
        }
        
        updateResultsCount(data) {
            const resultsCount = $('#hvnly-results-count');
            if (resultsCount.length && data.results_count_html) {
                resultsCount.html(data.results_count_html);
            }
        }
        
        updateLoadMoreSection(data) {
            const loadMoreContainer = $('#hvnly-load-more');
            if (!loadMoreContainer.length) return;

            this.main.maxPages = data.max_pages;
            this.main.currentPage = data.current_page;

            if (data.current_page >= data.max_pages) {
                loadMoreContainer.hide();
            } else {
                loadMoreContainer.show();
            }
        }
        
        updateCounts(data) {
            const loadedCount = $('#loadedCount');
            const totalCount = $('#totalCount');
            
            // Always update loaded count
            if (loadedCount.length && data.found_posts) {
                let cumulativeCount;
                
                if (this.isLoadMore) {
                    // For load more, add to existing cumulative count
                    cumulativeCount = this.cumulativeLoadedCount + (data.post_count || 0);
                    // console.log('Havenlytics: Load more count update -', this.cumulativeLoadedCount, '+', data.post_count, '=', cumulativeCount);
                } else {
                    // For regular pagination or filter changes, calculate based on current page
                    cumulativeCount = Math.min(this.main.currentPage * this.main.postsPerPage, data.found_posts);
                    // console.log('Havenlytics: Regular count update - page', this.main.currentPage, '*', this.main.postsPerPage, '=', cumulativeCount);
                }
                
                // Ensure we don't exceed total
                cumulativeCount = Math.min(cumulativeCount, data.found_posts);
                
                // Update the cumulative count tracker
                this.cumulativeLoadedCount = cumulativeCount;
                
                // Update the DOM
                loadedCount.text(cumulativeCount);
            }
            
            // Always update total count
            if (totalCount.length && data.found_posts) {
                totalCount.text(data.found_posts);
            }
        }
        
        reinitializeFrontend() {
            setTimeout(() => {
                if (window.havenlyticsFrontend) {
                    window.havenlyticsFrontend.initPropertyGalleryCarousels();
                    window.havenlyticsFrontend.initFavoriteButtons();
                    window.havenlyticsFrontend.initMultiSelectDropdowns();
                    window.havenlyticsFrontend.initCheckboxes();
                }
            }, 300);
        }
    }

    window.HavenlyticsSearch = HavenlyticsSearch;

})(jQuery);