/**
 * Order 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';

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

		/**
		 * Initialize the search module
		 */
		init: function () {
			this.searchInput = $('#momcs-order-search');
			this.searchDropdown = $('#momcs-order-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-order-search-wrapper').length) {
					self.hideDropdown();
				}
			});

			// Result item click
			this.searchDropdown.on('click', '.momcs-order-search-result-item', function () {
				const orderId = $(this).data('order-id');
				const amazonOrderId = $(this).data('amazon-order-id');
				
				// Filter orders by the selected order
				if (orderId) {
					// If we have a WooCommerce order ID, filter by it
					$('#momcs-order-search').val(orderId);
					// Trigger filter
					if (typeof applyFilters === 'function') {
						applyFilters();
					}
				} else if (amazonOrderId) {
					// Filter by Amazon Order ID
					$('#momcs-order-search').val(amazonOrderId);
					if (typeof applyFilters === 'function') {
						applyFilters();
					}
				}
				
				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-order-search-loading"><div class="momcs-order-search-loading-spinner"></div></div>'
			);
			this.showDropdown();

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

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

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

			let html = '';

			orders.forEach(function (order, index) {
				const orderId = order.order_id || order.id || '';
				const customer = order.customer || order.customer_name || '';
				const total = order.total || order.formatted_total || '';
				const amazonOrderId = order.amazon_order_id || '';

				html += `
					<div class="momcs-order-search-result-item" 
						 data-index="${index}" 
						 data-order-id="${orderId}"
						 data-amazon-order-id="${amazonOrderId}">
						<div class="momcs-order-search-result-info">
							<span class="order-id">#${self.escapeHtml(orderId)}</span>
							<span class="customer">${self.escapeHtml(customer)}</span>
							<span class="total">${self.escapeHtml(total)}</span>
						</div>
					</div>
				`;
			});

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

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

		/**
		 * Handle keyboard navigation
		 *
		 * @param {Event} e Keyboard event
		 */
		handleKeydown: function (e) {
			const items = this.searchDropdown.find('.momcs-order-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 orderId = selectedItem.data('order-id');
						const amazonOrderId = selectedItem.data('amazon-order-id');
						
						if (orderId) {
							$('#momcs-order-search').val(orderId);
							if (typeof applyFilters === 'function') {
								applyFilters();
							}
						} else if (amazonOrderId) {
							$('#momcs-order-search').val(amazonOrderId);
							if (typeof applyFilters === 'function') {
								applyFilters();
							}
						}
						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) {
			if (!text) {
				return '';
			}
			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 () {
			// Toggle menu on trigger click
			$(document).on('click', '.momcs-action-menu-trigger', function (e) {
				e.stopPropagation();
				const $menu = $(this).siblings('.momcs-action-menu-dropdown');
				$('.momcs-action-menu-dropdown').not($menu).removeClass('is-open');
				$menu.toggleClass('is-open');
			});

			// 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 () {
			const self = this;
			
			$(document).on('change', '.momcs-per-page-select', function () {
				const perPage = $(this).val();
				const $otherSelect = $(this).attr('id') === 'orders_per_page' 
					? $('#orders_per_page_bottom')
					: $('#orders_per_page');
				
				// Sync both selects
				$otherSelect.val(perPage);
				
				// Update order list state and reload
				if (typeof orderListState !== 'undefined') {
					orderListState.perPage = parseInt(perPage);
					orderListState.page = 1;
					
					if (typeof applyFilters === 'function') {
						applyFilters();
					} else if (typeof loadOrders === 'function') {
						loadOrders();
					}
				}
			});
		},
	};

	/**
	 * Pagination Module
	 */
	const PaginationModule = {
		/**
		 * Initialize pagination
		 */
		init: function () {
			this.bindEvents();
		},

		/**
		 * Bind event handlers
		 */
		bindEvents: function () {
			// Page navigation buttons
			$(document).on('click', '.momcs-page-btn', function () {
				const action = $(this).data('action');
				if (!action || $(this).prop('disabled')) {
					return;
				}

				if (typeof orderListState !== 'undefined') {
					const currentPage = orderListState.page || 1;
					const maxPages = orderListState.maxPages || 1;

					let newPage = currentPage;

					switch (action) {
						case 'first':
							newPage = 1;
							break;
						case 'prev':
							newPage = Math.max(1, currentPage - 1);
							break;
						case 'next':
							newPage = Math.min(maxPages, currentPage + 1);
							break;
						case 'last':
							newPage = maxPages;
							break;
					}

					if (newPage !== currentPage) {
						orderListState.page = newPage;
						if (typeof applyFilters === 'function') {
							applyFilters();
						} else if (typeof loadOrders === 'function') {
							loadOrders();
						}
					}
				}
			});

			// Page number clicks
			$(document).on('click', '.momcs-page-num', function (e) {
				e.preventDefault();
				const page = parseInt($(this).data('page'));
				if (page && typeof orderListState !== 'undefined') {
					orderListState.page = page;
					if (typeof applyFilters === 'function') {
						applyFilters();
					} else if (typeof loadOrders === 'function') {
						loadOrders();
					}
				}
			});
		},
	};

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