/**
 * @file assets/js/adminjs/mbs-import-covers.js
 * Cover image sideload poller; exposes window.mbsTriggerCoverSideload() for ISBN and Amazon import modules.
 * @package MyBookShowroom
 * @since   1.0.0
 */

( function ( $ ) {
	'use strict';

	var __ = wp.i18n.__;

	/**
	 * Poll mbs_sideload_covers until all pending cover URLs are processed.
	 * Appends per-book warnings/errors below the panel message element.
	 *
	 * @param {string} nonce         mbs_import_export nonce.
	 * @param {string} messageElemId ID (without #) of the status message element.
	 */
	function mbsTriggerCoverSideload( nonce, messageElemId ) {
		var $msg = $( '#' + messageElemId );
		if ( ! $msg.length ) {
			return;
		}

		var utils   = window.MBS_ImpExpUtils;
		var coverId = messageElemId + '-covers';

		$msg.after(
			'<div id="' + utils.esc( coverId ) + '" class="notice notice-info" style="margin-top:8px;">' +
			'<p>' + MBS_AdminUtils.escHtml( __( 'Processing cover images\u2026', 'my-book-showroom' ) ) + '</p></div>'
		);

		( function poll() {
			$.post( MBS_Settings.ajaxUrl, {
				action: 'mbs_sideload_covers',
				nonce:  nonce
			}, function ( response ) {
				var $coverMsg = $( '#' + coverId );

				if ( ! response.success ) {
					$coverMsg
						.removeClass( 'notice-info' ).addClass( 'notice-error' )
						.html( '<p>' + MBS_AdminUtils.escHtml( wp.i18n.sprintf(
							__( 'Cover processing failed: %s', 'my-book-showroom' ),
							( response.data && response.data.message ) || __( 'Unknown error', 'my-book-showroom' )
						) ) + '</p>' );
					return;
				}

				var d = response.data;

				if ( d.processed === 0 ) {
					$coverMsg.remove();
					return;
				}

				if ( d.remaining > 0 ) {
					$coverMsg.html(
					'<p>' + MBS_AdminUtils.escHtml( wp.i18n.sprintf(
						__( 'Processing covers\u2026 %d remaining.', 'my-book-showroom' ),
						d.remaining
					) ) + '</p>'
				);
					setTimeout( poll, 700 );
					return;
				}

				// All done — build summary.
				var lines = [];
				lines.push( MBS_AdminUtils.escHtml(
				wp.i18n.sprintf(
					wp.i18n._n( '%d cover image imported.', '%d cover images imported.', d.succeeded, 'my-book-showroom' ),
					d.succeeded
				)
			) );
				d.warnings.forEach( function ( w ) { lines.push( '\u26a0 ' + utils.esc( w ) ); } );
				d.errors.forEach(   function ( e ) { lines.push( '\u2715 ' + utils.esc( e ) ); } );

				var cls = d.errors.length ? 'notice-warning' : 'notice-success';
				$coverMsg
					.removeClass( 'notice-info' ).addClass( cls )
					.html( '<p>' + lines.join( '<br>' ) + '</p>' );
			} ).fail( function () {
				$( '#' + coverId ).remove();
			} );
		} )();
	}

	// Expose for use by mbs-import-isbn.js and mbs-import-amazon.js.
	window.mbsTriggerCoverSideload = mbsTriggerCoverSideload;

} )( jQuery );
