/**
 * @file assets/js/adminjs/mbs-import-isbn.js
 * ISBN bulk lookup via Google Books / Open Library and confirm-import flow 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 isbnCandidates = [];
	var progress         = null;

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

	// ── ISBN fetch ────────────────────────────────────────────────────────────

	$( '#mbs-isbn-fetch-btn' ).on( 'click', function () {
		var $btn   = $( this );
		var isbns  = $( '#mbs-isbn-list' ).val().trim();
		var source = $( 'input[name="mbs_isbn_source"]:checked' ).val() || 'google';
		var nonce  = $( '#mbs-isbn-panel-nonce' ).val();

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

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

		var action = ( source === 'openlibrary' )
			? 'mbs_import_open_library'
			: 'mbs_import_google_books';

		$.post( MBS_Settings.ajaxUrl, {
			action: action,
			nonce:  nonce,
			isbns:  isbns
		}, function ( response ) {
			if ( response.success ) {
				isbnCandidates = response.data.candidates || [];
				// BUG-ISBN-JS-1: Surface per-ISBN API errors (e.g. HTTP 429) so
				// the user sees the actual failure instead of a silent "No books found."
				var apiErrors = response.data.errors || [];
				utils.mbsRenderCandidatePreview(
					'#mbs-isbn-candidates-preview',
					isbnCandidates,
					nonce,
					'#mbs-isbn-message'
				);
				if ( apiErrors.length ) {
					utils.mbsShowPanelMessage(
						'mbs-isbn-message',
						apiErrors.join( '\n' ),
						'error'
					);
				}
			} else {
				utils.mbsShowPanelMessage(
					'mbs-isbn-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-isbn-message', wp.i18n.sprintf( __( 'AJAX error: %s', 'my-book-showroom' ), textStatus ), 'error' );
		} ).always( function () {
			$btn.prop( 'disabled', false ).text( __( 'Look Up ISBNs', 'my-book-showroom' ) );
		} );
	} );

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

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

		if ( ! isbnCandidates.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( isbnCandidates ),
			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-isbn-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' ) );
		} );
	} );

	// ── Google Books API key save ────────────────────────────────────────────────

	$( '#mbs-save-google-api-key-btn' ).on( 'click', function () {
		var $btn  = $( this );
		var key   = $( '#mbs-google-api-key' ).val().trim();
		var nonce = $( '#mbs-isbn-panel-nonce' ).val();

		if ( ! key ) {
			utils.mbsShowPanelMessage( 'mbs-google-api-key-message', __( 'Please enter an API key.', 'my-book-showroom' ), 'error' );
			return;
		}

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

		$.post( MBS_Settings.ajaxUrl, {
			action:  'mbs_save_google_books_api_key',
			nonce:   nonce,
			api_key: key
		}, function ( response ) {
			if ( response.success ) {
				utils.mbsShowPanelMessage( 'mbs-google-api-key-message', response.data.message, 'success' );
				$( '#mbs-google-api-key' ).val( '' );
			} else {
				utils.mbsShowPanelMessage(
					'mbs-google-api-key-message',
					response.data.message || __( 'Failed to save key.', 'my-book-showroom' ),
					'error'
				);
			}
		} ).fail( function ( jqXHR, textStatus ) {
			utils.mbsShowPanelMessage(
				'mbs-google-api-key-message',
				wp.i18n.sprintf( __( 'AJAX error: %s', 'my-book-showroom' ), textStatus ),
				'error'
			);
		} ).always( function () {
			$btn.prop( 'disabled', false ).text( __( 'Save Key', 'my-book-showroom' ) );
		} );
	} );

} )( jQuery );
