/* A1-WooBay - Import & Adopt eBay Listings page
 * Handles: inventory scan, import-from-scan, manual adopt-by-item-id.
 */
(function($) {

	var ajaxUrl = a1wbImport.ajaxUrl;
	var nonce   = a1wbImport.nonce;

	// ----- SCAN -----
	$('#a1wb-scan-btn').on('click', function() {
		$('#a1wb-scan-btn').prop('disabled', true);
		$('#a1wb-scan-spinner').show();
		$('#a1wb-scan-results').hide();
		$('#a1wb-scan-error').hide().empty();

		$.post(ajaxUrl, { action: 'a1woobay_fetch_ebay_inventory', nonce: nonce })
		.done(function(res) {
			$('#a1wb-scan-btn').prop('disabled', false);
			$('#a1wb-scan-spinner').hide();

			if (!res.success) {
				$('#a1wb-scan-error').text(res.data.message || 'Scan failed.').show();
				return;
			}

			var items = res.data.items;
			if (!items || items.length === 0) {
				$('#a1wb-scan-error').text('No inventory items found in eBay. Items created through A1 eBay Integration for WooCommerce will appear here.').show();
				return;
			}

			var html = '';
			$.each(items, function(i, item) {
				var actionHtml = '';
				if (item.already_tracked) {
					actionHtml = '<span style="color:#46b450;font-size:12px;">&#10003; Tracked</span>';
				} else if (item.wc_product_id) {
					actionHtml = '<button type="button" class="button button-small a1wb-import-btn" ' +
						'data-sku="' + escAttr(item.sku) + '" ' +
						'data-product-id="' + item.wc_product_id + '" ' +
						'data-offer-id="' + escAttr(item.offer_id) + '" ' +
						'data-listing-id="' + escAttr(item.listing_id) + '">' +
						'Import</button>';
				} else {
					actionHtml = '<span style="color:#888;font-size:12px;">No WC match</span>';
				}

				var statusColor = item.ebay_status === 'PUBLISHED' ? '#46b450' : '#888';
				var wcCell = item.wc_product_name
					? '<a href="' + escAttr(item.wc_edit_url) + '">' + escHtml(item.wc_product_name) + '</a>'
					: '<span style="color:#dc3232;font-size:12px;">No match found</span>';

				html += '<tr id="a1wb-scan-row-' + escAttr(item.sku) + '">' +
					'<td style="font-size:12px;">' + escHtml(item.sku) + '</td>' +
					'<td style="font-size:12px;">' + escHtml(item.title) + '</td>' +
					'<td style="font-size:12px;">' + wcCell + '</td>' +
					'<td style="font-size:12px;">' +
						(item.listing_id ? '<a href="https://www.ebay.com/itm/' + escAttr(item.listing_id) + '" target="_blank">' + escHtml(item.listing_id) + '</a>' : '--') +
					'</td>' +
					'<td><span style="padding:2px 6px;border-radius:3px;font-size:11px;color:#fff;background:' + statusColor + ';">' + escHtml(item.ebay_status || '--') + '</span></td>' +
					'<td>' + actionHtml + '</td>' +
					'</tr>';
			});

			$('#a1wb-scan-tbody').html(html);
			$('#a1wb-scan-results').show();
		})
		.fail(function() {
			$('#a1wb-scan-btn').prop('disabled', false);
			$('#a1wb-scan-spinner').hide();
			$('#a1wb-scan-error').text('Request failed. Check your connection.').show();
		});
	});

	// ----- IMPORT (from scan) -----
	$(document).on('click', '.a1wb-import-btn', function() {
		var $btn      = $(this);
		var productId = $btn.data('product-id');
		var offerId   = $btn.data('offer-id');
		var listingId = $btn.data('listing-id');
		var sku       = $btn.data('sku');

		$btn.prop('disabled', true).text('Importing...');

		$.post(ajaxUrl, {
			action:     'a1woobay_adopt_listing',
			nonce:      nonce,
			product_id: productId,
			item_id:    listingId,
			offer_id:   offerId,
		})
		.done(function(res) {
			if (res.success) {
				$btn.closest('td').html('<span style="color:#46b450;font-size:12px;">&#10003; Imported</span>');
			} else {
				$btn.prop('disabled', false).text('Import');
				alert(res.data.message || 'Import failed.');
			}
		})
		.fail(function() {
			$btn.prop('disabled', false).text('Import');
			alert('Request failed.');
		});
	});

	// ----- ADOPT (manual) -----
	$('#a1wb-adopt-btn').on('click', function() {
		var itemId    = $('#a1wb-adopt-item-id').val().trim();
		var productId = $('#a1wb-adopt-product').val();
		var $result   = $('#a1wb-adopt-result');

		if (!itemId) { $result.html('<span style="color:#dc3232;">Please enter an eBay Item ID.</span>'); return; }
		if (!productId) { $result.html('<span style="color:#dc3232;">Please select a WooCommerce product.</span>'); return; }

		$('#a1wb-adopt-btn').prop('disabled', true);
		$result.html('<em style="color:#888;">Adopting...</em>');

		$.post(ajaxUrl, {
			action:     'a1woobay_adopt_listing',
			nonce:      nonce,
			product_id: productId,
			item_id:    itemId,
			offer_id:   '',
		})
		.done(function(res) {
			$('#a1wb-adopt-btn').prop('disabled', false);
			if (res.success) {
				$result.html('<span style="color:#46b450;">' + escHtml(res.data.message) + ' — <a href="' + escAttr(res.data.edit_url) + '">Edit product</a></span>');
				$('#a1wb-adopt-item-id').val('');
				$('#a1wb-adopt-product').val('');
			} else {
				$result.html('<span style="color:#dc3232;">' + escHtml(res.data.message || 'Adopt failed.') + '</span>');
			}
		})
		.fail(function() {
			$('#a1wb-adopt-btn').prop('disabled', false);
			$result.html('<span style="color:#dc3232;">Request failed.</span>');
		});
	});

	// Helpers
	function escHtml(str) {
		return $('<div>').text(String(str || '')).html();
	}
	function escAttr(str) {
		return String(str || '').replace(/"/g, '&quot;').replace(/'/g, '&#039;');
	}

})(jQuery);
