/* Sync Queue functionality — left-nav layout with 4 views */
(function ($) {
	'use strict';

	// ---------------------------------------------------------------------
	// Constants & State
	// ---------------------------------------------------------------------
	const clockIcon = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 490 490"><path d="M245,0C109.5,0,0,109.5,0,245s109.5,245,245,245s245-109.5,245-245S380.5,0,245,0z M245,449.3c-112.6,0-204.3-91.7-204.3-204.3S132.4,40.7,245,40.7S449.3,132.4,449.3,245S357.6,449.3,245,449.3z"/><path d="M290.9,224.1h-25v-95.9c0-11.5-9.4-20.9-20.9-20.9s-20.9,9.4-20.9,20.9V245c0,11.5,9.4,20.9,20.9,20.9h45.9c11.5,0,20.9-9.4,20.9-20.9S302.3,224.1,290.9,224.1z"/></svg>';

	let currentPage = 1;
	let perPage      = 10;
	let totalItems   = 0;

	// ---------------------------------------------------------------------
	// Pagination Helpers - Modern Structure
	// ---------------------------------------------------------------------
	function renderPagination(total) {
		const totalPages = Math.ceil( total / perPage );
		const start      = total ? (currentPage - 1) * perPage + 1 : 0;
		const end        = Math.min( start + perPage - 1, total );

		// Update job count badge
		$( '#momcs-queue-count' ).text( total + ' ' + (total === 1 ? 'job' : 'jobs') );

		// Update pagination info
		const infoText = 'Showing <strong>' + start + '</strong>-<strong>' + end + '</strong> of <strong>' + total + '</strong> jobs';
		$( '#momcs-pagination-info-top, #momcs-pagination-info-bottom' ).html( infoText );

		// Show/hide pagination wrappers
		if (totalPages > 1 || total > 0) {
			$( '#momcs-pagination-top, #momcs-pagination-bottom' ).show();
		} else {
			$( '#momcs-pagination-top, #momcs-pagination-bottom' ).hide();
		}

		if (totalPages <= 1) {
			$( '#momcs-pagination-nav-top, #momcs-pagination-nav-bottom' ).empty();
			return;
		}

		// Build modern pagination navigation
		let navHtml = '';

		// First Page Button
		navHtml += '<button class="momcs-page-btn momcs-page-first" ' + (currentPage === 1 ? 'disabled' : '') + ' data-action="first" data-page="1">';
		navHtml += '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
		navHtml += '<polyline points="11 17 6 12 11 7"></polyline>';
		navHtml += '<polyline points="18 17 13 12 18 7"></polyline>';
		navHtml += '</svg></button>';

		// Previous Page Button
		navHtml += '<button class="momcs-page-btn momcs-page-prev" ' + (currentPage === 1 ? 'disabled' : '') + ' data-action="prev" data-page="' + (currentPage - 1) + '">';
		navHtml += '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
		navHtml += '<polyline points="15 18 9 12 15 6"></polyline>';
		navHtml += '</svg></button>';

		// Page Numbers
		navHtml += '<div class="momcs-page-numbers">';
		const range = 2;
		const startPage = Math.max( 1, currentPage - range );
		const endPage = Math.min( totalPages, currentPage + range );

		if (startPage > 1) {
			navHtml += '<button class="momcs-page-num" data-page="1">1</button>';
			if (startPage > 2) {
				navHtml += '<span class="momcs-page-ellipsis">...</span>';
			}
		}

		for (let i = startPage; i <= endPage; i++) {
			const activeClass = (i === currentPage) ? 'active' : '';
			navHtml += '<button class="momcs-page-num ' + activeClass + '" data-page="' + i + '">' + i + '</button>';
		}

		if (endPage < totalPages) {
			if (endPage < totalPages - 1) {
				navHtml += '<span class="momcs-page-ellipsis">...</span>';
			}
			navHtml += '<button class="momcs-page-num" data-page="' + totalPages + '">' + totalPages + '</button>';
		}

		navHtml += '</div>';

		// Next Page Button
		navHtml += '<button class="momcs-page-btn momcs-page-next" ' + (currentPage >= totalPages ? 'disabled' : '') + ' data-action="next" data-page="' + (currentPage + 1) + '">';
		navHtml += '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
		navHtml += '<polyline points="9 18 15 12 9 6"></polyline>';
		navHtml += '</svg></button>';

		// Last Page Button
		navHtml += '<button class="momcs-page-btn momcs-page-last" ' + (currentPage >= totalPages ? 'disabled' : '') + ' data-action="last" data-page="' + totalPages + '">';
		navHtml += '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
		navHtml += '<polyline points="13 17 18 12 13 7"></polyline>';
		navHtml += '<polyline points="6 17 11 12 6 7"></polyline>';
		navHtml += '</svg></button>';

		$( '#momcs-pagination-nav-top, #momcs-pagination-nav-bottom' ).html( navHtml );
	}

	// ---------------------------------------------------------------------
	// State for Tab Management — 4 views
	// ---------------------------------------------------------------------
	let currentTab = 'product_manual';

	// ---------------------------------------------------------------------
	// Column labels (localized from PHP, fallbacks for backwards compatibility)
	// ---------------------------------------------------------------------
	function col(key) {
		return (typeof momcs_sync_queue !== 'undefined' && momcs_sync_queue.cols && momcs_sync_queue.cols[key]) ? momcs_sync_queue.cols[key] : key;
	}

	// ---------------------------------------------------------------------
	// Tab → AJAX action mapping
	// ---------------------------------------------------------------------
	function getAjaxAction(tab) {
		switch (tab) {
			case 'product_manual':    return 'momcs_get_sync_queue';
			case 'product_scheduled': return 'momcs_get_scheduled_sync_queue';
			case 'order_manual':      return 'momcs_get_order_sync_queue';
			case 'order_scheduled':   return 'momcs_get_order_sync_queue';
			default:                  return 'momcs_get_sync_queue';
		}
	}

	// ---------------------------------------------------------------------
	// Dynamic table header per tab (no Job ID column)
	// ---------------------------------------------------------------------
	function getHeaderHtml(tab) {
		let th = '<tr>';
		if (tab === 'product_manual') {
			th += '<th>' + col('direction') + '</th>';
			th += '<th>' + col('mode') + '</th>';
			th += '<th>' + col('channelMarketplace') + '</th>';
		} else if (tab === 'product_scheduled') {
			th += '<th>' + col('direction') + '</th>';
			th += '<th>' + col('mode') + '</th>';
			th += '<th>' + col('channel') + '</th>';
		} else {
			// order_manual / order_scheduled
			th += '<th>' + col('fetched') + '</th>';
			th += '<th>' + col('created') + '</th>';
			th += '<th>' + col('failed') + '</th>';
			th += '<th>' + col('skipped') + '</th>';
		}
		th += '<th>' + col('createdOn') + '</th>';
		th += '<th>' + col('status') + '</th>';
		th += '<th>' + col('details') + '</th>';
		th += '</tr>';
		return th;
	}

	function getColumnCount(tab) {
		if (tab === 'order_manual' || tab === 'order_scheduled') {
			return 7;
		}
		return 6; // product_manual & product_scheduled
	}

	// ---------------------------------------------------------------------
	// Shimmer HTML for loading state (table body rows) - column count per tab
	// ---------------------------------------------------------------------
	function getShimmerRowsHtml(tab) {
		const count = getColumnCount(tab);
		let tdCells = '';
		for (let c = 0; c < count; c++) {
			tdCells += '<td><div class="momcs-shimmer"></div></td>';
		}
		const row = '<tr class="momcs-shimmer-row">' + tdCells + '</tr>';
		let html = '';
		for (let i = 0; i < 5; i++) {
			html += row;
		}
		return html;
	}

	// ---------------------------------------------------------------------
	// Fetch Queue Data & Build Table Rows
	// ---------------------------------------------------------------------
	function loadQueue(page, tab) {
		page = page || 1;
		tab  = tab || 'product_manual';
		currentPage = page;
		currentTab = tab;

		// Dynamic header and shimmer for current tab (column count must match)
		$( '#momcs_sync_queue_table thead' ).html( getHeaderHtml( tab ) );
		$( '#momcs_sync_queue_table tbody' ).html( getShimmerRowsHtml( tab ) );
		$( '#momcs-pagination-top, #momcs-pagination-bottom' ).hide();

		var postData = {
			action: getAjaxAction(tab),
			nonce: momcs_sync_queue.nonce,
			page: page,
			per_page: perPage
		};

		// Pass sync_type filter for order tabs.
		if (tab === 'order_manual') {
			postData.sync_type = 'manual';
		} else if (tab === 'order_scheduled') {
			postData.sync_type = 'scheduled';
		}

		$.post(
			ajaxurl,
			postData
		).done(
			function (resp) {
				if ( ! resp.success) {
					return;
				}

				totalItems = resp.data.total || 0;
				let rows   = '';

				$.each(
					resp.data.items || [],
					function (_, item) {
						let chipClass = '';
						switch (item.status.toLowerCase()) {
							case 'completed':
								chipClass = 'success';
								break;
							case 'failed':
								chipClass = 'error';
								break;
							case 'cancelled':
								chipClass = 'warning';
								break;
							case 'in progress':
							case 'processing':
								chipClass = 'info';
								break;
							default:
								chipClass = 'default';
						}

						// Short status labels to avoid wrapping.
						const statusLower = (item.status || '').toLowerCase();
						let statusLabel = item.status || '';
						if (statusLower === 'completed') {
							statusLabel = 'Completed';
						} else if (statusLower === 'failed') {
							statusLabel = 'Failed';
						} else if (statusLower === 'cancelled') {
							statusLabel = 'Cancelled';
						} else if (statusLower === 'in progress' || statusLower === 'processing') {
							statusLabel = statusLower === 'processing' ? 'Processing' : 'In progress';
						} else if (statusLabel && statusLabel.length > 0) {
							statusLabel = statusLabel.charAt(0).toUpperCase() + statusLabel.slice(1).toLowerCase();
						}

						// Build actions column
						let actionsContent = '<a href="#" class="momcs-view-logs" data-id="' + item.id + '">View Logs</a>';
						if (item.can_cancel && item.batch_id) {
							actionsContent += ' | <a href="#" class="momcs-cancel-sync" data-id="' + item.id + '" data-batch-id="' + item.batch_id + '">Cancel</a>';
						}

						const statusCell = '<span class="momcs-sync-status-chip-modern ' + chipClass + '"><span class="momcs-sync-status-dot-modern"></span>' + statusLabel + '</span>';

						// Build row per tab type (no Job ID column)
						if (currentTab === 'order_manual' || currentTab === 'order_scheduled') {
							rows += '<tr>' +
								'<td>' + (item.fetched !== undefined ? item.fetched : '—') + '</td>' +
								'<td>' + (item.created !== undefined ? item.created : 0) + '</td>' +
								'<td>' + (item.failed !== undefined ? item.failed : 0) + '</td>' +
								'<td>' + (item.skipped !== undefined ? item.skipped : 0) + '</td>' +
								'<td>' + item.date + '</td>' +
								'<td>' + statusCell + '</td>' +
								'<td>' + actionsContent + '</td>' +
								'</tr>';
						} else if (currentTab === 'product_scheduled') {
							const dir = (item.direction && item.mode) ? item.direction : '';
							const mode = (item.direction && item.mode) ? item.mode : (item.attributes || '');
							const ch = item.channel || 'Unknown';
							rows += '<tr>' +
								'<td>' + dir + '</td>' +
								'<td>' + mode + '</td>' +
								'<td>' + ch + '</td>' +
								'<td>' + item.date + '</td>' +
								'<td>' + statusCell + '</td>' +
								'<td>' + actionsContent + '</td>' +
								'</tr>';
						} else {
							// product_manual: Direction | Mode | Channel/Marketplace
							var dir = item.direction || '';
							var mode = item.mode || '';
							let channelCell = '';
							if (item.channel && item.marketplace) {
								channelCell = '<div class="momcs-sync-channel-marketplace">' +
									'<span class="momcs-channel-name">' + item.channel + '</span>' +
									'<span class="momcs-marketplace-separator"> - </span>' +
									'<span class="momcs-marketplace-name">' + item.marketplace + '</span>';
								if (item.product_count) {
									channelCell += '<br><small class="momcs-product-count">' + item.product_count + ' product(s)</small>';
								}
								channelCell += '</div>';
							} else if (item.channel) {
								// Amazon → WC rows have a channel but no marketplace.
								channelCell = '<div class="momcs-sync-channel-marketplace">' +
									'<span class="momcs-channel-name">' + item.channel + '</span></div>';
							} else if (item.product_count) {
								channelCell = '<div class="momcs-sync-product-count"><span>' + item.product_count + ' product(s)</span></div>';
							}
							rows += '<tr>' +
								'<td>' + dir + '</td>' +
								'<td>' + mode + '</td>' +
								'<td>' + channelCell + '</td>' +
								'<td>' + item.date + '</td>' +
								'<td>' + statusCell + '</td>' +
								'<td>' + actionsContent + '</td>' +
								'</tr>';
						}
					}
				);

				const colCount = getColumnCount( currentTab );
				$( '#momcs_sync_queue_table tbody' ).html( rows || '<tr><td colspan="' + colCount + '">No sync jobs found.</td></tr>' );
				renderPagination( totalItems );
			}
		).fail( function () {
			const colCount = getColumnCount( currentTab );
			$( '#momcs_sync_queue_table tbody' ).html( '<tr><td colspan="' + colCount + '">Unable to load. Please try again.</td></tr>' );
		} );
	}

	// ---------------------------------------------------------------------
	// Modal: Show Action Scheduler Job Logs
	// ---------------------------------------------------------------------
	function showJobLogs(id) {
		const loadingHtml = '<div class="momcs-sync-modal-overlay-modern"></div>' +
			'<div class="momcs-sync-loading-modal-modern">' +
			'<div class="momcs-sync-spinner-modern"></div>' +
			'<p class="momcs-sync-loading-text">Loading logs...</p></div>';
		$( 'body' ).append( loadingHtml );

		$.post(
			ajaxurl,
			{
				action: 'momcs_get_job_logs',
				nonce: momcs_sync_queue.nonce,
				action_id: id
			},
			function (resp) {
				$( '.momcs-sync-modal-overlay-modern, .momcs-sync-loading-modal-modern' ).remove();

				if ( ! resp.success) {
					alert( 'No logs available' );
					return;
				}

				let html = '<div class="momcs-sync-modal-overlay-modern"></div>';
				html    += '<div class="momcs-sync-modal-modern">' +
				'<div class="momcs-sync-modal-header-modern">' +
				'<h2>Logs for Job ' + id + '</h2>' +
				'<div class="momcs-sync-modal-actions">' +
				'<label class="momcs-toggle-switch">' +
				'<span class="momcs-toggle-label">Show detailed logs</span>' +
				'<input type="checkbox" id="momcs-detailed-toggle">' +
				'<span class="momcs-toggle-slider"></span>' +
				'</label>' +
				'<button type="button" class="momcs-sync-modal-close-modern" aria-label="Close">&times;</button>' +
				'</div>' +
				'</div>' +
				'<div class="momcs-sync-modal-content-modern">';

				const groups = {};
				$.each(
					resp.data,
					function (_, row) {
						const pid = row.payload && row.payload.product_id ? row.payload.product_id : 0;
						if ( ! groups[pid]) {
							groups[pid] = {
								title: (row.payload && row.payload.product_title) || ('Product #' + pid),
								errors: 0
							};
						}
						if (row.type === 'error') {
							groups[pid].errors += 1;
						}
					}
				);

				// Compute summary stats.
				let totalProducts = 0, successProducts = 0, errorProducts = 0;
				$.each( groups, function (pid, grp) {
					if (pid == 0) { return; }
					totalProducts++;
					if (grp.errors > 0) { errorProducts++; } else { successProducts++; }
				});

				// --- Summary Bar ---
				html += '<div class="momcs-audit-summary-bar">';

				// Stats section
				html += '<div class="momcs-audit-summary-stats">';
				html += '<span class="momcs-audit-stat">' +
					'<span class="momcs-audit-stat-value">' + totalProducts + '</span>' +
					'<span class="momcs-audit-stat-label">Products</span></span>';
				html += '<span class="momcs-audit-stat momcs-audit-stat-success">' +
					'<span class="momcs-audit-stat-dot"></span>' +
					'<span class="momcs-audit-stat-value">' + successProducts + '</span>' +
					'<span class="momcs-audit-stat-label">Passed</span></span>';
				html += '<span class="momcs-audit-stat momcs-audit-stat-error">' +
					'<span class="momcs-audit-stat-dot"></span>' +
					'<span class="momcs-audit-stat-value">' + errorProducts + '</span>' +
					'<span class="momcs-audit-stat-label">Failed</span></span>';
				html += '</div>';

				// Filter section
				html += '<div class="momcs-audit-product-filter">';

				// Active filter chip (hidden initially)
				html += '<span class="momcs-audit-active-filter" id="momcs-audit-active-filter" style="display:none;">' +
					'<span class="momcs-audit-active-filter-text"></span>' +
					'<button class="momcs-audit-active-filter-clear" aria-label="Clear filter">&times;</button>' +
					'</span>';

				// Search wrapper
				html += '<div class="momcs-audit-product-search-wrapper">' +
					'<svg class="momcs-audit-search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">' +
					'<circle cx="11" cy="11" r="8"></circle>' +
					'<path d="m21 21-4.35-4.35"></path></svg>' +
					'<input type="text" class="momcs-audit-search-input" id="momcs-audit-search" ' +
					'placeholder="Filter by product..." autocomplete="off" />' +
					'</div>';

				// Dropdown
				html += '<div class="momcs-audit-product-dropdown" id="momcs-audit-dropdown">';

				// "All" option
				html += '<div class="momcs-audit-dropdown-item momcs-audit-dropdown-all active" data-pid="all">' +
					'<span class="momcs-audit-dropdown-item-name">All Products</span>' +
					'<span class="momcs-audit-dropdown-item-count">' + resp.data.length + ' logs</span></div>';

				// Error filter toggle (only show if there are errors)
				if (errorProducts > 0) {
					html += '<div class="momcs-audit-dropdown-group-header">' +
						'<span>Show only errors</span>' +
						'<label class="momcs-audit-error-toggle">' +
						'<input type="checkbox" id="momcs-audit-errors-only" />' +
						'<span class="momcs-audit-mini-toggle"></span></label></div>';
				}

				// Scrollable product list
				html += '<div class="momcs-audit-dropdown-scroll" id="momcs-audit-dropdown-scroll">';
				$.each( groups, function (pid, grp) {
					if (pid == 0) { return; }
					var statusClass = grp.errors > 0 ? 'error' : 'success';
					var badgeText   = grp.errors > 0
						? grp.errors + ' error' + (grp.errors > 1 ? 's' : '')
						: '\u2713';
					html += '<div class="momcs-audit-dropdown-item" data-pid="' + pid + '">' +
						'<span class="momcs-audit-dropdown-item-status ' + statusClass + '"></span>' +
						'<span class="momcs-audit-dropdown-item-name momcs-audit-log-group-title">' + grp.title + '</span>' +
						'<span class="momcs-audit-dropdown-item-badge ' + statusClass + '">' + badgeText + '</span>' +
						'</div>';
				});
				html += '</div>'; // close scroll
				html += '<div class="momcs-audit-dropdown-empty" style="display:none;">No products match your search</div>';
				html += '</div>'; // close dropdown
				html += '</div>'; // close filter
				html += '</div>'; // close summary bar

				html += '<ol class="momcs-sync-timeline" id="momcs-audit-timeline">';
				$.each(
					resp.data,
					function (_, row) {
						const pid      = row.payload && row.payload.product_id ? row.payload.product_id : 0;
						const sev      = row.type || 'info';
						const detailed = (row.payload && row.payload.stage && /_(request|response)$/.test( row.payload.stage )) ? '1' : '0';
						let node       = '<li class="momcs-sync-node momcs-sev-' + sev + '" data-detailed="' + detailed + '" data-pid="' + pid + '"' + (detailed === '1' ? ' style="display:none;"' : '') + '>';

						let primary = '';
						if (row.payload && typeof row.payload === 'object') {
							if (row.payload.message) {
								primary = row.payload.message;
							} else if (row.payload.stage) {
								primary = row.payload.stage.replace( /_/g, ' ' );
							}
						}
						if ( ! primary) {
							primary = row.pretty || row.type;
						}

						let formatted    = '';
						const isRequest  = row.payload && (row.type === 'request' || row.payload.method);
						const isResponse = row.payload && (row.type === 'response' || typeof row.payload.status_code !== 'undefined' || typeof row.payload.statusCode !== 'undefined');

						if (isRequest) {
							const method = (row.payload.method || 'GET').toUpperCase();
							const url    = row.payload.endpoint || row.payload.url || '';
							formatted   += '<div><span class="momcs-chip momcs-chip-method method-' + method.toLowerCase() + '">' + method + '</span> ' +
							'<code class="momcs-code-url">' + url + '</code></div>';
							if (row.payload.headers) {
								formatted += '<h4 style="margin:4px 0 2px;">Headers</h4>' +
								'<pre class="momcs-sub-pre">' + JSON.stringify( row.payload.headers, null, 2 ) + '</pre>';
							}
							let bodyData = row.payload.body || row.payload.request;
							if ( ! bodyData) {
								const clone = Object.assign( {}, row.payload );
								['method', 'endpoint', 'url', 'headers', 'stage', 'severity', 'product_id'].forEach(
									function (k) {
										delete clone[k]; }
								);
								bodyData = Object.keys( clone ).length ? clone : null;
							}
							if (bodyData) {
								const prettyBody = typeof bodyData === 'string' ? (() => {
									try {
										return JSON.stringify( JSON.parse( bodyData ), null, 2 ); } catch (e) {
																	return bodyData; }
								})() : JSON.stringify( bodyData, null, 2 );
								formatted += '<h4 style="margin:4px 0 2px;">Body</h4>' +
									'<pre class="momcs-sub-pre">' + prettyBody + '</pre>';
							}
						} else if (isResponse) {
							const status      = row.payload.status_code || row.payload.statusCode || 0;
							const statusClass = (status >= 200 && status < 300) ? 'success' : 'error';
							formatted        += '<div><span class="momcs-chip momcs-chip-status ' + statusClass + '">' + status + '</span></div>';
							if (row.payload.headers) {
								formatted += '<h4 style="margin:4px 0 2px;">Headers</h4>' +
								'<pre class="momcs-sub-pre">' + JSON.stringify( row.payload.headers, null, 2 ) + '</pre>';
							}
							let respBody = row.payload.body || row.payload.response;
							if ( ! respBody) {
								const clone = Object.assign( {}, row.payload );
								['status_code', 'statusCode', 'headers', 'stage', 'severity', 'product_id', 'success', 'message'].forEach(
									function (k) {
										delete clone[k]; }
								);
								respBody = Object.keys( clone ).length ? clone : null;
							}
							if (respBody) {
								const prettyResp = typeof respBody === 'string' ? (() => {
									try {
										return JSON.stringify( JSON.parse( respBody ), null, 2 ); } catch (e) {
																	return respBody; }
								})() : JSON.stringify( respBody, null, 2 );
								formatted += '<h4 style="margin:4px 0 2px;">Body</h4>' +
									'<pre class="momcs-sub-pre">' + prettyResp + '</pre>';
							}
						}

						if ( ! isRequest && ! isResponse) {
							formatted += '<pre style="white-space:pre-wrap;background:#f7f7f7;padding:8px;border-radius:10px;margin-top:8px;">' + row.pretty + '</pre>';
						}

						node += '<strong>' + primary + '</strong><br/><small class="timestamp">' + clockIcon + row.time + '</small>';
						node += '<div class="momcs-sync-details" style="display:none;margin-top:8px;">' + formatted + '</div>';
						node += '</li>';
						html += node;
					}
				);
				html += '</ol></div></div>';

				$( 'body' ).append( html );

				$( document ).off( 'click', '.momcs-sync-node' );
				$( document ).off( 'click', '.momcs-audit-dropdown-item' );
				$( document ).off( 'click', '.momcs-audit-active-filter-clear' );
				$( document ).off( 'input', '#momcs-audit-search' );
				$( document ).off( 'focus', '#momcs-audit-search' );
				$( document ).off( 'change', '#momcs-audit-errors-only' );
				$( document ).off( 'click', '.momcs-sync-modal-close-modern, .momcs-sync-modal-overlay-modern' );
				$( document ).off( 'change', '#momcs-detailed-toggle' );

				// Expand/collapse timeline nodes
				$( document ).on(
					'click',
					'.momcs-sync-node',
					function (e) {
						e.preventDefault();
						e.stopPropagation();
						if ($( e.target ).closest( 'pre' ).length) {
							return;
						}

						const $details = $( this ).find( '.momcs-sync-details' );
						$( '.momcs-sync-details' ).not( $details ).slideUp( 100 );
						$details.slideToggle( 100 );
						$( this ).toggleClass( 'active' );
						$( '.momcs-sync-node' ).not( this ).removeClass( 'active' );
					}
				);

				// Open dropdown on search input focus
				$( document ).on( 'focus', '#momcs-audit-search', function () {
					$( '#momcs-audit-dropdown' ).addClass( 'is-open' );
				});

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

				// Search filtering within dropdown (debounced)
				var auditSearchTimer;
				$( document ).on( 'input', '#momcs-audit-search', function () {
					var query = $( this ).val().toLowerCase().trim();
					clearTimeout( auditSearchTimer );
					auditSearchTimer = setTimeout( function () {
						var visibleCount = 0;
						$( '#momcs-audit-dropdown-scroll .momcs-audit-dropdown-item' ).each( function () {
							var name    = $( this ).find( '.momcs-audit-dropdown-item-name' ).text().toLowerCase();
							var matches = ! query || name.indexOf( query ) !== -1;
							$( this ).toggle( matches );
							if (matches) { visibleCount++; }
						});
						$( '.momcs-audit-dropdown-empty' ).toggle( visibleCount === 0 );

						// Ensure dropdown is open
						$( '#momcs-audit-dropdown' ).addClass( 'is-open' );
					}, 150 );
				});

				// Product selection from dropdown
				$( document ).on( 'click', '.momcs-audit-dropdown-item', function (e) {
					e.preventDefault();
					e.stopPropagation();

					var pid = $( this ).data( 'pid' );

					// Update active state in dropdown
					$( '.momcs-audit-dropdown-item' ).removeClass( 'active' );
					$( this ).addClass( 'active' );

					// Update active filter chip
					if (pid === 'all') {
						$( '#momcs-audit-active-filter' ).hide();
					} else {
						var productName = $( this ).find( '.momcs-audit-dropdown-item-name' ).text();
						$( '#momcs-audit-active-filter' ).show()
							.find( '.momcs-audit-active-filter-text' ).text( productName );
					}

					// Close dropdown & clear search
					$( '#momcs-audit-dropdown' ).removeClass( 'is-open' );
					$( '#momcs-audit-search' ).val( '' );
					// Reset search filter
					$( '#momcs-audit-dropdown-scroll .momcs-audit-dropdown-item' ).show();
					$( '.momcs-audit-dropdown-empty' ).hide();

					// Apply timeline filter
					$( '#momcs-audit-timeline .momcs-sync-node' ).each( function () {
						var $node        = $( this );
						var isDetailed   = $node.data( 'detailed' ) === 1;
						var showDetailed = $( '#momcs-detailed-toggle' ).prop( 'checked' );
						var matchesPid   = pid === 'all' || $node.data( 'pid' ) == pid;
						$node.toggle( matchesPid && ( ! isDetailed || showDetailed) );
					});
				});

				// Clear filter chip handler
				$( document ).on( 'click', '.momcs-audit-active-filter-clear', function (e) {
					e.preventDefault();
					e.stopPropagation();
					$( '.momcs-audit-dropdown-all' ).trigger( 'click' );
				});

				// Errors-only toggle inside dropdown
				$( document ).on( 'change', '#momcs-audit-errors-only', function () {
					var errorsOnly = $( this ).prop( 'checked' );
					$( '#momcs-audit-dropdown-scroll .momcs-audit-dropdown-item' ).each( function () {
						if (errorsOnly) {
							var isError = $( this ).find( '.momcs-audit-dropdown-item-status' ).hasClass( 'error' );
							$( this ).toggle( isError );
						} else {
							$( this ).show();
						}
					});
				});

				// Close modal
				$( document ).on(
					'click',
					'.momcs-sync-modal-close-modern, .momcs-sync-modal-overlay-modern',
					function () {
						$( '.momcs-sync-modal-modern, .momcs-sync-modal-overlay-modern' ).remove();
					}
				);

				// Detailed logs toggle
				$( document ).on(
					'change',
					'#momcs-detailed-toggle',
					function () {
						const show = this.checked;
						$( '#momcs-audit-timeline .momcs-sync-node' ).each(
							function () {
								const $node      = $( this );
								const isDetailed = $node.data( 'detailed' ) === 1;
								let matchesPid   = true;
								const activeTab  = $( '.momcs-audit-dropdown-item.active' ).data( 'pid' );
								if (activeTab && activeTab !== 'all') {
									matchesPid = $node.data( 'pid' ) === activeTab;
								}
								$node.toggle( ! isDetailed || (show && matchesPid) );
							}
						);
					}
				);
				$( '#momcs-detailed-toggle' ).prop( 'checked', false ).trigger( 'change' );
			}
		);
	}

	// ---------------------------------------------------------------------
	// Event Bindings
	// ---------------------------------------------------------------------
	// Modern pagination button clicks
	$( document ).on(
		'click',
		'.momcs-page-btn[data-page]:not(:disabled), .momcs-page-num[data-page]',
		function (e) {
			e.preventDefault();
			const page = parseInt( $( this ).data( 'page' ), 10 ) || 1;
			if (page && page !== currentPage) {
				loadQueue( page, currentTab );
			}
		}
	);

	// Items per page selector
	$( document ).on(
		'change',
		'.momcs-per-page-select',
		function () {
			perPage = parseInt( $( this ).val(), 10 ) || 10;
			loadQueue( 1, currentTab );
		}
	);

	$( document ).on(
		'click',
		'.momcs-view-logs',
		function (e) {
			e.preventDefault();
			const id = $( this ).data( 'id' );
			id && showJobLogs( id );
		}
	);

	// Left-nav item switching handler
	$( document ).on(
		'click',
		'.momcs-audit-nav-item',
		function (e) {
			e.preventDefault();

			const tabType = $( this ).data( 'tab' );

			// Update active nav item
			$( '.momcs-audit-nav-item' ).removeClass( 'active' );
			$( this ).addClass( 'active' );

			// Load queue for the selected tab
			currentTab = tabType;
			loadQueue( 1, tabType );
		}
	);

	// Cancel sync handler
	$( document ).on(
		'click',
		'.momcs-cancel-sync',
		function (e) {
			e.preventDefault();

			if ( ! confirm( 'Are you sure you want to cancel this sync?' ) ) {
				return;
			}

			const $link   = $( this );
			const id      = $link.data( 'id' );
			const batchId = $link.data( 'batch-id' );

			$link.text( 'Cancelling...' ).css( 'pointer-events', 'none' );

			$.post(
				ajaxurl,
				{
					action: 'momcs_cancel_marketplace_sync',
					nonce: momcs_sync_queue.nonce,
					action_id: id,
					batch_id: batchId
				},
				function (resp) {
					if ( resp.success ) {
						loadQueue( currentPage, currentTab );
					} else {
						alert( resp.data.message || 'Failed to cancel sync' );
						$link.text( 'Cancel' ).css( 'pointer-events', 'auto' );
					}
				}
			).fail( function() {
				alert( 'Failed to cancel sync' );
				$link.text( 'Cancel' ).css( 'pointer-events', 'auto' );
			});
		}
	);

	// ---------------------------------------------------------------------
	// Initial Load
	// ---------------------------------------------------------------------
	$(
		function () {
			loadQueue( 1, 'product_manual' );
		}
	);

})( jQuery );
