/* A1-WooBay - Product edit screen Publish Box eBay panel
 * Handles: profile switcher, Verify/Publish/Revise/Re-list action button.
 * Reuses the `a1woobay` object localized alongside product-meta.js
 * (ajax_url, nonce, product_id, and the i18n strings below).
 */
(function($){
	$(function(){
		var pbNonce = a1woobay.nonce;
		var pid     = a1woobay.product_id;

		// Profile switcher
		$('#a1wb-pb-profile-select').on('change', function(){
			var profileId   = parseInt( $(this).val(), 10 );
			var resultEl    = $('#a1wb-pb-profile-result');
			resultEl.text(a1woobay.i18n.saving);
			$.post(a1woobay.ajax_url, {
				action:     'a1woobay_switch_profile',
				nonce:      pbNonce,
				product_id: pid,
				profile_id: profileId
			}, function(r){
				if (r.success) {
					resultEl.css('color','#2a7a2a').text('✓ ' + (r.data.message || a1woobay.i18n.saved));
					setTimeout(function(){ location.reload(); }, 900);
				} else {
					var msg = (r.data && r.data.message) ? r.data.message : a1woobay.i18n.failed;
					resultEl.css('color','#dc3232').text('✗ ' + msg);
				}
			}).fail(function(){
				resultEl.css('color','#dc3232').text('✗ ' + a1woobay.i18n.requestFailed);
			});
		});

		// Action button (Verify / Publish / Revise / Re-list)
		$('#a1wb-publish-box-panel').on('click', '.a1wb-pb-action', function(){
			var btn    = $(this);
			var action = btn.data('action');
			var label  = btn.data('label');
			var result = btn.siblings('.a1wb-pb-result');
			var ajaxAction = ( 'publish' === action )
				? 'a1woobay_push_product'
				: 'a1woobay_verify_product';

			btn.prop('disabled', true).text(a1woobay.i18n.working);
			result.css('color','#888').text(a1woobay.i18n.contactingEbay);

			$.post(a1woobay.ajax_url, {
				action:     ajaxAction,
				nonce:      pbNonce,
				product_id: pid
			}, function(r){
				btn.prop('disabled', false).text(label);
				if (r.success) {
					result.css('color','#2a7a2a').text('✓ ' + (r.data.message || a1woobay.i18n.done));
					setTimeout(function(){ location.reload(); }, 1800);
				} else {
					var msg = (r.data && r.data.message) ? r.data.message : (typeof r.data === 'string' ? r.data : a1woobay.i18n.actionFailed);
					result.css('color','#dc3232').text('✗ ' + msg);
				}
			}).fail(function(){
				btn.prop('disabled', false).text(label);
				result.css('color','#dc3232').text('✗ ' + a1woobay.i18n.requestFailed);
			});
		});
	});
}(jQuery));
