/* A1-WooBay - eBay Listings page
 * Handles: bulk actions modal, single-row actions, check-for-sales, sortable columns.
 */
(function($) {
	// Check-all checkbox
	$('#a1wb-check-all').on('change', function() {
		$('input[name="product_ids[]"]').prop('checked', this.checked);
	});

	// Local-only actions submit normally via form POST
	var localActions = ['move_to_archive', 'reset_to_prepared'];

	$('#a1wb-bulk-apply').on('click', function() {
		var action   = $('#a1wb-bulk-action').val();
		var checked  = $('input[name="product_ids[]"]:checked');

		if ( ! action ) {
			alert('Please select a bulk action.');
			return;
		}
		if ( checked.length === 0 ) {
			alert('Please select at least one item.');
			return;
		}

		if ( localActions.indexOf(action) !== -1 ) {
			// Submit the form normally
			if ( ['move_to_archive'].indexOf(action) !== -1 ) {
				if ( ! confirm('Apply this action to ' + checked.length + ' item(s)?') ) return;
			}
			$('#a1wb-listings-form').submit();
			return;
		}

		// eBay actions: run via AJAX loop
		var dangerous = ['end_listings', 'mark_sold'];
		if ( dangerous.indexOf(action) !== -1 ) {
			if ( ! confirm('This will send a request to eBay for each selected item. Apply to ' + checked.length + ' item(s)?') ) return;
		}

		var ids = [];
		checked.each(function() { ids.push(parseInt(this.value)); });
		runBulkAjax(action, ids);
	});

	function actionLabel(action) {
		var map = {
			'verify':       'Verifying with eBay',
			'publish':      'Publishing to eBay',
			'revise':       'Revising listings',
			'end_listings': 'Ending listings',
			'mark_sold':    'Marking as Sold',
			'relist':       'Re-listing',
			'resync':       'Re-syncing from eBay',
		};
		return map[action] || action;
	}

	function runBulkAjax(action, ids) {
		var ajaxAction = {
			'verify':       'a1woobay_verify_product',
			'publish':      'a1woobay_push_product',
			'revise':       'a1woobay_revise_product',
			'end_listings': 'a1woobay_end_listing',
			'mark_sold':    'a1woobay_mark_sold',
			'relist':       'a1woobay_push_product',
			'resync':       'a1woobay_resync_from_ebay',
		}[action];

		if ( ! ajaxAction ) {
			alert('This action is not yet supported.');
			return;
		}

		var nonce    = a1wbListings.productActionNonce;
		var ajaxUrl  = a1wbListings.ajaxUrl;
		var total    = ids.length;
		var done     = 0;
		var errors   = 0;

		// Open modal
		$('#a1wb-modal-title').text(actionLabel(action) + ' (' + total + ' items)');
		$('#a1wb-modal-log').empty();
		$('#a1wb-modal-progress').text('0 / ' + total);
		$('#a1wb-modal-close').prop('disabled', true);
		$('#a1wb-bulk-modal').css('display', 'flex');

		function log(pid, ok, msg) {
			var color = ok ? '#46b450' : '#dc3232';
			var icon  = ok ? '&#10003;' : '&#10007;';
			$('#a1wb-modal-log').append(
				'<div><span style="color:' + color + ';">' + icon + '</span> <strong>#' + pid + '</strong> &mdash; ' + $('<div>').text(msg).html() + '</div>'
			);
			// scroll to bottom
			var log = document.getElementById('a1wb-modal-log');
			log.scrollTop = log.scrollHeight;
		}

		function updateStatusBadge(pid, statusLabel, color) {
			var badge = $('#a1wb-row-' + pid + ' .a1wb-status-badge');
			if ( badge.length ) {
				badge.text(statusLabel.toUpperCase()).css('background', color);
			}
		}

		function processNext(index) {
			if ( index >= ids.length ) {
				// All done
				$('#a1wb-modal-progress').text(total + ' / ' + total + ' — ' + (total - errors) + ' succeeded, ' + errors + ' failed');
				$('#a1wb-modal-close').prop('disabled', false);
				return;
			}

			var pid = ids[index];
			$('#a1wb-modal-progress').text((index + 1) + ' / ' + total);

			$.post(ajaxUrl, {
				action:      ajaxAction,
				nonce:       nonce,
				product_id:  pid,
			}, function(res) {
				done++;
				if ( res && res.success ) {
					log(pid, true, res.data.message || 'OK');
					// Update badge in table
					var badgeMap = {
						'verify':       { label: 'Verified',  color: '#0073aa' },
						'publish':      { label: 'Published', color: '#46b450' },
						'revise':       { label: 'Published', color: '#46b450' },
						'end_listings': { label: 'Ended',     color: '#dc3232' },
						'mark_sold':    { label: 'Sold',      color: '#8b5cf6' },
						'relist':       { label: 'Published', color: '#46b450' },
						'resync':       { label: 'Synced',    color: '#46b450' },
					};
					if ( badgeMap[action] ) {
						updateStatusBadge(pid, badgeMap[action].label, badgeMap[action].color);
					}
					// Update watchers cell inline after re-sync
					if ( 'resync' === action && res.data.watch_count !== undefined ) {
						$('#a1wb-row-' + pid + ' .a1wb-watch-cell').text( res.data.watch_count );
					}
				} else {
					errors++;
					log(pid, false, (res && res.data && res.data.message) ? res.data.message : 'Unknown error');
				}
				processNext(index + 1);
			}).fail(function() {
				errors++;
				done++;
				log(pid, false, 'Request failed (network error)');
				processNext(index + 1);
			});
		}

		processNext(0);
	}


	// ---- Single-row action links ----
	$(document).on('click', '.a1wb-row-action', function(e) {
		e.preventDefault();
		var action = $(this).data('action');
		var pid    = String($(this).data('pid'));
		if ( ! action || ! pid ) return;
		if ( action === 'end_listings' ) {
			if ( ! confirm('End this eBay listing?') ) return;
		}
		runBulkAjax(action, [pid]);
	});

	$('#a1wb-modal-close').on('click', function() {
			$('#a1wb-bulk-modal').hide();
		});

		// Check for Sales - uses the bulk modal for feedback
		$('#a1wb-check-sales-btn').on('click', function(){
			var nonce = a1wbListings.importOrdersNonce;

			// Open modal in loading state
			$('#a1wb-modal-title').text('Checking eBay for New Orders…');
			$('#a1wb-modal-progress').text('Contacting eBay Fulfillment API…');
			$('#a1wb-modal-log').empty();
			$('#a1wb-modal-close').prop('disabled', true);
			$('#a1wb-bulk-modal').css('display', 'flex');

			$.post(ajaxurl, {
				action: 'a1woobay_import_orders',
				nonce:  nonce
			}, function(r){
				if (r.success) {
					var res = r.data.result;
					$('#a1wb-modal-title').text('Order Import Complete');
					$('#a1wb-modal-progress').text(r.data.message);
					if (res.created > 0) {
						$('#a1wb-modal-log').append('<div style="color:#2a9d2a;">' + res.created + ' new order(s) created in WooCommerce.</div>');
					}
					if (res.skipped > 0) {
						$('#a1wb-modal-log').append('<div style="color:#888;">' + res.skipped + ' order(s) already imported, skipped.</div>');
					}
					if (res.errors > 0) {
						$('#a1wb-modal-log').append('<div style="color:#dc3232;">' + res.errors + ' error(s) — check error log.</div>');
					}
					if (res.total === 0) {
						$('#a1wb-modal-log').append('<div style="color:#888;">No new eBay orders found in the current window.</div>');
					}
				} else {
					$('#a1wb-modal-title').text('Order Import Failed');
					$('#a1wb-modal-progress').text('');
					$('#a1wb-modal-log').append('<div style="color:#dc3232;">' + (r.data || 'Unknown error') + '</div>');
				}
				$('#a1wb-modal-close').prop('disabled', false);
			}).fail(function(){
				$('#a1wb-modal-title').text('Request Failed');
				$('#a1wb-modal-progress').text('');
				$('#a1wb-modal-log').append('<div style="color:#dc3232;">Could not reach the server. Please try again.</div>');
				$('#a1wb-modal-close').prop('disabled', false);
			});
		});

	// -------------------------------------------------------------------------
	// Sortable column headers
	// -------------------------------------------------------------------------
	var a1wbSortCol = -1;
	var a1wbSortDir = 1; // 1 = asc, -1 = desc

	$('.a1wb-sort-th').on('click', function() {
		var col  = parseInt( $(this).data('sort-col'), 10 );
		var type = $(this).data('sort-type');

		if ( a1wbSortCol === col ) {
			a1wbSortDir *= -1;
		} else {
			a1wbSortCol = col;
			a1wbSortDir = 1;
		}

		// Update sort indicators
		$('.a1wb-sort-ind').text('');
		$(this).find('.a1wb-sort-ind').text( a1wbSortDir === 1 ? '▲' : '▼' );

		var tbody = $('#a1wb-listings-tbody');
		var rows  = tbody.find('tr').get();

		rows.sort(function(a, b) {
			var aCell = $( $(a).find('td').get(col) );
			var bCell = $( $(b).find('td').get(col) );

			// Always read directly from DOM attribute (avoids jQuery data() cache issues after reorder)
			var aRaw = aCell.attr('data-sort-val');
			var bRaw = bCell.attr('data-sort-val');

			var aVal = ( aRaw !== undefined && aRaw !== null ) ? aRaw : aCell.text().trim();
			var bVal = ( bRaw !== undefined && bRaw !== null ) ? bRaw : bCell.text().trim();

			if ( type === 'num' ) {
				var aNum = parseFloat( aVal );
				var bNum = parseFloat( bVal );
				if ( isNaN(aNum) ) aNum = -Infinity;
				if ( isNaN(bNum) ) bNum = -Infinity;
				return ( aNum - bNum ) * a1wbSortDir;
			} else {
				return aVal.toLowerCase().localeCompare( bVal.toLowerCase() ) * a1wbSortDir;
			}
		});

		$.each(rows, function(i, row) {
			tbody.append(row);
		});
	});


})(jQuery);
