/**
 * admin-look-inside.js
 *
 * Look Inside admin UX: DOCX upload flow, TinyMCE re-init on tab switch,
 * and live word count.
 *
 * Handle:     mbs-admin-look-inside
 * Dependency: mbs-book-editor
 * Localized:  MBS_LookInsideAjax (PRO only) -- { ajaxUrl, nonce, isPro, i18n }
 *
 * @package My_Book_Showroom
 * @since   4.20
 */
( function ( $ ) {
	'use strict';
	var __ = wp.i18n.__;

	// ── DOCX upload flow (PRO only) ─────────────────────────────────────────────
	if ( typeof MBS_LookInsideAjax !== 'undefined' && MBS_LookInsideAjax.isPro ) {
		var $fileInput = $( '#mbs-docx-file-input' );

		$( '#mbs-docx-upload-btn' ).on( 'click', function () {
			$fileInput.trigger( 'click' );
		} );

		$fileInput.on( 'change', function () {
			var file = this.files && this.files[ 0 ];
			if ( ! file ) {
				return;
			}

			// Capture file in closure so overwrite resubmission can resend
			// the same File object without re-triggering the file chooser.
			function doUpload( confirmed ) {
				var fd = new FormData();
				fd.append( 'action', 'mbs_extract_docx_look_inside' );
				fd.append( 'nonce', MBS_LookInsideAjax.nonce );
				fd.append( 'post_id', $( '#post_ID' ).val() );
				fd.append( 'file', file );
				if ( confirmed ) {
					fd.append( 'confirmed_overwrite', 'true' );
				}

				$( '#mbs-docx-status' ).text( __( 'Uploading...', 'my-book-showroom' ) );

				$.ajax( {
					url:         MBS_LookInsideAjax.ajaxUrl,
					type:        'POST',
					data:        fd,
					processData: false,
					contentType: false,
					success: function ( response ) {
						if ( ! response.success ) {
							$( '#mbs-docx-status' ).text( response.data.message || __( 'Upload error.', 'my-book-showroom' ) );
							return;
						}
						if ( response.data.overwrite_required ) {
							if ( window.confirm( __( 'This book already has Look Inside text. Replace it?', 'my-book-showroom' ) ) ) {
								doUpload( true );
							} else {
								$( '#mbs-docx-status' ).text( '' );
							}
							return;
						}
						var editor = tinymce.get( 'mbs_look_inside_text' );
						if ( editor ) {
							editor.setContent( response.data.html );
						} else {
							document.getElementById( 'mbs_look_inside_text' ).value = response.data.html;
						}
						$( '#mbs-look-inside-wc' ).text( Math.min( response.data.word_count, 6000 ) );
						if ( response.data.truncated ) {
							$( '#mbs-docx-status' ).text( __( 'Content was truncated to 6,000 words.', 'my-book-showroom' ) );
						} else {
							$( '#mbs-docx-status' ).text( '' );
						}
					},
					error: function ( xhr ) {
						// 403 (tier/capability) errors carry a message in responseJSON.data.message.
						var msg = xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message
							? xhr.responseJSON.data.message
							: __( 'Upload failed. Please try again.', 'my-book-showroom' );
						$( '#mbs-docx-status' ).text( msg );
					}
				} );
			}

			doUpload( false );
		} );
	}

	// ── EPUB upload flow (PRO only) ──────────────────────────────────────────────
	if ( typeof MBS_LookInsideAjax !== 'undefined' && MBS_LookInsideAjax.isPro ) {
		var $epubFileInput = $( '#mbs-epub-file-input' );

		$( '#mbs-epub-upload-btn' ).on( 'click', function () {
			$epubFileInput.trigger( 'click' );
		} );

		$epubFileInput.on( 'change', function () {
			var file = this.files && this.files[ 0 ];
			if ( ! file ) {
				return;
			}

			function doEpubUpload( confirmed ) {
				var fd = new FormData();
				fd.append( 'action', 'mbs_extract_epub_look_inside' );
				fd.append( 'nonce', MBS_LookInsideAjax.nonce );
				fd.append( 'post_id', $( '#post_ID' ).val() );
				fd.append( 'file', file );
				if ( confirmed ) {
					fd.append( 'confirmed_overwrite', 'true' );
				}

				$( '#mbs-epub-status' ).text( __( 'Uploading...', 'my-book-showroom' ) );

				$.ajax( {
					url:         MBS_LookInsideAjax.ajaxUrl,
					type:        'POST',
					data:        fd,
					processData: false,
					contentType: false,
					success: function ( response ) {
						if ( ! response.success ) {
							$( '#mbs-epub-status' ).text( response.data.message || __( 'Upload error.', 'my-book-showroom' ) );
							return;
						}
						if ( response.data.overwrite_required ) {
							if ( window.confirm( __( 'This book already has Look Inside text. Replace it?', 'my-book-showroom' ) ) ) {
								doEpubUpload( true );
							} else {
								$( '#mbs-epub-status' ).text( '' );
							}
							return;
						}
						var editor = tinymce.get( 'mbs_look_inside_text' );
						if ( editor ) {
							editor.setContent( response.data.html );
						} else {
							document.getElementById( 'mbs_look_inside_text' ).value = response.data.html;
						}
						$( '#mbs-look-inside-wc' ).text( Math.min( response.data.word_count, 6000 ) );
						if ( response.data.truncated ) {
							$( '#mbs-epub-status' ).text( __( 'Content was truncated to 6,000 words.', 'my-book-showroom' ) );
						} else {
							$( '#mbs-epub-status' ).text( '' );
						}
					},
					error: function ( xhr ) {
						var msg = xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message
							? xhr.responseJSON.data.message
							: __( 'Upload failed. Please try again.', 'my-book-showroom' );
						$( '#mbs-epub-status' ).text( msg );
					}
				} );
			}

			doEpubUpload( false );
		} );
	}

	// ── TinyMCE re-init on Book Details tab activation ───────────────────────────
	// The book editor shell routes all tab switches through window.hashchange
	// (hash format: #domain-key/section-key). location.hash includes the leading #,
	// so the check must be indexOf('#book-details/') === 0.
	$( window ).on( 'hashchange', function () {
		if ( location.hash.indexOf( '#book-details/' ) === 0 ) {
			if ( typeof tinymce !== 'undefined' ) {
				if ( tinymce.get( 'mbs_look_inside_text' ) ) {
					tinymce.get( 'mbs_look_inside_text' ).show();
				} else {
					tinymce.execCommand( 'mceAddEditor', true, 'mbs_look_inside_text' );
				}
			}
		}
	} );

	// ── Live word count (TinyMCE AddEditor callback) ─────────────────────────────
	// Binding must be inside AddEditor callback -- editor does not exist at load time.
	if ( typeof tinymce !== 'undefined' ) {
		tinymce.on( 'AddEditor', function ( e ) {
			if ( e.editor.id !== 'mbs_look_inside_text' ) {
				return;
			}
			e.editor.on( 'keyup change', function () {
				var text  = e.editor.getContent( { format: 'text' } );
				var words = text.trim() ? text.trim().split( /\s+/ ).length : 0;
				var el    = document.getElementById( 'mbs-look-inside-wc' );
				if ( el ) {
					el.textContent = Math.min( words, 6000 );
				}
			} );
		} );
	}

} )( jQuery );
