/**
 * File Path: assets/js/adminjs/mbs-import-epub.js
 *
 * EPUB Import — Admin JS Module
 *
 * Handles the two-phase EPUB import flow on the Import/Export tab:
 *   Phase 1 — Upload .epub, call mbs_epub_parse, render preview panel.
 *   Phase 2 — User confirms, call mbs_epub_import, redirect to book editor.
 *
 * Depends on: mbs-admin-imp-exp (jQuery, MBS_ImpExp.ajaxurl / nonce).
 *
 * @package MyBookShowroom
 * @since   1.2.0
 */
( function ( $ ) {
	'use strict';
	var __ = wp.i18n.__;
	var sprintf = wp.i18n.sprintf;
	var escHtml = MBS_AdminUtils.escHtml;

	if ( typeof MBS_ImpExp === 'undefined' ) {
		return;
	}

	// ── State ────────────────────────────────────────────────────────────────

	var parsed       = null;   // Payload from Phase 1 parse
	var coverTempKey = '';

	// ── DOM refs (resolved after DOMContentLoaded) ────────────────────────────

	var $panel, $fileInput, $uploadBtn, $status,
	    $previewWrap, $previewTable, $importBtn, $forceBtn, $dupNotice;

	// ── Boot ─────────────────────────────────────────────────────────────────

	$( document ).ready( function () {
		$panel      = $( '#mbs-panel-epub' );
		$fileInput  = $( '#mbs-epub-file' );
		$uploadBtn  = $( '#mbs-epub-upload-btn' );
		$status     = $( '#mbs-epub-status' );
		$previewWrap  = $( '#mbs-epub-preview' );
		$previewTable = $( '#mbs-epub-preview-table' );
		$importBtn  = $( '#mbs-epub-import-btn' );
		$forceBtn   = $( '#mbs-epub-force-btn' );
		$dupNotice  = $( '#mbs-epub-dup-notice' );

		$uploadBtn.on( 'click', handleUpload );
		$importBtn.on( 'click', function () { handleImport( false ); } );
		$forceBtn.on( 'click',  function () { handleImport( true );  } );

		// Allow Enter key on file input to trigger upload.
		$fileInput.on( 'change', function () {
			if ( this.files && this.files.length ) {
				setStatus( '' );
				resetPreview();
			}
		} );
	} );

	// ── Phase 1: Upload + Parse ───────────────────────────────────────────────

	/**
	 * Upload the selected .epub file and request a parsed preview from the server.
	 *
	 * @returns {void}
	 */
	function handleUpload() {
		var file = $fileInput[0] && $fileInput[0].files[0];
		if ( ! file ) {
			setStatus( __( 'Please select an .epub file first.', 'my-book-showroom' ), 'error' );
			return;
		}
		var ext = file.name.split( '.' ).pop().toLowerCase();
		if ( ext !== 'epub' ) {
			setStatus( __( 'Only .epub files are accepted.', 'my-book-showroom' ), 'error' );
			return;
		}

		resetPreview();
		setStatus( __( 'Parsing EPUB…', 'my-book-showroom' ), 'info' );
		$uploadBtn.prop( 'disabled', true );

		var formData = new FormData();
		formData.append( 'action', 'mbs_epub_parse' );
		formData.append( 'nonce',  $fileInput.attr( 'data-nonce' ) || '' );
		formData.append( 'file',   file );

		$.ajax( {
			url:         ajaxurl,
			type:        'POST',
			data:        formData,
			processData: false,
			contentType: false,
			success: function ( res ) {
				$uploadBtn.prop( 'disabled', false );
				if ( ! res.success ) {
					setStatus( ( res.data && res.data.message ) || __( 'Parse failed.', 'my-book-showroom' ), 'error' );
					return;
				}
				parsed       = res.data;
				coverTempKey = parsed.cover_temp_key || '';
				setStatus( __( 'EPUB parsed. Review the details below, then click Import.', 'my-book-showroom' ), 'success' );
				renderPreview( parsed );
			},
			error: function () {
				$uploadBtn.prop( 'disabled', false );
				setStatus( __( 'Server error during parse. Please try again.', 'my-book-showroom' ), 'error' );
			}
		} );
	}

	// ── Phase 2: Import ───────────────────────────────────────────────────────

	/**
	 * Submit the import request using the parsed data payload.
	 *
	 * @param {boolean} force  When true, bypasses duplicate warning.
	 * @returns {void}
	 */
	function handleImport( force ) {
		if ( ! parsed ) {
			setStatus( __( 'Please upload and parse an EPUB file first.', 'my-book-showroom' ), 'error' );
			return;
		}

		setStatus( __( 'Creating book…', 'my-book-showroom' ), 'info' );
		$importBtn.prop( 'disabled', true );
		$forceBtn.prop( 'disabled', true );

		var postData = {
			action:          'mbs_epub_import',
			nonce:           $fileInput.attr( 'data-nonce' ) || '',
			force:           force ? 'true' : 'false',
			title:           parsed.title           || '',
			description:     parsed.description     || '',
			publisher:       parsed.publisher       || '',
			pub_date:        parsed.pub_date        || '',
			language:        parsed.language        || '',
			copyright_year:  parsed.copyright_year  || '',
			lccn:            parsed.lccn            || '',
			isbn13:          parsed.isbn13          || '',
			page_count:      parsed.page_count      || '',
			toc:             parsed.toc             || '',
			contributors:    JSON.stringify( parsed.contributors || [] ),
			bisac_codes:     JSON.stringify( parsed.bisac_codes  || [] ),
			thema_codes:     JSON.stringify( parsed.thema_codes  || [] ),
			bic_codes:       JSON.stringify( parsed.bic_codes    || [] ),
			cover_temp_key:       coverTempKey,
			look_inside_choice:   $previewWrap.find( 'input[name="mbs_li_choice"]:checked' ).val() || 'neither',
		};

		$.post( ajaxurl, postData, function ( res ) {
			$importBtn.prop( 'disabled', false );
			$forceBtn.prop( 'disabled', false );

			if ( ! res.success ) {
				// Duplicate detected — show warning UI.
				if ( res.data && res.data.duplicate && res.data.duplicate.found ) {
					showDuplicateWarning( res.data.duplicate );
					return;
				}
				setStatus( ( res.data && res.data.message ) || __( 'Import failed.', 'my-book-showroom' ), 'error' );
				return;
			}

			// Success — redirect to book editor.
			var editUrl = res.data.edit_url;
			if ( editUrl ) {
				setStatus( __( 'Book created! Redirecting to editor…', 'my-book-showroom' ), 'success' );
				window.location.href = editUrl;
			} else {
				setStatus( __( 'Book created.', 'my-book-showroom' ), 'success' );
			}
		} ).fail( function () {
			$importBtn.prop( 'disabled', false );
			$forceBtn.prop( 'disabled', false );
			setStatus( __( 'Server error during import. Please try again.', 'my-book-showroom' ), 'error' );
		} );
	}

	// ── Preview rendering ─────────────────────────────────────────────────────

	/**
	 * Render the parsed EPUB data into the preview table.
	 *
	 * @param {Object} d  Parsed data payload from Phase 1.
	 * @returns {void}
	 */
	function renderPreview( d ) {
		var rows = [];

		if ( d.cover_temp_url ) {
			rows.push( row( escHtml( __( 'Cover', 'my-book-showroom' ) ), '<img src="' + MBS_ImpExpUtils.esc( d.cover_temp_url ) + '" alt="' + escHtml( __( 'Cover', 'my-book-showroom' ) ) + '" style="max-height:120px;max-width:90px;border:1px solid #ddd;">' ) );
		}

		rows.push( row( escHtml( __( 'Title', 'my-book-showroom' ) ),            MBS_ImpExpUtils.esc( d.title ) ) );
		rows.push( row( escHtml( __( 'Description', 'my-book-showroom' ) ),      '<div style="max-height:80px;overflow:auto;">' + MBS_ImpExpUtils.esc( d.description ) + '</div>' ) );
		rows.push( row( escHtml( __( 'Publisher', 'my-book-showroom' ) ),        MBS_ImpExpUtils.esc( d.publisher ) ) );
		rows.push( row( escHtml( __( 'Publication Date', 'my-book-showroom' ) ), MBS_ImpExpUtils.esc( d.pub_date ) ) );
		rows.push( row( escHtml( __( 'Language', 'my-book-showroom' ) ),         MBS_ImpExpUtils.esc( d.language ) ) );
		rows.push( row( escHtml( __( 'Copyright Year', 'my-book-showroom' ) ),   MBS_ImpExpUtils.esc( d.copyright_year ) ) );

		// Identifiers
		rows.push( row( escHtml( __( 'ISBN-13 (EPUB)', 'my-book-showroom' ) ),   MBS_ImpExpUtils.esc( d.isbn13 ) ) );
		var lccnDisplay = d.lccn;
		if ( d.lc_url ) {
			lccnDisplay += ' <a href="' + MBS_ImpExpUtils.esc( d.lc_url ) + '" target="_blank" rel="noreferrer">'  + escHtml( __( '[LC record]', 'my-book-showroom' ) ) + '</a>';
		}
		rows.push( row( escHtml( __( 'LCCN', 'my-book-showroom' ) ), lccnDisplay ) );

		// Production
		rows.push( row( escHtml( __( 'Trim Size', 'my-book-showroom' ) ),   MBS_ImpExpUtils.esc( d.trim_size ) ) );
		rows.push( row( escHtml( __( 'Page Count', 'my-book-showroom' ) ),  MBS_ImpExpUtils.esc( d.page_count ) ) );

		// Series
		var seriesDisplay = MBS_ImpExpUtils.esc( d.series_name );
		if ( d.series_num ) {			seriesDisplay += ' ' + sprintf( __( '(Book %s)', 'my-book-showroom' ), MBS_ImpExpUtils.esc( d.series_num ) ) + ' <em style="color:#888;font-size:11px;">' + escHtml( __( '(assign in editor)', 'my-book-showroom' ) ) + '</em>';		}		rows.push( row( escHtml( __( 'Series', 'my-book-showroom' ) ), seriesDisplay ) );

		// Contributors
		if ( d.contributors && d.contributors.length ) {
			var contribHtml = d.contributors.map( function ( c ) {
				return MBS_ImpExpUtils.esc( c.name ) + ' <span style="color:#888;">(' + MBS_ImpExpUtils.esc( c.label ) + ')</span>';
			} ).join( '<br>' );
			rows.push( row( escHtml( __( 'Contributors', 'my-book-showroom' ) ), contribHtml ) );
		}

		// Table of Contents
		if ( d.toc ) {
			var tocLines = d.toc.split( '\n' );
			var tocPreview = tocLines.slice( 0, 5 ).map( MBS_ImpExpUtils.esc ).join( '<br>' );
			if ( tocLines.length > 5 ) {
				tocPreview += '<br><em style="color:#888;">' + escHtml( sprintf( __( '+ %d more', 'my-book-showroom' ), tocLines.length - 5 ) ) + '</em>';
			}
			rows.push( row( escHtml( sprintf( __( 'Table of Contents (%d)', 'my-book-showroom' ), tocLines.length ) ), tocPreview ) );
		}

		// Classification codes
		if ( d.bisac_codes && d.bisac_codes.length ) {
			rows.push( row( escHtml( __( 'BISAC Codes', 'my-book-showroom' ) ), d.bisac_codes.map( MBS_ImpExpUtils.esc ).join( ', ' ) ) );
		}
		if ( d.bic_codes && d.bic_codes.length ) {
			rows.push( row( escHtml( __( 'BIC Codes', 'my-book-showroom' ) ), d.bic_codes.map( MBS_ImpExpUtils.esc ).join( ', ' ) ) );
		}
		if ( d.thema_codes && d.thema_codes.length ) {
			rows.push( row( escHtml( __( 'THEMA Codes', 'my-book-showroom' ) ), d.thema_codes.map( MBS_ImpExpUtils.esc ).join( ', ' ) ) );
		}

		// Other format ISBNs (reference table — manual entry in editor)
		if ( d.other_isbns && d.other_isbns.length ) {
			var isbnRows = d.other_isbns.map( function ( i ) {
				return '<tr><td>' + MBS_ImpExpUtils.esc( i.label ) + '</td><td><code>' + MBS_ImpExpUtils.esc( i.isbn ) + '</code></td></tr>';
			} ).join( '' );
			var isbnTable = '<table style="border-collapse:collapse;font-size:12px;">'
				+ '<tr><th style="text-align:left;padding-right:16px;">' + escHtml( __( 'Format', 'my-book-showroom' ) ) + '</th><th style="text-align:left;">' + escHtml( __( 'ISBN-13', 'my-book-showroom' ) ) + '</th></tr>'
				+ isbnRows + '</table>'
				+ '<em style="color:#888;font-size:11px;">' + escHtml( __( 'Add these manually via the Format Rows metabox.', 'my-book-showroom' ) ) + '</em>';
			rows.push( row( escHtml( __( 'Other Format ISBNs', 'my-book-showroom' ) ), isbnTable ) );
		}

		// Preview-only fields
		if ( d.pub_address ) {
			rows.push( row( escHtml( __( 'Publisher Address', 'my-book-showroom' ) ) + ' <em style="color:#888;font-size:11px;">' + escHtml( __( '(preview only)', 'my-book-showroom' ) ) + '</em>', MBS_ImpExpUtils.esc( d.pub_address ) ) );
		}
		if ( d.cover_artist ) {
			rows.push( row( escHtml( __( 'Cover Artist', 'my-book-showroom' ) ) + ' <em style="color:#888;font-size:11px;">' + escHtml( __( '(preview only)', 'my-book-showroom' ) ) + '</em>', MBS_ImpExpUtils.esc( d.cover_artist ) ) );
		}

		// Look Inside labels (candidate HTML stored server-side in transient; never sent to browser)
		if ( d.look_inside_labels && d.look_inside_labels.length ) {
			var liHtml = '';
			d.look_inside_labels.forEach( function( label, i ) {
				liHtml += '<label><input type="radio" name="mbs_li_choice" value="'
					+ MBS_ImpExpUtils.esc( label ) + '"' + ( i === 0 ? ' checked' : '' ) + '> '
					+ MBS_ImpExpUtils.esc( label ) + ' ' + escHtml( __( '(detected)', 'my-book-showroom' ) ) + '</label> ';
			} );
			liHtml += '<label><input type="radio" name="mbs_li_choice" value="neither">'
				+ ' ' + escHtml( __( 'Neither — enter manually', 'my-book-showroom' ) ) + '</label>';
			rows.push( row( escHtml( __( 'Look Inside', 'my-book-showroom' ) ), liHtml ) );
		} else {
			rows.push( row( escHtml( __( 'Look Inside', 'my-book-showroom' ) ), '<em style="color:#888;">' + escHtml( __( 'No Prologue or Chapter 1 detected — enter manually in book editor.', 'my-book-showroom' ) ) + '</em>' ) );
		}

		$previewTable.html( rows.join( '' ) );

		// Duplicate warning
		$dupNotice.hide();
		$forceBtn.hide();
		if ( d.duplicate && d.duplicate.found ) {
			showDuplicateWarning( d.duplicate );
		} else {
			$importBtn.show().prop( 'disabled', false );
		}

		$previewWrap.show();
	}

	/**
	 * Display the duplicate-detected notice and action buttons.
	 *
	 * @param {Object} dup  Duplicate info: { found, type, post_id, edit_url }
	 * @returns {void}
	 */
	function showDuplicateWarning( dup ) {
		var typeLabel = dup.type === 'isbn13' ? __( 'ISBN-13', 'my-book-showroom' ) : __( 'title', 'my-book-showroom' );
		var msg = escHtml( sprintf( __( 'A book with the same %s already exists.', 'my-book-showroom' ), typeLabel ) );
		if ( dup.edit_url ) {
			msg += ' <a href="' + MBS_ImpExpUtils.esc( dup.edit_url ) + '" target="_blank">' + escHtml( __( 'Edit existing book', 'my-book-showroom' ) ) + '</a>';
		}
		$dupNotice.html( msg ).show();
		$importBtn.hide();
		$forceBtn.show().prop( 'disabled', false );
	}

	// ── Utility ───────────────────────────────────────────────────────────────

	/**
	 * Build a two-column table row.
	 *
	 * @param {string} label  Row label (may contain safe HTML).
	 * @param {string} value  Row value (may contain safe HTML).
	 * @returns {string} HTML string.
	 */
	function row( label, value ) {
		if ( ! value || value === '' ) {
			return '';
		}
		return '<tr>'
			+ '<th style="text-align:left;padding:4px 12px 4px 0;vertical-align:top;white-space:nowrap;font-weight:600;">' + label + '</th>'
			+ '<td style="padding:4px 0;vertical-align:top;">' + value + '</td>'
			+ '</tr>';
	}

	/**
	 * HTML-escape a value for safe output. Returns empty string for falsy input.
	 *
	 * @param {*} val
	 * @returns {string}
	 */
	/**
	 * Show or clear the status message area.
	 *
	 * @param {string} msg   Message to show (empty string clears).
	 * @param {string} type  'info' | 'success' | 'error'
	 * @returns {void}
	 */
	function setStatus( msg, type ) {
		if ( ! msg ) {
			$status.hide().text( '' );
			return;
		}
		window.MBS_ImpExpUtils.mbsShowPanelMessage( 'mbs-epub-status', msg, type || 'info' );
	}

	/**
	 * Hide and empty the preview panel.
	 *
	 * @returns {void}
	 */
	function resetPreview() {
		$previewWrap.hide();
		$previewTable.empty();
		$importBtn.hide();
		$forceBtn.hide();
		$dupNotice.hide().empty();
		parsed = null;
	}

} )( jQuery );
