/**
 * @file assets/js/adminjs/mbs-admin-migrate.js
 *
 * MyBookTable migration handler — Story 14-1b.
 *
 * Sends the selected JSON file directly to mbs_import_mybooktable via FormData,
 * bypassing the CSV pipeline entirely. This gives admins:
 *   · One-click migration (no column-mapping step).
 *   · Full 6-setting affiliate import.
 *   · Direct DAO writes with better series hierarchy and multi-author support.
 *
 * Progress UX uses MBSImportProgress (mbs-import-progress.js):
 *   - Vanishing current-activity line replaces itself per timed step.
 *   - On success: progress.complete(summary) fades the bar after 2.5 s.
 *   - On error: progress.failed(msg) hides the bar, shows red status line.
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

/* global MBSImportProgress, MBS_AdminUtils, ajaxurl */
( function ( $ ) {
	'use strict';
	var __ = wp.i18n.__;
	var _n = wp.i18n._n;
	var sprintf = wp.i18n.sprintf;

	/** @type {Object} MBSImportProgress instance */
	var progress = null;

	// -------------------------------------------------------------------------
	// Init
	// -------------------------------------------------------------------------

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

	// -------------------------------------------------------------------------
	// Upload and migrate
	// -------------------------------------------------------------------------

	$( document ).on( 'click', '#mbs-migrate-mbt-btn', function () {
		var fileInput = document.getElementById( 'mbs-migrate-mbt-file' );
		var $btn      = $( this );

		if ( ! fileInput || ! fileInput.files.length ) {
			progress.reset();
			progress.failed( __( 'Please choose a MyBookTable JSON export file first.', 'my-book-showroom' ) );
			return;
		}

		var file = fileInput.files[ 0 ];

		// Accept .json files and extensionless files — MBT exports are JSON
		// but ship with no file extension (UNREGFREE-10).
		var hasNoExtension = file.name.indexOf( '.' ) === -1;
		if ( ! hasNoExtension && ! file.name.toLowerCase().endsWith( '.json' ) ) {
			progress.reset();
			progress.failed( __( 'Please select a .json file exported from MyBookTable.', 'my-book-showroom' ) );
			return;
		}

		// WordPress sets `ajaxurl` globally on all admin pages.
		if ( typeof ajaxurl === 'undefined' ) {
			progress.reset();
			progress.failed( __( 'Admin AJAX URL not available. Please reload and try again.', 'my-book-showroom' ) );
			return;
		}

		var nonce = fileInput.getAttribute( 'data-nonce' ) || '';

		$btn.prop( 'disabled', true ).text( __( 'Importing…', 'my-book-showroom' ) );

		progress.reset();
		progress.show();
		progress.setBar( 2 );
		progress.setMessage( __( 'Beginning migration — uploading and validating file…', 'my-book-showroom' ) );

		var stopProgress = startProgressMessages();

		MBS_AdminUtils.fileUploadAjax( {
			action:  'mbs_import_mybooktable',
			nonce:   nonce,
			file:    file,
			timeout: 600000,
			success: function ( response ) {
				stopProgress();
				$btn.prop( 'disabled', false ).text( __( 'Upload & Migrate', 'my-book-showroom' ) );

				if ( ! response.success ) {
					var errMsg = ( response.data && response.data.message )
						? response.data.message
						: __( 'Import failed. Please check your file and try again.', 'my-book-showroom' );
					progress.failed( errMsg );
					return;
				}

				var d     = response.data;
				var parts = [];

				if ( d.imported > 0 ) {
					parts.push( sprintf( _n( '%d book imported', '%d books imported', d.imported, 'my-book-showroom' ), d.imported ) );
				}
				if ( d.skipped > 0 ) {
					parts.push( sprintf( __( '%d skipped (already exist)', 'my-book-showroom' ), d.skipped ) );
				}
				if ( d.settings_applied > 0 ) {
					parts.push( sprintf( _n( '%d affiliate setting applied', '%d affiliate settings applied', d.settings_applied, 'my-book-showroom' ), d.settings_applied ) );
				}

				var summary = parts.length
					? parts.join( ', ' ) + '.'
					: __( 'No new books found in the file.', 'my-book-showroom' );

				if ( d.errors && d.errors.length ) {
					$.each( d.errors, function ( i, errMsg ) {
						progress.addWarning( errMsg );
					} );
				}

				progress.complete( sprintf( __( '✓ Migration complete: %s', 'my-book-showroom' ), summary ) );
			},
			error: function ( xhr, status ) {
				stopProgress();
				$btn.prop( 'disabled', false ).text( __( 'Upload & Migrate', 'my-book-showroom' ) );
				var errMsg = __( 'Upload failed.', 'my-book-showroom' );
				if ( 'timeout' === status ) {
					errMsg = __( 'The import timed out. Try again — duplicate books are skipped automatically.', 'my-book-showroom' );
				}
				progress.failed( errMsg );
			}
		} );
	} );

	// -------------------------------------------------------------------------
	// Timed progress messages
	// -------------------------------------------------------------------------

	/**
	 * Rotate status messages while the import AJAX request is in flight.
	 *
	 * Returns a cancel function; call it in the success/error handler to stop
	 * the rotation and let the final result message replace the last status line.
	 *
	 * Timings are calibrated to the real import pipeline:
	 *   0 s  — file upload + PHP validation
	 *   8 s  — JSON parsed, settings extracted
	 *  20 s  — taxonomy terms (series, genres, tags) being created
	 *  40 s  — book records being imported
	 *  75 s  — cover images being downloaded (slowest step)
	 * 150 s  — still sideloading covers for large catalogs
	 * 240 s  — nearing completion
	 * 330 s  — final wrap-up
	 *
	 * @returns {Function}  Cancel function.
	 */
	function startProgressMessages() {
		var steps = [
			{ delay:     0, pct:  5, text: __( 'File verified. Analyzing book catalog structure…',                'my-book-showroom' ) },
			{ delay:  8000, pct: 10, text: __( 'Importing series, genres, and tag data…',                          'my-book-showroom' ) },
			{ delay: 20000, pct: 20, text: __( 'Importing books…',                                                  'my-book-showroom' ) },
			{ delay: 40000, pct: 40, text: __( 'Downloading and importing cover images — this is the slowest step…', 'my-book-showroom' ) },
			{ delay: 75000, pct: 55, text: __( 'Still working — large catalogs can take 5–8 minutes…',    'my-book-showroom' ) },
			{ delay:150000, pct: 70, text: __( 'Almost done — finishing the last few covers…',                 'my-book-showroom' ) },
			{ delay:240000, pct: 88, text: __( 'Wrapping up…',                                                      'my-book-showroom' ) },
			{ delay:330000, pct: 95, text: __( 'Finalising…',                                                       'my-book-showroom' ) },
		];

		var timers    = [];
		var canceled = false;

		steps.forEach( function ( step ) {
			var t = setTimeout( function () {
				if ( ! canceled ) {
					progress.setBar( step.pct );
					progress.setMessage( step.text );
				}
			}, step.delay );
			timers.push( t );
		} );

		return function cancel() {
			canceled = true;
			timers.forEach( clearTimeout );
		};
	}

} )( jQuery );
