/**
 * Frontend JavaScript for Zluck Ajax Posts Filter
 *
 * @package Zluck_Ajax_Posts_Filter_Elementor
 */

(function($) {
	'use strict';

	/**
	 * Zluck Ajax Posts Filter
	 */
	var AAPFFrontend = {
		init: function() {
			this.bindEvents();
			this.initInfiniteScroll();
			this.initURLSync();
		},

		bindEvents: function() {
			var self = this;

			// Filter item click - handle both click and keyboard events for accessibility
			$(document).on('click', '.aapf-filter-item', function(e) {
				e.preventDefault();
				e.stopPropagation(); // Prevent Elementor editor from handling the click
				self.handleFilterClick($(this));
			});
			
			// Handle keyboard events for accessibility
			$(document).on('keydown', '.aapf-filter-item', function(e) {
				if (e.key === 'Enter' || e.key === ' ') {
					e.preventDefault();
					e.stopPropagation();
					self.handleFilterClick($(this));
				}
			});

			// Load more button
			$(document).on('click', '.aapf-load-more-btn', function(e) {
				e.preventDefault();
				self.handleLoadMore($(this));
			});

			// Pagination numbers click - handle both click and keyboard events
			$(document).on('click', '.aapf-pagination-link', function(e) {
				e.preventDefault();
				e.stopPropagation(); // Prevent Elementor editor from handling the click
				self.handlePaginationClick($(this));
			});
			
			// Handle keyboard events for pagination
			$(document).on('keydown', '.aapf-pagination-link', function(e) {
				if (e.key === 'Enter' || e.key === ' ') {
					e.preventDefault();
					e.stopPropagation();
					self.handlePaginationClick($(this));
				}
			});
		},

		handleFilterClick: function($item) {
			var $filter = $item.closest('.aapf-filter');
			
			// Find posts wrapper - handle both regular and vertical layouts
			var $wrapper = $filter.next('.aapf-posts-wrapper');
			if (!$wrapper.length) {
				// For vertical layout, look for posts-content-wrapper first
				var $contentWrapper = $filter.next('.aapf-posts-content-wrapper');
				if ($contentWrapper.length) {
					$wrapper = $contentWrapper.find('.aapf-posts-wrapper').first();
				}
			}
			
			// Fallback: find by widget ID
			if (!$wrapper.length) {
				var widgetId = $filter.data('widget-id');
				if (widgetId) {
					// Sanitize widget ID to prevent XSS
					var sanitizedWidgetId = String(widgetId).replace(/[^a-z0-9_-]/gi, '');
					$wrapper = $('.aapf-posts-wrapper[data-widget-id="' + sanitizedWidgetId + '"]');
				}
			}
			
			if (!$wrapper.length) {
				// Silently fail - element may not be present
				return;
			}
			
			var widgetId = $filter.data('widget-id');
			var taxonomy = $filter.data('taxonomy');
			var isMultiselect = $filter.hasClass('aapf-filter-multiselect');
			var termId = $item.data('term-id');

			// Update active state
			if (!isMultiselect) {
				$filter.find('.aapf-filter-item').removeClass('active');
				$item.addClass('active');
			} else {
				$item.toggleClass('active');
			}

			// Get selected terms - convert to integers
			var selectedTerms = [];
			if (isMultiselect) {
				$filter.find('.aapf-filter-item.active').each(function() {
					var id = $(this).data('term-id');
					if (id) {
						selectedTerms.push(parseInt(id, 10));
					}
				});
			} else {
				if (termId) {
					selectedTerms.push(parseInt(termId, 10));
				}
			}

			// Get settings - parse from JSON if it's a string
			var settings = {};
			var settingsData = $wrapper.attr('data-settings');
			if (settingsData) {
				try {
					settings = JSON.parse(settingsData);
				} catch (e) {
					// Fallback to data attribute
					settings = $wrapper.data('settings') || {};
				}
			} else {
				settings = $wrapper.data('settings') || {};
			}

			// Filter posts
			this.filterPosts($wrapper, settings, selectedTerms, 1);

			// Update URL if enabled
			if (settings.filter_url_sync === 'yes') {
				this.updateURL(taxonomy, selectedTerms);
			}
		},

		filterPosts: function($wrapper, settings, selectedTerms, paged) {
			var self = this;

			// Show loading state
			$wrapper.addClass('aapf-loading');

			// Prepare data
			var data = {
				action: 'aapf_filter_posts',
				nonce: aapfAjax.nonce,
				settings: settings,
				terms: selectedTerms,
				paged: paged
			};

			// AJAX request
			$.ajax({
				url: aapfAjax.ajaxurl,
				type: 'POST',
				data: data,
				success: function(response) {
					if (response.success) {
						// Store widget ID for reference
						var widgetId = $wrapper.data('widget-id');
						
						// Update posts
						$wrapper.html(response.data.posts);
						
						// Re-apply widget ID and settings to maintain data attributes
						if (widgetId) {
							$wrapper.attr('data-widget-id', widgetId);
						}
						$wrapper.attr('data-settings', JSON.stringify(settings));

						// Update pagination - find it relative to wrapper
						var $pagination = $wrapper.next('.aapf-pagination');
						
						// For vertical layout, pagination might be in content wrapper
						if (!$pagination.length) {
							var $contentWrapper = $wrapper.closest('.aapf-posts-content-wrapper');
							if ($contentWrapper.length) {
								$pagination = $contentWrapper.find('.aapf-pagination').first();
							}
						}
						
						if ($pagination.length && response.data.pagination) {
							$pagination.html(response.data.pagination);
						} else if (!$pagination.length && response.data.pagination) {
							// Create pagination if it doesn't exist
							// For vertical layout, add to content wrapper
							var $contentWrapper = $wrapper.closest('.aapf-posts-content-wrapper');
							if ($contentWrapper.length) {
								$contentWrapper.append(response.data.pagination);
							} else {
								$wrapper.after(response.data.pagination);
							}
						} else if ($pagination.length && !response.data.pagination) {
							// Remove pagination if no longer needed
							$pagination.remove();
						}

						// Reinitialize infinite scroll if needed
						if (settings.pagination === 'infinite') {
							self.initInfiniteScroll();
						}

						// Scroll to top (only if wrapper exists and is visible)
						if ($wrapper.length) {
							var offset = $wrapper.offset();
							if (offset && offset.top !== undefined) {
								$('html, body').animate({
									scrollTop: offset.top - 100
								}, 500);
							}
						}
					} else {
						// Show user-friendly error message
						if (response.data && response.data.message) {
							$wrapper.html('<div class="aapf-error">' + $('<div>').text(response.data.message).html() + '</div>');
						}
					}
				},
				error: function(xhr, status, error) {
					// Show user-friendly error message
					var errorMsg = aapfAjax.errorMessage || 'An error occurred. Please try again.';
					$wrapper.html('<div class="aapf-error">' + $('<div>').text(errorMsg).html() + '</div>');
				},
				complete: function() {
					$wrapper.removeClass('aapf-loading');
				}
			});
		},

		handlePaginationClick: function($link) {
			var self = this;
			var $pagination = $link.closest('.aapf-pagination');
			
			// Find the wrapper - it should be before the pagination
			var $wrapper = $pagination.prev('.aapf-posts-wrapper');
			
			// If not found, try finding by widget ID from pagination's parent
			if (!$wrapper.length) {
				var $widgetContainer = $pagination.closest('.elementor-widget-aapf_posts');
				if ($widgetContainer.length) {
					$wrapper = $widgetContainer.find('.aapf-posts-wrapper').first();
				}
			}
			
			// If still not found, try to find by data-widget-id if pagination has it
			if (!$wrapper.length) {
				var widgetId = $pagination.data('widget-id');
				if (widgetId) {
					// Sanitize widget ID to prevent XSS
					var sanitizedWidgetId = String(widgetId).replace(/[^a-z0-9_-]/gi, '');
					$wrapper = $('.aapf-posts-wrapper[data-widget-id="' + sanitizedWidgetId + '"]');
				}
			}
			
			// Last resort: find any wrapper on the page
			if (!$wrapper.length) {
				$wrapper = $('.aapf-posts-wrapper').first();
			}
			
			if (!$wrapper.length) {
				// Silently fail - element may not be present
				return;
			}
			
			var $filter = $wrapper.prev('.aapf-filter');
			
			// Get settings from data attribute or parse from JSON
			var settings = {};
			var settingsData = $wrapper.attr('data-settings');
			if (settingsData) {
				try {
					settings = JSON.parse(settingsData);
				} catch (e) {
					// Fallback to data attribute
					settings = $wrapper.data('settings') || {};
				}
			} else {
				settings = $wrapper.data('settings') || {};
			}
			
			// Get page number from data attribute
			var page = parseInt($link.data('page'));
			
			// Validate page number
			if (!page || isNaN(page) || page < 1) {
				// Invalid page, don't proceed
				return;
			}

			// Get selected terms
			var selectedTerms = [];
			if ($filter.length) {
				$filter.find('.aapf-filter-item.active').each(function() {
					var id = $(this).data('term-id');
					if (id) {
						selectedTerms.push(id);
					}
				});
			}

			// Filter posts with new page
			this.filterPosts($wrapper, settings, selectedTerms, page);
		},

		handleLoadMore: function($button) {
			var self = this;
			var $wrapper = $button.closest('.aapf-posts-wrapper').prev('.aapf-posts-wrapper');
			if (!$wrapper.length) {
				$wrapper = $button.closest('.aapf-pagination').prev('.aapf-posts-wrapper');
			}

			var $filter = $wrapper.prev('.aapf-filter');
			var settings = $wrapper.data('settings') || {};
			var currentPage = parseInt($button.data('page')) || 1;
			var maxPages = parseInt($button.data('max-pages')) || 1;
			var nextPage = currentPage + 1;

			// Get selected terms
			var selectedTerms = [];
			if ($filter.length) {
				$filter.find('.aapf-filter-item.active').each(function() {
					var id = $(this).data('term-id');
					if (id) {
						selectedTerms.push(id);
					}
				});
			}

			// Disable button
			$button.prop('disabled', true).text('Loading...');

			// Load more posts
			var data = {
				action: 'aapf_filter_posts',
				nonce: aapfAjax.nonce,
				settings: settings,
				terms: selectedTerms,
				paged: nextPage
			};

			$.ajax({
				url: aapfAjax.ajaxurl,
				type: 'POST',
				data: data,
				success: function(response) {
					if (response.success) {
						// Append posts
						$wrapper.append(response.data.posts);

						// Update button
						if (nextPage < maxPages) {
							$button.data('page', nextPage).prop('disabled', false).text($button.data('original-text') || 'Load More');
						} else {
							$button.remove();
						}
					}
				},
				error: function(xhr, status, error) {
					// Re-enable button on error
					$button.prop('disabled', false).text($button.data('original-text') || 'Load More');
				}
			});
		},

		initInfiniteScroll: function() {
			var self = this;
			var $infinitePagination = $('.aapf-pagination-infinite');

			if (!$infinitePagination.length) {
				return;
			}

			// Remove existing scroll handler
			$(window).off('scroll.aapf-infinite');

			// Add scroll handler
			$(window).on('scroll.aapf-infinite', function() {
				$infinitePagination.each(function() {
					var $pagination = $(this);
					var currentPage = parseInt($pagination.data('page')) || 1;
					var maxPages = parseInt($pagination.data('max-pages')) || 1;

					if (currentPage >= maxPages) {
						return;
					}

					var elementTop = $pagination.offset().top;
					var windowBottom = $(window).scrollTop() + $(window).height();

					if (windowBottom >= elementTop - 200) {
						// Load next page
						var $wrapper = $pagination.prev('.aapf-posts-wrapper');
						var $filter = $wrapper.prev('.aapf-filter');
						var settings = $wrapper.data('settings') || {};
						var nextPage = currentPage + 1;

						// Get selected terms
						var selectedTerms = [];
						if ($filter.length) {
							$filter.find('.aapf-filter-item.active').each(function() {
								var id = $(this).data('term-id');
								if (id) {
									selectedTerms.push(id);
								}
							});
						}

						// Update page
						$pagination.data('page', nextPage);

						// Load posts
						var data = {
							action: 'aapf_filter_posts',
							nonce: aapfAjax.nonce,
							settings: settings,
							terms: selectedTerms,
							paged: nextPage
						};

						$.ajax({
							url: aapfAjax.ajaxurl,
							type: 'POST',
							data: data,
							success: function(response) {
								if (response.success) {
									$wrapper.append(response.data.posts);

									if (nextPage >= maxPages) {
										$pagination.remove();
									}
								}
							}
						});
					}
				});
			});
		},

		initURLSync: function() {
			// Check URL parameters on load
			var urlParams = new URLSearchParams(window.location.search);
			var taxonomy = urlParams.get('taxonomy');
			var terms = urlParams.get('terms');

			if (taxonomy && terms) {
				var termIds = terms.split(',').map(function(id) {
					return parseInt(id);
				});

			// Find matching filter and activate - sanitize taxonomy to prevent XSS
			var sanitizedTaxonomy = taxonomy.replace(/[^a-z0-9_-]/gi, '');
			$('.aapf-filter[data-taxonomy="' + sanitizedTaxonomy + '"]').each(function() {
					var $filter = $(this);
					var $wrapper = $filter.next('.aapf-posts-wrapper');
					var settings = $wrapper.data('settings') || {};

				// Activate terms - sanitize termId to prevent XSS
				termIds.forEach(function(termId) {
					var sanitizedTermId = parseInt(termId, 10);
					if (!isNaN(sanitizedTermId) && sanitizedTermId > 0) {
						$filter.find('.aapf-filter-item[data-term-id="' + sanitizedTermId + '"]').addClass('active');
					}
				});

					// Filter posts
					AAPFFrontend.filterPosts($wrapper, settings, termIds, 1);
				});
			} else {
				// If no URL params, check if "All" is disabled and select first term
				$('.aapf-filter').each(function() {
					var $filter = $(this);
					var $wrapper = $filter.next('.aapf-posts-wrapper');
					if (!$wrapper.length) {
						// For vertical layout, look for posts-content-wrapper first
						var $contentWrapper = $filter.next('.aapf-posts-content-wrapper');
						if ($contentWrapper.length) {
							$wrapper = $contentWrapper.find('.aapf-posts-wrapper').first();
						}
					}
					
					if (!$wrapper.length) {
						return;
					}
					
					var settings = $wrapper.data('settings') || {};
					var settingsData = $wrapper.attr('data-settings');
					if (settingsData) {
						try {
							settings = JSON.parse(settingsData);
						} catch (e) {
							settings = $wrapper.data('settings') || {};
						}
					}
					
					// Check if "All" is disabled
					var showAll = settings.filter_show_all === 'yes';
					
					// If "All" is disabled and no active filter item exists, activate first term
					if (!showAll) {
						var $activeItem = $filter.find('.aapf-filter-item.active');
						if (!$activeItem.length || $activeItem.data('term-id') === '') {
							var $firstTerm = $filter.find('.aapf-filter-item[data-term-id]:first');
							if ($firstTerm.length) {
								$firstTerm.addClass('active');
							}
						}
					}
				});
			}
		},

		updateURL: function(taxonomy, terms) {
			var url = new URL(window.location.href);
			
			if (terms.length > 0) {
				url.searchParams.set('taxonomy', taxonomy);
				url.searchParams.set('terms', terms.join(','));
			} else {
				url.searchParams.delete('taxonomy');
				url.searchParams.delete('terms');
			}

			window.history.pushState({}, '', url);
		}
	};

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

	// Store original load more text
	$(document).on('mouseenter', '.aapf-load-more-btn', function() {
		if (!$(this).data('original-text')) {
			$(this).data('original-text', $(this).text());
		}
	});

})(jQuery);

