/**
 * @file assets/js/adminjs/mbs-import-wxr.js
 *
 * WXR (WordPress eXtended RSS) importer — Story 14-2.
 *
 * Progress UX uses MBSImportProgress (mbs-import-progress.js):
 *   Analyze and import steps both drive the shared progress bar.
 *   On success, progress.complete() fades the bar while the gap card
 *   stays visible below it.
 *
 * Three-step flow:
 *   Step 1: Upload a .xml WXR file to mbs_import_wxr_analyze.
 *           Server returns the unique postmeta keys found in the file,
 *           a target CPT hint, a source-plugin slug, and the MBS target field list.
 *   Step 2: Render a mapping table (source key → MBS field dropdown).
 *           On confirm, POST the mapping to mbs_import_wxr_run.
 *           Server imports books and returns counts.
 *   Step 3: Render a per-plugin gap card showing what to add after import.
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

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

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

	var state = {
		token:        '',
		targetFields: {},
		cpt:          '',
		sourceKey:    '',  // source-plugin slug returned by mbs_import_wxr_analyze
	};

	// ── Gap data ──────────────────────────────────────────────────────────────────────────────

	/**
	 * Fields MBS supports that no competitor plugin tracks.
	 * Shown for every import regardless of source.
	 *
	 * @type {string[]}
	 * @since 1.2.0
	 */
	var UNIVERSAL_GAPS = [
		__( 'Language', 'my-book-showroom' ),
		__( 'Copyright year', 'my-book-showroom' ),
		__( 'Tagline (short promotional phrase)', 'my-book-showroom' ),
		__( 'Edition number / type (e.g. 2nd Edition, Anniversary Edition)', 'my-book-showroom' ),
		__( 'Word count', 'my-book-showroom' ),
		__( 'Illustration count and type', 'my-book-showroom' ),
		__( 'Audience / age rating (middle grade, YA, adult, etc.)', 'my-book-showroom' ),
		__( 'Awards and recognition', 'my-book-showroom' ),
		__( 'Goodreads URL and StoryGraph URL', 'my-book-showroom' ),
		__( 'Book trailer URL', 'my-book-showroom' ),
		__( 'Imprint (separate from publisher)', 'my-book-showroom' ),
		__( 'THEMA / BISAC classification codes', 'my-book-showroom' ),
		__( 'Territorial rights', 'my-book-showroom' ),
	];

	/**
	 * Per-plugin gap configuration keyed by the source slug
	 * returned by mbs_import_wxr_analyze.
	 *
	 * pluginName   {string}   Display name used in the card heading.
	 * successMsg   {string}   Intro paragraph after a successful import.
	 * specificGaps {string[]} Plugin-specific fields to add, shown before universal gaps.
	 *
	 * @type {Object}
	 * @since 1.2.0
	 */
	var GAP_DATA = {
		'mybooktable': {
			pluginName:   __( 'MyBookTable', 'my-book-showroom' ),
			successMsg:   __( 'Your MyBookTable library has been imported — titles, covers, ISBNs, series, genres, and purchase links are all here. MBS supports a richer set of book metadata than MyBookTable. Take a few minutes to add the fields below to complete each record.', 'my-book-showroom' ),
			specificGaps: [
				__( 'Subtitle', 'my-book-showroom' ),
				__( 'Full publication date (add month and day — MyBookTable stores year only)', 'my-book-showroom' ),
				__( 'Dimensions', 'my-book-showroom' ),
				__( 'Weight', 'my-book-showroom' ),
			],
		},
		'wp-books-gallery': {
			pluginName:   __( 'WP Books Gallery', 'my-book-showroom' ),
			successMsg:   __( 'Your WP Books Gallery catalog has been imported. Titles, covers, ISBNs, pub dates, and publisher information are ready. MBS can store a much richer set of links and edition detail — add your other retailer links and assign genres to complete each record.', 'my-book-showroom' ),
			specificGaps: [
				__( 'Additional purchase links (WP Books Gallery stores one buy link per book — add Amazon, Barnes and Noble, Apple Books, and other retailers in MBS)', 'my-book-showroom' ),
				__( 'Additional edition rows (MBS stores separate entries for paperback, hardcover, ebook, and audiobook, each with its own ISBN/ASIN and price)', 'my-book-showroom' ),
				__( 'Genre / category (WP Books Gallery categories are not mapped to MBS genres automatically)', 'my-book-showroom' ),
				__( 'Series', 'my-book-showroom' ),
				__( 'Weight', 'my-book-showroom' ),
			],
		},
		'genesis-author-pro': {
			pluginName:   __( 'Genesis Author Pro', 'my-book-showroom' ),
			successMsg:   __( 'Your Genesis Author Pro books have been imported with titles, covers, ISBNs, pub dates, and purchase links. Because MBS tracks significantly more per-book detail, you will want to add ASINs, genres, and edition formats to unlock the full catalog experience.', 'my-book-showroom' ),
			specificGaps: [
				__( 'ASIN (Genesis Author Pro does not store ASINs — add yours to enable Kindle edition rows and affiliate link features)', 'my-book-showroom' ),
				__( 'Format (all books default to paperback — update audiobook, hardcover, and ebook titles to their correct format)', 'my-book-showroom' ),
				__( 'Page count', 'my-book-showroom' ),
				__( 'Subtitle', 'my-book-showroom' ),
				__( 'Additional purchase links (Genesis Author Pro supports three buy buttons — add more retailers in MBS)', 'my-book-showroom' ),
				__( 'Genre / category', 'my-book-showroom' ),
			],
		},
		'rs-wp-books': {
			pluginName:   __( 'RS WP Books Showcase', 'my-book-showroom' ),
			successMsg:   __( 'Your RS WP Books Showcase library has been imported — this is one of the most complete transfers available, including publisher, dimensions, weight, and all purchase links. Add series assignments, genres, and any additional edition rows to finish the records.', 'my-book-showroom' ),
			specificGaps: [
				__( 'Additional format editions (RS WP Books Showcase Pro stores multiple formats per book — MBS imports the primary edition and preserves all purchase links; promote additional formats to full edition rows in the book editor)', 'my-book-showroom' ),
				__( 'Subtitle', 'my-book-showroom' ),
				__( 'Series', 'my-book-showroom' ),
				__( 'Genre / category', 'my-book-showroom' ),
			],
		},
		'gs-bookshowcase': {
			pluginName:   __( 'GS Books Showcase', 'my-book-showroom' ),
			successMsg:   __( 'Your GS Books Showcase catalog has been imported with cover images, ISBNs, ASINs, pub dates, and all purchase links. MBS gives each format its own edition row — a few minutes in the editor will let you set up your full paperback, hardcover, and ebook records properly.', 'my-book-showroom' ),
			specificGaps: [
				__( 'Additional edition rows (GS Books Showcase Pro stores multiple formats per book — MBS imports the primary edition and all purchase links; promote additional formats to full edition rows in the book editor)', 'my-book-showroom' ),
				__( 'Genre / category (GS Books Showcase groups are not automatically mapped to MBS genres)', 'my-book-showroom' ),
				__( 'Authors (GS Books Showcase Pro author taxonomy is site-specific and not portable — re-assign authors in MBS)', 'my-book-showroom' ),
				__( 'Series', 'my-book-showroom' ),
				__( 'Subtitle', 'my-book-showroom' ),
				__( 'Weight', 'my-book-showroom' ),
			],
		},
		'novelist': {
			pluginName:   __( 'Novelist', 'my-book-showroom' ),
			successMsg:   __( 'Your Novelist library has been imported with titles, ISBNs, ASINs, series, pub dates, and all purchase links. Novelist is a focused plugin — MBS supports significantly more metadata. Add genres, formats, and language information to complete each record.', 'my-book-showroom' ),
			specificGaps: [
				__( 'Format (Novelist does not store a per-book format field — MBS infers paperback or ebook via ASIN detection; update audiobook, hardcover, and large-print titles to their correct format)', 'my-book-showroom' ),
				__( 'Genre / category (Novelist genre taxonomy terms are not automatically mapped to MBS genres)', 'my-book-showroom' ),
				__( 'Subtitle', 'my-book-showroom' ),
				__( 'Dimensions and weight', 'my-book-showroom' ),
			],
		},
	};

	// ── Init ──────────────────────────────────────────────────────────────────────────────

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

	// ── Step 1: Analyze ────────────────────────────────────────────────────────────────

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

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

		var file = fileInput.files[ 0 ];
		if ( ! file.name.toLowerCase().endsWith( '.xml' ) ) {
			progress.reset();
			progress.failed( __( 'Only .xml WXR export files are accepted.', 'my-book-showroom' ) );
			return;
		}

		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' ) || '';

		$( '#mbs-wxr-analyze-btn' ).prop( 'disabled', true ).text( __( 'Analyzing…', 'my-book-showroom' ) );
		progress.reset();
		progress.show();
		progress.setBar( 5 );
		progress.setMessage( __( 'Reading your export file — this may take a moment for large files…', 'my-book-showroom' ) );

		MBS_AdminUtils.fileUploadAjax( {
			action:  'mbs_import_wxr_analyze',
			nonce:   nonce,
			file:    file,
			timeout: 60000,
			success: function ( response ) {
				$( '#mbs-wxr-analyze-btn' ).prop( 'disabled', false ).text( __( 'Upload & Analyze', 'my-book-showroom' ) );

				if ( ! response.success ) {
					progress.failed(
						( response.data && response.data.message )
							? response.data.message
							: __( 'Analysis failed.', 'my-book-showroom' )
					);
					return;
				}

				var d = response.data;
				state.token        = d.token;
				state.targetFields = d.target_fields || {};
				state.cpt          = d.cpt || '';
				state.sourceKey    = d.source || '';

				if ( ! d.keys || ! d.keys.length ) {
					progress.failed( __( 'No postmeta keys were found in this export. Make sure you exported book posts.', 'my-book-showroom' ) );
					return;
				}

				renderMappingTable( d.keys );
				progress.reset();
				$( '#mbs-wxr-upload-area' ).hide();
				$( '#mbs-wxr-mapping-area' ).show();
			},
			error: function ( xhr, status ) {
				$( '#mbs-wxr-analyze-btn' ).prop( 'disabled', false ).text( __( 'Upload & Analyze', 'my-book-showroom' ) );
				progress.failed( 'timeout' === status ? __( 'Analysis timed out. Try a smaller file.', 'my-book-showroom' ) : __( 'Upload failed.', 'my-book-showroom' ) );
			}
		} );
	} );

	// ── Step 2: Render mapping table ─────────────────────────────────────────────────

	function renderMappingTable( keys ) {
		var $tbody = $( '#mbs-wxr-mapping-rows' ).empty();

		keys.forEach( function ( key ) {
			var $row = $( '<tr>' );

			$row.append(
				$( '<td>' ).text( key )
			);

			var $select = $( '<select>' )
				.attr( 'name', 'mbs_wxr_map[' + key + ']' )
				.attr( 'data-key', key );

			// Build options from MBS target fields.
			var autoMatch = guessTarget( key );
			$.each( state.targetFields, function ( value, label ) {
				var $opt = $( '<option>' ).val( value ).text( label );
				if ( value === autoMatch ) {
					$opt.prop( 'selected', true );
				}
				$select.append( $opt );
			} );

			$row.append( $( '<td>' ).append( $select ) );
			$tbody.append( $row );
		} );
	}

	/**
	 * Heuristic: guess the MBS target field from a postmeta key.
	 * Returns the matching target field value, or empty string to skip.
	 *
	 * @param  {string} key Source postmeta key.
	 * @returns {string}     MBS target field value.
	 * @since  1.0.0
	 */
	function guessTarget( key ) {
		var k = key.toLowerCase();
		if ( k.indexOf( 'isbn' ) !== -1 )          { return 'mbs_isbn13'; }
		if ( k.indexOf( 'asin' ) !== -1 )          { return 'mbs_asin'; }
		if ( k.indexOf( 'publisher' ) !== -1 && k.indexOf( 'url' ) !== -1 ) { return 'mbs_publisher_url'; }
		if ( k.indexOf( 'publisher' ) !== -1 )     { return 'mbs_publisher'; }
		if ( k.indexOf( 'pub_date' ) !== -1 || k.indexOf( 'publication' ) !== -1 ) { return 'mbs_pub_date'; }
		if ( k.indexOf( 'page' ) !== -1 && k.indexOf( 'count' ) !== -1 ) { return 'mbs_page_count'; }
		if ( k.indexOf( 'series' ) !== -1 && ( k.indexOf( 'num' ) !== -1 || k.indexOf( 'order' ) !== -1 ) ) { return 'mbs_series_number'; }
		if ( k.indexOf( 'series' ) !== -1 )        { return 'mbs_series_name'; }
		if ( k.indexOf( 'goodread' ) !== -1 )      { return 'mbs_goodreads_url'; }
		if ( k.indexOf( 'storygraph' ) !== -1 )    { return 'mbs_storygraph_url'; }
		if ( k.indexOf( 'bookbub' ) !== -1 )        { return 'mbs_bookbub_url'; }
		if ( k.indexOf( 'author_bio' ) !== -1 || k.indexOf( 'bio' ) !== -1 ) { return 'mbs_author_bio'; }
		return '';
	}

	// ── Step 2: Import ──────────────────────────────────────────────────────────────────────

	$( document ).on( 'click', '#mbs-wxr-import-btn', function () {
		var mapping  = {};

		$( '#mbs-wxr-mapping-rows select' ).each( function () {
			var key = $( this ).attr( 'data-key' );
			var val = $( this ).val();
			if ( key && val ) {
				mapping[ key ] = val;
			}
		} );

		if ( ! state.token ) {
			progress.reset();
			progress.failed( __( 'Session expired. Please re-upload your file.', 'my-book-showroom' ) );
			$( '#mbs-wxr-mapping-area' ).hide();
			$( '#mbs-wxr-upload-area' ).show();
			return;
		}

		$( '#mbs-wxr-import-btn' ).prop( 'disabled', true ).text( __( 'Importing…', 'my-book-showroom' ) );
		$( '#mbs-wxr-back-btn' ).prop( 'disabled', true );
		progress.reset();
		progress.show();
		progress.setBar( 10 );
		progress.setMessage( __( 'Importing books — please wait…', 'my-book-showroom' ) );

		var nonce = $( '#mbs-wxr-file' ).attr( 'data-nonce' ) || '';

		$.post(
			ajaxurl,
			{
				action:     'mbs_import_wxr_run',
				nonce:      nonce,
				token:      state.token,
				mapping:    JSON.stringify( mapping ),
				target_cpt: state.cpt,
			},
			function ( response ) {
				$( '#mbs-wxr-import-btn' ).prop( 'disabled', false ).text( __( 'Import Books', 'my-book-showroom' ) );
				$( '#mbs-wxr-back-btn' ).prop( 'disabled', false );

				if ( ! response.success ) {
					progress.failed(
						( response.data && response.data.message )
							? response.data.message
							: __( 'Import failed.', 'my-book-showroom' )
					);
					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 (duplicates)', 'my-book-showroom' ), d.skipped ) );
				}
				var summary = parts.length ? parts.join( ', ' ) + '.' : __( 'No new books found.', 'my-book-showroom' );
				if ( d.errors && d.errors.length ) {
					summary += ' (' + sprintf( _n( '%d error', '%d errors', d.errors.length, 'my-book-showroom' ), d.errors.length ) + ')';
				}

				progress.complete( summary );
				state.token = '';
				$( '#mbs-wxr-mapping-area' ).hide();
				renderGapCard( state.sourceKey, summary );
				$( '#mbs-wxr-file' ).val( '' );
			},
			'json'
		).fail( function () {
			$( '#mbs-wxr-import-btn' ).prop( 'disabled', false ).text( __( 'Import Books', 'my-book-showroom' ) );
			$( '#mbs-wxr-back-btn' ).prop( 'disabled', false );
			progress.failed( __( 'Import request failed. Please try again.', 'my-book-showroom' ) );
		} );
	} );

	// ── Step 3: Gap card ──────────────────────────────────────────────────────────────────

	/**
	 * Build and insert the per-plugin "what to add after import" card.
	 * Replaces any existing gap card before rendering.
	 * Inserted after #mbs-wxr-mapping-area within the same path container.
	 *
	 * @param {string} sourceKey  Source slug from the analyze response (e.g. "novelist").
	 * @param {string} summary    Human-readable import result summary string.
	 * @returns {void}
	 * @since  1.2.0
	 */
	function renderGapCard( sourceKey, summary ) {
		$( '#mbs-wxr-gap-area' ).remove();

		var data    = GAP_DATA[ sourceKey ] || null;
		var heading = data ? sprintf( __( '%s import complete', 'my-book-showroom' ), data.pluginName ) : __( 'Import complete', 'my-book-showroom' );
		var intro   = data
			? data.successMsg
			: __( 'Your books have been imported. MBS supports additional metadata fields that your previous plugin may not have tracked — take a few minutes to add them and complete each record.', 'my-book-showroom' );

		var $area = $( '<div>' ).attr( 'id', 'mbs-wxr-gap-area' ).css( 'margin-top', '16px' );

		// ── Success banner ───────────────────────────────────────────────────────────────
		var $banner = $( '<div>' ).addClass( 'mbs-wxr-gap-banner' ).css( {
			background:   '#edfaed',
			border:       '1px solid #2e7d32',
			borderRadius: '4px',
			padding:      '12px 16px',
			marginBottom: '16px',
		} );
		$banner.append(
			$( '<strong>' ).css( 'color', '#2e7d32' ).text( '✓ ' + heading )
		);
		$banner.append(
			$( '<span>' ).css( { marginLeft: '8px', color: '#3c434a' } ).text( summary )
		);
		$area.append( $banner );

		// ── Intro paragraph ─────────────────────────────────────────────────────────────
		$area.append( $( '<p>' ).css( { margin: '0 0 12px' } ).text( intro ) );

		// ── Collapsible gap list ────────────────────────────────────────────────────────
		var $toggle = $( '<button>' )
			.attr( 'type', 'button' )
			.addClass( 'button mbs-wxr-gap-toggle' )
			.css( { marginBottom: '10px' } )
			.text( __( 'What to add after import', 'my-book-showroom' ) + ' ▾' );

		var $listWrap = $( '<div>' ).attr( 'id', 'mbs-wxr-gap-list' );

		// Plugin-specific gaps first.
		if ( data && data.specificGaps && data.specificGaps.length ) {
			var $ul = $( '<ul>' ).css( { listStyle: 'disc', paddingLeft: '24px', margin: '0 0 10px' } );
			$.each( data.specificGaps, function ( i, gap ) {
				$ul.append( $( '<li>' ).text( gap ) );
			} );
			$listWrap.append( $ul );
		}

		// Universal MBS gaps.
		$listWrap.append(
			$( '<p>' )
				.css( { fontWeight: '600', margin: '10px 0 6px' } )
				.text( __( 'MBS additional fields (apply to all imports)', 'my-book-showroom' ) )
		);
		var $ulUniversal = $( '<ul>' ).css( { listStyle: 'disc', paddingLeft: '24px', margin: '0 0 10px' } );
		$.each( UNIVERSAL_GAPS, function ( i, gap ) {
			$ulUniversal.append( $( '<li>' ).text( gap ) );
		} );
		$listWrap.append( $ulUniversal );

		// Cover image notice.
		$listWrap.append(
			$( '<p>' )
				.addClass( 'description' )
				.css( { marginTop: '10px', fontStyle: 'italic' } )
				.text( __( 'Cover images import automatically in most cases. If a cover is missing after import, upload it directly to the book record.', 'my-book-showroom' ) )
		);

		$toggle.on( 'click', function () {
			$listWrap.toggle();
			var open = $listWrap.is( ':visible' );
			$( this ).text( __( 'What to add after import', 'my-book-showroom' ) + ' ' + ( open ? '▾' : '▸' ) );
		} );

		$area.append( $toggle );
		$area.append( $listWrap );

		// ── Import more button ────────────────────────────────────────────────────────
		$area.append( $( '<p>' ).css( 'margin-top', '16px' ).append(
			$( '<button>' )
				.attr( { type: 'button', id: 'mbs-wxr-another-btn' } )
				.addClass( 'button' )
				.text( __( 'Import More Books', 'my-book-showroom' ) )
				.on( 'click', function () {
					$( '#mbs-wxr-gap-area' ).remove();
					$( '#mbs-wxr-upload-area' ).show();
				} )
		) );

		// Insert gap area after the mapping area within the same path container.
		$( '#mbs-wxr-mapping-area' ).after( $area );
	}

	// ── Back button ────────────────────────────────────────────────────────────────────────

	$( document ).on( 'click', '#mbs-wxr-back-btn', function () {
		state.token = '';
		progress.reset();
		$( '#mbs-wxr-mapping-area' ).hide();
		$( '#mbs-wxr-upload-area' ).show();
		$( '#mbs-wxr-file' ).val( '' );
	} );

	// ── Helper ──────────────────────────────────────────────────────────────────────────────

	/**
	 * Display a status message in the given element.
	 *
	 * @param {jQuery} $el   Target element.
	 * @param {string} text  Message text.
	 * @param {string} type  "error" | "success" | "info".
	 * @returns {void}
	 * @since  1.0.0
	 */
	function showMsg( $el, text, type ) {
		var colors = { error: '#d63638', success: '#2e7d32', info: '#2271b1' };
		$el.css( 'color', colors[ type ] || colors.info ).text( text ).show();
	}

} )( jQuery );
