/**
 * @file assets/js/adminjs/mbs-import-amazon.js
 * Amazon ASIN lookup and confirm-import flow with PA-API credentials save on Settings → Import / Export.
 *
 * Uses MBSImportProgress (mbs-import-progress.js) for progress bar UX on confirm-import.
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

/* global MBSImportProgress */
( function ( $ ) {
	'use strict';

	var __ = wp.i18n.__;
	var _n = wp.i18n._n;

	var utils            = window.MBS_ImpExpUtils;
	var amazonCandidates = [];
	var progress         = null;

	$( function () {
		progress = MBSImportProgress.create( {
			barWrap    : document.getElementById( 'mbs-amazon-progress-bar' ),
			barFill    : document.getElementById( 'mbs-amazon-bar' ),
			msgArea    : document.getElementById( 'mbs-amazon-msgarea' ),
			statusArea : document.getElementById( 'mbs-amazon-status' ),
		} );
	} );

	// ── PA-API credentials save ───────────────────────────────────────────────

	$( document ).on( 'click', '#mbs-amazon-save-credentials-btn', function () {
		var $btn       = $( this );
		var $msg       = $( '#mbs-amazon-credentials-message' );
		var nonce      = $btn.data( 'nonce' );
		var accessKey  = $( '#mbs-amazon-access-key' ).val().trim();
		var secretKey  = $( '#mbs-amazon-secret-key' ).val().trim();
		var partnerTag = $( '#mbs-amazon-partner-tag' ).val().trim();

		if ( ! accessKey && ! secretKey && ! partnerTag ) {
			$msg.removeClass( 'mbs-cred-ok mbs-cred-err' )
			    .addClass( 'mbs-cred-err' )
			    .text( __( 'Please enter at least one value.', 'my-book-showroom' ) )
			    .show();
			return;
		}

		$btn.prop( 'disabled', true ).text( __( 'Saving\u2026', 'my-book-showroom' ) );
		$msg.hide();

		$.post( MBS_Settings.ajaxUrl, {
			action:      'mbs_save_amazon_credentials',
			nonce:       nonce,
			access_key:  accessKey,
			secret_key:  secretKey,
			partner_tag: partnerTag
		}, function ( response ) {
			if ( response.success ) {
				$msg.removeClass( 'mbs-cred-err' )
				    .addClass( 'mbs-cred-ok' )
				    .text( response.data.message || __( 'Credentials saved.', 'my-book-showroom' ) )
				    .show();
				// Clear sensitive fields after save — do not leave key material in the DOM.
				$( '#mbs-amazon-access-key' ).val( '' ).attr( 'placeholder', __( 'Leave blank to keep existing', 'my-book-showroom' ) );
				$( '#mbs-amazon-secret-key' ).val( '' ).attr( 'placeholder', __( 'Leave blank to keep existing', 'my-book-showroom' ) );
			} else {
				$msg.removeClass( 'mbs-cred-ok' )
				    .addClass( 'mbs-cred-err' )
				    .text( ( response.data && response.data.message ) ? response.data.message : __( 'Save failed.', 'my-book-showroom' ) )
				    .show();
			}
		} ).fail( function ( jqXHR, textStatus ) {
			$msg.removeClass( 'mbs-cred-ok' )
			    .addClass( 'mbs-cred-err' )
			    .text( wp.i18n.sprintf( __( 'AJAX error: %s', 'my-book-showroom' ), textStatus ) )
			    .show();
		} ).always( function () {
			$btn.prop( 'disabled', false ).text( __( 'Save Credentials', 'my-book-showroom' ) );
		} );
	} );

	// ── Amazon fetch ──────────────────────────────────────────────────────────

	$( '#mbs-amazon-fetch-btn' ).on( 'click', function () {
		var $btn  = $( this );
		var codes = $( '#mbs-amazon-list' ).val().trim();
		var nonce = $( '#mbs-amazon-panel-nonce' ).val();

		if ( ! codes ) {
			utils.mbsShowPanelMessage( 'mbs-amazon-message', __( 'Please enter at least one ASIN or ISBN.', 'my-book-showroom' ), 'error' );
			return;
		}

		$btn.prop( 'disabled', true ).text( __( 'Looking up\u2026', 'my-book-showroom' ) );
		$( '#mbs-amazon-candidates-preview' ).empty();
		amazonCandidates = [];

		$.post( MBS_Settings.ajaxUrl, {
			action: 'mbs_import_amazon',
			nonce:  nonce,
			codes:  codes
		}, function ( response ) {
			if ( response.success ) {
				amazonCandidates = response.data.candidates || [];
				utils.mbsRenderCandidatePreview(
					'#mbs-amazon-candidates-preview',
					amazonCandidates,
					nonce,
					'#mbs-amazon-message'
				);
			} else {
				utils.mbsShowPanelMessage(
					'mbs-amazon-message',
					wp.i18n.sprintf( __( 'Lookup failed: %s', 'my-book-showroom' ), response.data.message || __( 'Unknown error', 'my-book-showroom' ) ),
					'error'
				);
			}
		} ).fail( function ( jqXHR, textStatus ) {
			utils.mbsShowPanelMessage( 'mbs-amazon-message', wp.i18n.sprintf( __( 'AJAX error: %s', 'my-book-showroom' ), textStatus ), 'error' );
		} ).always( function () {
			$btn.prop( 'disabled', false ).text( __( 'Look Up ASINs / ISBNs', 'my-book-showroom' ) );
		} );
	} );

	// ── Confirm import (delegated on panel — no cross-module branching) ───────

	$( '#mbs-panel-amazon' ).on( 'click', '.mbs-confirm-import-btn', function () {
		var $btn            = $( this );
		var nonce           = $btn.data( 'nonce' );
		var messageSelector = $btn.data( 'message-selector' );

		if ( ! amazonCandidates.length ) {
			return;
		}

		$btn.prop( 'disabled', true ).text( __( 'Importing\u2026', 'my-book-showroom' ) );
		if ( progress ) {
			progress.reset();
			progress.show();
			progress.setBar( 10 );
			progress.setMessage( __( 'Importing books\u2026', 'my-book-showroom' ) );
		}

		$.post( MBS_Settings.ajaxUrl, {
			action:            'mbs_import_candidates',
			nonce:             nonce,
			candidates_json:   JSON.stringify( amazonCandidates ),
			force_insert_keys: JSON.stringify( [] )
		}, function ( response ) {
			if ( response.success ) {
				var d = response.data;
				var confirmSummary = wp.i18n.sprintf( _n( '%d book imported.', '%d books imported.', d.inserted, 'my-book-showroom' ), d.inserted ) +
					( d.skipped ? ' ' + wp.i18n.sprintf( _n( '%d skipped (duplicate).', '%d skipped (duplicates).', d.skipped, 'my-book-showroom' ), d.skipped ) : '' );
				if ( progress ) { progress.complete( confirmSummary ); } else { utils.mbsShowPanelMessage( messageSelector.replace( '#', '' ), confirmSummary, 'success' ); }
				$btn.closest( 'table' ).addBack().next( 'p' ).remove();
				window.mbsTriggerCoverSideload( nonce, 'mbs-amazon-status' );
			} else {
				var confirmFailMsg = wp.i18n.sprintf( __( 'Import failed: %s', 'my-book-showroom' ), response.data.message || __( 'Unknown error', 'my-book-showroom' ) );
				if ( progress ) { progress.failed( confirmFailMsg ); } else { utils.mbsShowPanelMessage( messageSelector.replace( '#', '' ), confirmFailMsg, 'error' ); }
				$btn.prop( 'disabled', false ).text( __( 'Retry Import', 'my-book-showroom' ) );
			}
		} ).fail( function ( jqXHR, textStatus ) {
			var confirmAjaxErr = wp.i18n.sprintf( __( 'AJAX error: %s', 'my-book-showroom' ), textStatus );
			if ( progress ) { progress.failed( confirmAjaxErr ); } else { utils.mbsShowPanelMessage( messageSelector.replace( '#', '' ), confirmAjaxErr, 'error' ); }
			$btn.prop( 'disabled', false ).text( __( 'Retry Import', 'my-book-showroom' ) );
		} );
	} );

} )( jQuery );
