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

(function($) {
    'use strict';

    class HavenlyticsPagination {
        constructor(main) {
            this.main = main;
            // Track cumulative loaded count separately
            this.cumulativeLoadedCount = 0;
            // Track pagination type
            this.paginationType = 'load-more';
        }
        
        init() {
            this.bindPaginationEvents();
            // Initialize cumulative count from DOM on page load
            this.initCumulativeCount();
            // Detect which pagination type is present
            this.detectPaginationType();
        }
        
        // Detect which pagination type is active
        detectPaginationType() {
            if ($('#hvnly-load-more').length && $('#hvnly-load-more').is(':visible')) {
                this.paginationType = 'load-more';
                // console.log('Havenlytics: Using Load More pagination');
            } else if ($('#hvnly-property-pagination').length && $('#hvnly-property-pagination').is(':visible')) {
                this.paginationType = 'traditional';
                // console.log('Havenlytics: Using Traditional pagination');
            }
        }
        
        // Initialize cumulative count
        initCumulativeCount() {
            const loadedCount = $('#loadedCount');
            if (loadedCount.length) {
                this.cumulativeLoadedCount = parseInt(loadedCount.text()) || 0;
                // console.log('Havenlytics: Initial loaded count =', this.cumulativeLoadedCount);
            }
        }
        
        bindPaginationEvents() {
            const self = this;
            
            // Load more button click
            $(document).on('click', '#hvnlyLoadMorePropertyBtn', function(e) {
                e.preventDefault();
                // console.log('Havenlytics: Load more clicked');
                self.loadMore();
            });
            
            // Traditional pagination item click
            $(document).on('click', '.hvnly-property-pagination-item', function(e) {
                e.preventDefault();
                if ($(this).hasClass('active') || $(this).hasClass('dots')) return;
                
                const page = $(this).data('page');
                // console.log('Havenlytics: Pagination item clicked - page', page);
                
                if (page) {
                    if (self.main.modules.search) {
                        self.main.modules.search.isLoadMore = false;
                    }
                    self.main.currentPage = parseInt(page);
                    self.main.performAjaxSearch();
                }
            });
        }
        
        loadMore() {
            if (this.main.isLoading || this.main.currentPage >= this.main.maxPages) {
                // console.log('Havenlytics: Cannot load more - isLoading:', this.main.isLoading, 'currentPage:', this.main.currentPage, 'maxPages:', this.main.maxPages);
                return;
            }
            
            if (this.main.modules.search) {
                this.main.modules.search.isLoadMore = true;
            }
            
            this.main.currentPage++;
            // console.log('Havenlytics: Loading more - new page:', this.main.currentPage);
            this.main.performAjaxSearch();
        }
        
        updatePaginationDisplay(data) {
            // console.log('Havenlytics: Updating pagination display', data);
            
            const paginationContainer = $('#hvnly-property-pagination');
            const loadMoreContainer = $('#hvnly-load-more');
            
            this.main.maxPages = data.max_pages || 1;
            this.main.currentPage = data.current_page || 1;
            
            // Update traditional pagination if it exists
            if (paginationContainer.length) {
                const shouldShowPagination = this.shouldShowPagination(data);
                
                if (shouldShowPagination && data.pagination_html) {
                    // console.log('Havenlytics: Updating traditional pagination HTML');
                    paginationContainer.html(data.pagination_html);
                    paginationContainer.show();
                } else if (paginationContainer.length) {
                    paginationContainer.hide();
                }
            }
            
            // Update load more section if it exists
            if (loadMoreContainer.length) {
                this.updateLoadMoreSection(data);
            }
            
            // Always update counts regardless of which pagination type is visible
            this.updateCounts(data);
        }
        
        shouldShowPagination(data) {
            const foundPosts = data.found_posts || 0;
            const maxPages = data.max_pages || 1;
            const currentPostCount = data.post_count || 0;
            
            if (maxPages <= 1) {
                return false;
            }
            
            if (foundPosts <= this.main.postsPerPage) {
                return false;
            }
            
            if (this.main.currentPage === 1 && currentPostCount === this.main.postsPerPage && foundPosts === this.main.postsPerPage) {
                return false;
            }
            
            return true;
        }
        
        updateLoadMoreSection(data) {
            const loadMoreContainer = $('#hvnly-load-more');
            if (!loadMoreContainer.length) return;

            this.main.maxPages = data.max_pages || 1;
            this.main.currentPage = data.current_page || 1;
            
            const shouldShowLoadMore = this.shouldShowLoadMore(data);
            
            if (shouldShowLoadMore) {
                loadMoreContainer.show();
            } else {
                loadMoreContainer.hide();
            }
        }
        
        shouldShowLoadMore(data) {
            if (this.main.currentPage >= this.main.maxPages) {
                return false;
            }
            
            return this.shouldShowPagination(data);
        }
        
        updateCounts(data) {
            const loadedCount = $('#loadedCount');
            const totalCount = $('#totalCount');
            
            // Always update loaded count
            if (loadedCount.length && data.found_posts) {
                let cumulativeCount;
                
                if (this.main.modules.search && this.main.modules.search.isLoadMore) {
                    // For load more, add to existing cumulative count
                    cumulativeCount = this.cumulativeLoadedCount + (data.post_count || 0);
                    // console.log('Havenlytics: Load more - adding', data.post_count, 'to', this.cumulativeLoadedCount, '=', 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 pagination - page', this.main.currentPage, '*', this.main.postsPerPage, '=', cumulativeCount);
                }
                
                // Ensure we don't exceed total found posts
                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);
            }
        }
    }

    window.HavenlyticsPagination = HavenlyticsPagination;

})(jQuery);