/**
 * Product Search and Modern UI Interactions
 *
 * Handles live search with debounced AJAX, dropdown rendering,
 * keyboard navigation, action menus, and per-page selector.
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/assets/js
 * @author     miniOrange
 * @since      1.0.0
 */

(function ($) {
	'use strict';

	/**
	 * Product Search Module
	 */
	const ProductSearch = {
		searchInput: null,
		searchDropdown: null,
		debounceTimer: null,
		selectedIndex: -1,
		searchResults: [],

		/**
		 * Initialize the search module
		 */
		init: function () {
			this.searchInput = $('#momcs-product-search');
			this.searchDropdown = $('#momcs-search-dropdown');

			if (!this.searchInput.length) {
				return;
			}

			this.bindEvents();
		},

		/**
		 * Bind event handlers
		 */
		bindEvents: function () {
			const self = this;

			// Input events
			this.searchInput.on('input', function () {
				self.handleInput($(this).val());
			});

			this.searchInput.on('focus', function () {
				if (self.searchResults.length > 0) {
					self.showDropdown();
				}
			});

			// Keyboard navigation
			this.searchInput.on('keydown', function (e) {
				self.handleKeydown(e);
			});

			// Click outside to close
			$(document).on('click', function (e) {
				if (!$(e.target).closest('.momcs-product-search-wrapper').length) {
					self.hideDropdown();
				}
			});

			// Result item click
			this.searchDropdown.on('click', '.momcs-search-result-item', function () {
				const productId = $(this).data('product-id');
				const editLink = $(this).data('edit-link');
				if (editLink) {
					window.open(editLink, '_blank');
				}
				self.hideDropdown();
				self.searchInput.val('');
			});
		},

		/**
		 * Handle input changes with debounce
		 *
		 * @param {string} query Search query
		 */
		handleInput: function (query) {
			const self = this;

			clearTimeout(this.debounceTimer);

			if (query.length < 2) {
				this.hideDropdown();
				this.searchResults = [];
				return;
			}

			this.debounceTimer = setTimeout(function () {
				self.performSearch(query);
			}, 300);
		},

		/**
		 * Perform AJAX search
		 *
		 * @param {string} query Search query
		 */
		performSearch: function (query) {
			const self = this;

			// Show loading state
			this.searchDropdown.html(
				'<div class="momcs-search-loading"><div class="momcs-search-loading-spinner"></div></div>'
			);
			this.showDropdown();

			$.ajax({
				url: momcs_sync.ajax_url,
				type: 'POST',
				data: {
					action: 'momcs_search_products',
					nonce: momcs_sync.nonce,
					query: query,
				},
				success: function (response) {
					if (response.success && response.data.products) {
						self.searchResults = response.data.products;
						self.renderResults(response.data.products);
					} else {
						self.renderNoResults();
					}
				},
				error: function () {
					self.renderNoResults();
				},
			});
		},

		/**
		 * Render search results in dropdown
		 *
		 * @param {Array} products Array of product objects
		 */
		renderResults: function (products) {
			const self = this;

			if (!products.length) {
				this.renderNoResults();
				return;
			}

			let html = '';

			products.forEach(function (product, index) {
				html += `
					<div class="momcs-search-result-item" 
						 data-index="${index}" 
						 data-product-id="${product.id}"
						 data-edit-link="${product.edit_link}">
						<img src="${product.image || ''}" alt="${self.escapeHtml(product.name)}" class="momcs-search-result-thumb">
						<div class="momcs-search-result-info">
							<span class="momcs-search-result-name">${self.escapeHtml(product.name)}</span>
							<div class="momcs-search-result-meta">
								<span class="momcs-search-result-price">${product.formatted_price}</span>
								${product.sku ? `<span class="momcs-search-result-sku">SKU: ${self.escapeHtml(product.sku)}</span>` : ''}
							</div>
						</div>
					</div>
				`;
			});

			this.searchDropdown.html(html);
			this.selectedIndex = -1;
			this.showDropdown();
		},

		/**
		 * Render no results message
		 */
		renderNoResults: function () {
			this.searchDropdown.html(
				'<div class="momcs-search-no-results">No products found</div>'
			);
			this.searchResults = [];
			this.showDropdown();
		},

		/**
		 * Handle keyboard navigation
		 *
		 * @param {Event} e Keyboard event
		 */
		handleKeydown: function (e) {
			const items = this.searchDropdown.find('.momcs-search-result-item');

			if (!items.length) {
				return;
			}

			switch (e.keyCode) {
				case 40: // Arrow Down
					e.preventDefault();
					this.selectedIndex = Math.min(this.selectedIndex + 1, items.length - 1);
					this.updateSelection(items);
					break;

				case 38: // Arrow Up
					e.preventDefault();
					this.selectedIndex = Math.max(this.selectedIndex - 1, 0);
					this.updateSelection(items);
					break;

				case 13: // Enter
					e.preventDefault();
					if (this.selectedIndex >= 0) {
						const selectedItem = items.eq(this.selectedIndex);
						const editLink = selectedItem.data('edit-link');
						if (editLink) {
							window.open(editLink, '_blank');
						}
						this.hideDropdown();
						this.searchInput.val('');
					}
					break;

				case 27: // Escape
					this.hideDropdown();
					break;
			}
		},

		/**
		 * Update visual selection state
		 *
		 * @param {jQuery} items Result items
		 */
		updateSelection: function (items) {
			items.removeClass('is-focused');
			if (this.selectedIndex >= 0) {
				items.eq(this.selectedIndex).addClass('is-focused');

				// Scroll into view
				const container = this.searchDropdown[0];
				const selectedEl = items[this.selectedIndex];
				if (selectedEl.offsetTop < container.scrollTop) {
					container.scrollTop = selectedEl.offsetTop;
				} else if (
					selectedEl.offsetTop + selectedEl.offsetHeight >
					container.scrollTop + container.offsetHeight
				) {
					container.scrollTop =
						selectedEl.offsetTop +
						selectedEl.offsetHeight -
						container.offsetHeight;
				}
			}
		},

		/**
		 * Show the search dropdown
		 */
		showDropdown: function () {
			this.searchDropdown.addClass('is-open');
		},

		/**
		 * Hide the search dropdown
		 */
		hideDropdown: function () {
			this.searchDropdown.removeClass('is-open');
			this.selectedIndex = -1;
		},

		/**
		 * Escape HTML to prevent XSS
		 *
		 * @param {string} text Text to escape
		 * @return {string} Escaped text
		 */
		escapeHtml: function (text) {
			const div = document.createElement('div');
			div.textContent = text;
			return div.innerHTML;
		},
	};

	/**
	 * Action Menu Module
	 */
	const ActionMenu = {
		/**
		 * Initialize action menus
		 */
		init: function () {
			this.bindEvents();
		},

		/**
		 * Bind event handlers
		 */
		bindEvents: function () {

			// Close menu when clicking outside
			$(document).on('click', function (e) {
				if (!$(e.target).closest('.momcs-action-menu').length) {
					$('.momcs-action-menu-dropdown').removeClass('is-open');
				}
			});

			// Close menu when pressing Escape
			$(document).on('keydown', function (e) {
				if (e.keyCode === 27) {
					$('.momcs-action-menu-dropdown').removeClass('is-open');
				}
			});
		},
	};

	/**
	 * Per-Page Selector Module
	 */
	const PerPageSelector = {
		/**
		 * Initialize per-page selectors
		 */
		init: function () {
			this.bindEvents();
		},

		/**
		 * Bind event handlers
		 */
		bindEvents: function () {
			$(document).on('change', '.momcs-per-page-select', function () {
				const perPage = $(this).val();
				const currentUrl = new URL(window.location.href);

				// Save preference via AJAX
				$.ajax({
					url: momcs_sync.ajax_url,
					type: 'POST',
					data: {
						action: 'momcs_save_products_per_page',
						nonce: momcs_sync.nonce,
						per_page: perPage,
					},
					success: function () {
						// Reset to page 1 and reload with new per_page
						currentUrl.searchParams.set('paged', '1');
						window.location.href = currentUrl.toString();
					},
					error: function () {
						// Still reload even if save fails
						currentUrl.searchParams.set('paged', '1');
						window.location.href = currentUrl.toString();
					},
				});
			});
		},
	};

	/**
	 * Checkbox Selection Module
	 */
	const CheckboxSelection = {
		/**
		 * Initialize checkbox selection
		 */
		init: function () {
			this.bindEvents();
		},

		/**
		 * Bind event handlers
		 */
		bindEvents: function () {
			// Select all checkbox
			$(document).on('change', '#momcs-select-all', function () {
				const isChecked = $(this).prop('checked');
				$('.momcs-products-table tbody input[type="checkbox"]').prop(
					'checked',
					isChecked
				);
			});

			// Individual checkbox - update select all state
			$(document).on(
				'change',
				'.momcs-products-table tbody input[type="checkbox"]',
				function () {
					const totalCheckboxes = $(
						'.momcs-products-table tbody input[type="checkbox"]'
					).length;
					const checkedCheckboxes = $(
						'.momcs-products-table tbody input[type="checkbox"]:checked'
					).length;

					$('#momcs-select-all').prop(
						'checked',
						totalCheckboxes === checkedCheckboxes && totalCheckboxes > 0
					);
				}
			);
		},
	};

	/**
	 * Filter Module
	 *
	 * Manages the filters popup: open/close and apply/clear.
	 * Sort, Category, and Status are applied only when "Apply" is clicked.
	 */
	const FilterModule = {
		/**
		 * Initialize filters (popup + apply/clear)
		 */
		init: function () {
			this.bindEvents();
		},

		/**
		 * Show the filters modal.
		 */
		openModal: function () {
			$('#momcs-filters-modal-overlay').addClass('is-open').attr('aria-hidden', 'false');
			$('#momcs-filters-modal').addClass('is-open').attr('aria-hidden', 'false');
			$('#momcs-filters-trigger').attr('aria-expanded', 'true');
		},

		/**
		 * Hide the filters modal.
		 */
		closeModal: function () {
			$('#momcs-filters-modal-overlay').removeClass('is-open').attr('aria-hidden', 'true');
			$('#momcs-filters-modal').removeClass('is-open').attr('aria-hidden', 'true');
			$('#momcs-filters-trigger').attr('aria-expanded', 'false');
		},

		/**
		 * Build URL with current filter values and redirect.
		 *
		 * @param {Object} overrides Optional overrides for orderby, product_cat, listing_status.
		 */
		applyAndRedirect: function (overrides) {
			const currentUrl = new URL(window.location.href);
			const orderby = overrides && overrides.orderby !== undefined ? overrides.orderby : $('#momcs-filter-sort').val();
			const productCat = overrides && overrides.product_cat !== undefined ? overrides.product_cat : $('#momcs-filter-category').val();
			const listingStatus = overrides && overrides.listing_status !== undefined ? overrides.listing_status : $('#momcs-filter-status').val();

			currentUrl.searchParams.set('orderby', orderby);
			currentUrl.searchParams.set('paged', '1');
			if (productCat) {
				currentUrl.searchParams.set('product_cat', productCat);
			} else {
				currentUrl.searchParams.delete('product_cat');
			}
			if (listingStatus) {
				currentUrl.searchParams.set('listing_status', listingStatus);
			} else {
				currentUrl.searchParams.delete('listing_status');
			}
			window.location.href = currentUrl.toString();
		},

		/**
		 * Bind event handlers
		 */
		bindEvents: function () {
			// Open filters popup
			$('#momcs-filters-trigger').on('click', function () {
				FilterModule.openModal();
			});

			// Close popup: overlay or close button
			$('#momcs-filters-modal-overlay').on('click', function () {
				FilterModule.closeModal();
			});
			$('#momcs-filters-modal-close').on('click', function () {
				FilterModule.closeModal();
			});

			// Close on Escape
			$(document).on('keydown.momcsFiltersModal', function (e) {
				if (e.key === 'Escape' && $('#momcs-filters-modal').hasClass('is-open')) {
					FilterModule.closeModal();
				}
			});

			// Apply: redirect with current filter values
			$('#momcs-filters-apply').on('click', function () {
				FilterModule.applyAndRedirect();
			});

			// Clear: reset to defaults and redirect
			$('#momcs-filters-clear').on('click', function () {
				$('#momcs-filter-sort').val('date-desc');
				$('#momcs-filter-category').val('');
				$('#momcs-filter-status').val('');
				FilterModule.applyAndRedirect({
					orderby: 'date-desc',
					product_cat: '',
					listing_status: ''
				});
			});
		},
	};

	/**
	 * Initialize all modules on document ready
	 */
	$(document).ready(function () {
		// Only initialize if we're on the products page
		if ($('.momcs-products-modern').length) {
			ProductSearch.init();
			ActionMenu.init();
			PerPageSelector.init();
			CheckboxSelection.init();
			FilterModule.init();
		}
	});
})(jQuery);
