/**
 * File Path: assets/js/adminjs/mbs-tutorial-admin.js
 *
 * MBS Tutorial Data Admin -- Dashboard Panel JS
 *
 * Drives the Tutorial Data panel on the MBS dashboard (install / reinstall /
 * uninstall actions). Uses MBSImportProgress for the install / reinstall
 * vanishing-message progress UX; the uninstall flow uses a simple inline
 * notice instead of a progress bar.
 *
 * AJAX actions consumed:
 *   mbs_tutorial_install       -- calls MBS_Tutorial_Importer::run()
 *   mbs_tutorial_reinstall     -- uninstall + install in sequence
 *   mbs_tutorial_uninstall     -- calls MBS_Tutorial_Uninstaller::run()
 *   mbs_tutorial_poll_progress -- returns current progress transient data
 *
 * Poll response shape (mbs_tutorial_poll_progress):
 *   { step, message, pct, book_num?, total?, post_id?, title? }
 *
 * Depends on: MBSImportProgress (mbs-import-progress.js).
 * Data: mbsTutorial (wp_localize_script).
 *
 * @package MyBookShowroom
 * @since   2.1.0
 */

/* global MBSImportProgress, window */
( function () {
	'use strict';

	// -------------------------------------------------------------------------
	// Config / i18n (provided by wp_localize_script)
	// -------------------------------------------------------------------------
	var cfg = window.mbsTutorial || {};

	var i18n = {
		confirm    : cfg.i18nConfirm    || 'Remove all tutorial books, media, and terms? This cannot be undone.',
		failed     : cfg.i18nFailed     || 'Request failed. Please try again.',
		error      : cfg.i18nError      || 'An error occurred.',
		starting   : cfg.i18nStarting   || 'Starting\u2026',
		removing   : cfg.i18nRemoving   || 'Removing tutorial data\u2026',
		installed  : cfg.i18nInstalled  || 'Tutorial successfully installed. \u2713',
		installing : cfg.i18nInstalling || 'Installing',
		of         : cfg.i18nOf         || 'of',
	};

	// -------------------------------------------------------------------------
	// State
	// -------------------------------------------------------------------------
	var progress  = null;
	var pollTimer = null;

	// -------------------------------------------------------------------------
	// Helpers
	// -------------------------------------------------------------------------

	/**
	 * Escape HTML for safe innerHTML insertion.
	 *
	 * @param  {string} text
	 * @return {string}
	 */
	function escHtml( text ) {
		return String( text )
			.replace( /&/g, '&amp;' )
			.replace( /</g, '&lt;' )
			.replace( />/g, '&gt;' )
			.replace( /"/g, '&quot;' );
	}

	/**
	 * Build a FormData object for an AJAX action.
	 *
	 * @param  {string} action  AJAX action name.
	 * @return {FormData}
	 */
	function buildForm( action ) {
		var fd = new FormData();
		fd.append( 'action', action );
		fd.append( 'nonce',  cfg.nonce );
		return fd;
	}

	/**
	 * Enable or disable all tutorial action buttons.
	 *
	 * @param {boolean} disabled
	 */
	function disableBtns( disabled ) {
		document.querySelectorAll( '.mbs-tutorial-btn' ).forEach( function ( b ) {
			b.disabled = disabled;
		} );
	}

	// -------------------------------------------------------------------------
	// Progress polling (install / reinstall only)
	// -------------------------------------------------------------------------

	/**
	 * Start a 600 ms polling interval that reads the progress transient and
	 * updates MBSImportProgress. Returns the interval ID.
	 *
	 * @return {number}
	 */
	function startPoll() {
		return setInterval( function () {
			fetch( cfg.ajaxUrl, {
				method     : 'POST',
				body       : buildForm( 'mbs_tutorial_poll_progress' ),
				credentials: 'same-origin',
			} )
			.then( function ( r ) { return r.json(); } )
			.then( function ( d ) {
				if ( ! d.success || ! d.data || d.data.pct <= 0 ) {
					return;
				}
				progress.setBar( d.data.pct );
				if ( 'book' === d.data.step && d.data.title ) {
					progress.setMessage(
						'\u201c' + d.data.title + '\u201d \u2014 ' +
						i18n.installing + ' ' +
						d.data.book_num + ' ' + i18n.of + ' ' + d.data.total
					);
				} else if ( d.data.message ) {
					progress.setMessage( d.data.message );
				}
			} )
			.catch( function () {} );
		}, 600 );
	}

	/**
	 * Stop the poll interval if running.
	 */
	function stopPoll() {
		if ( pollTimer ) {
			clearInterval( pollTimer );
			pollTimer = null;
		}
	}

	// -------------------------------------------------------------------------
	// Uninstall notice helpers (no progress module for uninstall)
	// -------------------------------------------------------------------------

	var resultDiv = null;

	/**
	 * Show a simple notice in the result area (used for uninstall flow).
	 *
	 * @param {string} msg
	 * @param {string} type  'info' | 'success' | 'error'
	 */
	function showResult( msg, type ) {
		if ( ! resultDiv ) { return; }
		resultDiv.className = 'notice notice-' + type;
		resultDiv.innerHTML = '<p>' + escHtml( msg ) + '</p>';
		resultDiv.style.display = 'block';
	}

	// -------------------------------------------------------------------------
	// Click handler
	// -------------------------------------------------------------------------

	document.addEventListener( 'DOMContentLoaded', function () {
		resultDiv = document.getElementById( 'mbs-tutorial-result' );

		progress = MBSImportProgress.create( {
			barWrap    : document.getElementById( 'mbs-tutorial-progress-bar' ),
			barFill    : document.getElementById( 'mbs-tutorial-bar' ),
			msgArea    : document.getElementById( 'mbs-tutorial-msgarea' ),
			statusArea : resultDiv,
		} );

		document.querySelectorAll( '.mbs-tutorial-btn' ).forEach( function ( btn ) {
			btn.addEventListener( 'click', function () {
				var action    = btn.getAttribute( 'data-action' );
				var isInstall = ( 'mbs_tutorial_install'   === action ||
				                  'mbs_tutorial_reinstall' === action );

				if ( 'mbs_tutorial_uninstall' === action ) {
					if ( ! window.confirm( i18n.confirm ) ) { return; }
				}

				disableBtns( true );
				progress.reset();
				if ( resultDiv ) {
					resultDiv.style.display = 'none';
					resultDiv.innerHTML     = '';
				}

				if ( isInstall ) {
					progress.show();
					// Show bar for install/reinstall.
					var barWrapEl = document.getElementById( 'mbs-tutorial-progress-bar' );
					if ( barWrapEl ) { barWrapEl.style.display = 'block'; }
					progress.setBar( 2 );
					progress.setMessage( i18n.starting );
					pollTimer = startPoll();
				} else {
					// Uninstall: simple notice, no progress bar.
					showResult( i18n.removing, 'info' );
				}

				fetch( cfg.ajaxUrl, {
					method     : 'POST',
					body       : buildForm( action ),
					credentials: 'same-origin',
				} )
				.then( function ( r ) { return r.json(); } )
				.then( function ( data ) {
					stopPoll();
					var msg = data.data && data.data.message
						? data.data.message
						: ( data.success ? i18n.installed : i18n.error );

					if ( isInstall ) {
						if ( data.success ) {
							progress.complete( i18n.installed );
							setTimeout( function () { location.reload(); }, 2500 );
						} else {
							progress.failed( msg );
							disableBtns( false );
						}
					} else {
						// Uninstall complete.
						disableBtns( false );
						if ( data.success ) {
							showResult( msg, 'success' );
							setTimeout( function () { location.reload(); }, 1500 );
						} else {
							showResult( msg, 'error' );
						}
					}
				} )
				.catch( function () {
					stopPoll();
					disableBtns( false );
					if ( isInstall ) {
						progress.failed( i18n.failed );
					} else {
						showResult( i18n.failed, 'error' );
					}
				} );
			} );
		} );
	} );

} )();
