/**
 * mbs-broadcast.js -- New Release Broadcast Buttons -- F-026-7/b
 *
 * Handles send, preview, test-send, and retry buttons in the book editor.
 *
 * Localized object: MBS_Broadcast
 *   .ajaxurl    string  WordPress admin-ajax.php URL
 *   .adminEmail string  Site admin email for test-send label
 *   .i18n       object  Translatable strings
 */
( function ( $ ) {
	'use strict';
	var __ = wp.i18n.__;
	var escHtml = MBS_AdminUtils.escHtml;
	var escAttr = MBS_AdminUtils.escAttr;

	// ── Inject modal markup once on ready ────────────────────────────────────
	$( function () {
		if ( $( '#mbs-broadcast-modal-overlay' ).length ) {
			return;
		}
		var modal =
			'<div id="mbs-broadcast-modal-overlay" role="dialog" aria-modal="true" aria-label="' +
			escAttr( __( 'Preview Email', 'my-book-showroom' ) ) + '">' +
			'<div id="mbs-broadcast-modal">' +
			'<div id="mbs-broadcast-modal-header">' +
			'<span>' + escHtml( __( 'Preview Email', 'my-book-showroom' ) ) + '</span>' +
			'<button type="button" id="mbs-broadcast-modal-close" aria-label="' + escAttr( __( 'Close', 'my-book-showroom' ) ) + '">&times;</button>' +
			'</div>' +
			'<div id="mbs-broadcast-modal-body">' +
			'<iframe id="mbs-broadcast-preview-frame" title="Email preview" sandbox="allow-same-origin"></iframe>' +
			'</div>' +
			'<div id="mbs-broadcast-modal-footer">' +
			'<span id="mbs-test-send-result"></span>' +
			'<button type="button" id="mbs-send-test-btn" class="button">' +
			escHtml( __( 'Send Test Email', 'my-book-showroom' ) ) + '</button>' +
			'</div>' +
			'</div>' +
			'</div>';
		$( 'body' ).append( modal );
	} );

	// ── Helpers ───────────────────────────────────────────────────────────────
	function getPanel( $el ) {
		return $el.closest( '#mbs-broadcast-panel, .mbs-broadcast-panel' );
	}
	function getResult( $el ) {
		return getPanel( $el ).find( '.mbs-broadcast-result' );
	}

	// ── Send broadcast ────────────────────────────────────────────────────────
	$( document ).on( 'click', '.mbs-send-broadcast', function () {
		var $btn    = $( this );
		var postId  = $btn.data( 'post-id' );
		var nonce   = $btn.data( 'nonce' );
		var $result = getResult( $btn );

		if ( ! window.confirm( __( 'Send this new release email now? This action cannot be undone.', 'my-book-showroom' ) ) ) {
			return;
		}

		$btn.prop( 'disabled', true ).text( __( 'Sending…', 'my-book-showroom' ) );
		$result.removeClass( 'notice-success notice-error' ).text( '' );

		$.ajax( {
			url:  MBS_Broadcast.ajaxurl,
			type: 'POST',
			data: { action: 'mbs_esp_send_broadcast', post_id: postId, nonce: nonce },
			success: function ( response ) {
				if ( response.success ) {
					$result.addClass( 'notice-success' ).text( response.data.message );
					getPanel( $btn ).find( '.button, .description' ).hide();
				} else {
					var msg = ( response.data && response.data.message )
						? response.data.message : __( 'Something went wrong. Please try again.', 'my-book-showroom' );
					$result.addClass( 'notice-error' ).text( msg );
					$btn.prop( 'disabled', false ).text( __( 'Send New Release Email', 'my-book-showroom' ) );
				}
			},
			error: function () {
				$result.addClass( 'notice-error' ).text( __( 'Something went wrong. Please try again.', 'my-book-showroom' ) );
				$btn.prop( 'disabled', false ).text( __( 'Send New Release Email', 'my-book-showroom' ) );
			},
		} );
	} );

	// ── Retry broadcast ───────────────────────────────────────────────────────
	$( document ).on( 'click', '.mbs-retry-broadcast', function () {
		var $btn    = $( this );
		var postId  = $btn.data( 'post-id' );
		var nonce   = $btn.data( 'nonce' );
		var $result = getResult( $btn );

		$btn.prop( 'disabled', true ).text( __( 'Retrying…', 'my-book-showroom' ) );
		$result.removeClass( 'notice-success notice-error' ).text( '' );

		$.ajax( {
			url:  MBS_Broadcast.ajaxurl,
			type: 'POST',
			data: { action: 'mbs_esp_send_broadcast', post_id: postId, nonce: nonce },
			success: function ( response ) {
				if ( response.success ) {
					$result.addClass( 'notice-success' ).text( response.data.message );
					getPanel( $btn ).find( '.button, .description' ).hide();
				} else {
					var msg = ( response.data && response.data.message )
						? response.data.message : __( 'Something went wrong. Please try again.', 'my-book-showroom' );
					$result.addClass( 'notice-error' ).text( msg );
					$btn.prop( 'disabled', false ).text( __( 'Retry Send', 'my-book-showroom' ) );
				}
			},
			error: function () {
				$result.addClass( 'notice-error' ).text( __( 'Something went wrong. Please try again.', 'my-book-showroom' ) );
				$btn.prop( 'disabled', false ).text( __( 'Retry Send', 'my-book-showroom' ) );
			},
		} );
	} );

	// ── Preview broadcast ─────────────────────────────────────────────────────
	$( document ).on( 'click', '.mbs-preview-broadcast', function () {
		var $btn   = $( this );
		var postId = $btn.data( 'post-id' );
		var nonce  = $btn.data( 'nonce' );

		$btn.prop( 'disabled', true );
		$( '#mbs-test-send-result' ).text( '' ).removeClass( 'mbs-error' );
		$( '#mbs-send-test-btn' ).data( 'post-id', postId ).data( 'nonce', nonce )
			.prop( 'disabled', false ).text( __( 'Send Test Email', 'my-book-showroom' ) );

		$.ajax( {
			url:  MBS_Broadcast.ajaxurl,
			type: 'POST',
			data: { action: 'mbs_esp_preview_broadcast', post_id: postId, nonce: nonce },
			success: function ( response ) {
				$btn.prop( 'disabled', false );
				if ( response.success ) {
					var frame = document.getElementById( 'mbs-broadcast-preview-frame' );
					frame.srcdoc = response.data.html;
					$( '#mbs-broadcast-modal-overlay' ).addClass( 'mbs-modal-open' );
				} else {
					var msg = ( response.data && response.data.message )
						? response.data.message : __( 'Something went wrong. Please try again.', 'my-book-showroom' );
					getResult( $btn ).addClass( 'notice-error' ).text( msg );
				}
			},
			error: function () {
				$btn.prop( 'disabled', false );
				getResult( $btn ).addClass( 'notice-error' ).text( __( 'Something went wrong. Please try again.', 'my-book-showroom' ) );
			},
		} );
	} );

	// ── Close modal ───────────────────────────────────────────────────────────
	$( document ).on( 'click', '#mbs-broadcast-modal-close', function () {
		$( '#mbs-broadcast-modal-overlay' ).removeClass( 'mbs-modal-open' );
	} );
	$( document ).on( 'click', '#mbs-broadcast-modal-overlay', function ( e ) {
		if ( $( e.target ).is( '#mbs-broadcast-modal-overlay' ) ) {
			$( '#mbs-broadcast-modal-overlay' ).removeClass( 'mbs-modal-open' );
		}
	} );
	$( document ).on( 'keydown', function ( e ) {
		if ( 27 === e.which ) {
			$( '#mbs-broadcast-modal-overlay' ).removeClass( 'mbs-modal-open' );
		}
	} );

	// ── Test send from modal ──────────────────────────────────────────────────
	$( document ).on( 'click', '#mbs-send-test-btn', function () {
		var $btn   = $( this );
		var postId = $btn.data( 'post-id' );
		var nonce  = $btn.data( 'nonce' );
		var $msg   = $( '#mbs-test-send-result' );

		$btn.prop( 'disabled', true ).text( __( 'Sending test…', 'my-book-showroom' ) );
		$msg.text( '' ).removeClass( 'mbs-error' );

		$.ajax( {
			url:  MBS_Broadcast.ajaxurl,
			type: 'POST',
			data: { action: 'mbs_esp_send_test_broadcast', post_id: postId, nonce: nonce },
			success: function ( response ) {
				$btn.prop( 'disabled', false ).text( __( 'Send Test Email', 'my-book-showroom' ) );
				if ( response.success ) {
					$msg.text( response.data.message );
				} else {
					var err = ( response.data && response.data.message )
						? response.data.message : __( 'Something went wrong. Please try again.', 'my-book-showroom' );
					$msg.addClass( 'mbs-error' ).text( err );
				}
			},
			error: function () {
				$btn.prop( 'disabled', false ).text( __( 'Send Test Email', 'my-book-showroom' ) );
				$msg.addClass( 'mbs-error' ).text( __( 'Something went wrong. Please try again.', 'my-book-showroom' ) );
			},
		} );
	} );

} )( jQuery );
