<?php
/**
 * Customize WP Emails - System Emails Page
 * PowerSuite style: header row, card panels, buttons.
 *
 * @var array $emails
 * @var array $settings
 * @var array $defaults
 * @var string|null $edit_email_id
 * @var array|null $edit_email_meta
 * @var array|null $edit_smartcodes
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use WP_PowerSuite\Admin\PageHero;
use WP_PowerSuite\Core\NetworkScope;

$list_url     = NetworkScope::adminUrl( 'admin.php', [ 'page' => 'powersuite-custom-wp-emails' ] );
$template_url = NetworkScope::adminUrl( 'admin.php', [ 'page' => 'powersuite-custom-wp-emails', 'tab' => 'template' ] );
$emails_by_recipient = [
	'user'       => [],
	'site_admin' => [],
];
foreach ( $emails as $id => $meta ) {
	$recipient = $meta['recipient'] ?? 'user';
	$emails_by_recipient[ $recipient ][ $id ] = $meta;
}
?>
<div class="wrap wpps-cwe-wrap">
	<hr class="wp-header-end" style="margin:0;padding:0;border:none;height:0;overflow:hidden;">

	<?php if ( isset( $_GET['saved'] ) ) : ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Email settings saved.', 'wp-powersuite' ); ?></p></div>
	<?php endif; ?>
	<?php if ( isset( $_GET['error'] ) && sanitize_key( wp_unslash( $_GET['error'] ) ) === 'required_smartcode' ) : ?>
		<div class="notice notice-error"><p><?php esc_html_e( 'Save failed: a required security placeholder is missing from the subject or body. Password reset and email-change templates must include their confirmation link placeholders.', 'wp-powersuite' ); ?></p></div>
	<?php elseif ( isset( $_GET['error'] ) ) : ?>
		<div class="notice notice-error"><p><?php esc_html_e( 'An error occurred. Please try again.', 'wp-powersuite' ); ?></p></div>
	<?php endif; ?>

	<?php if ( $edit_email_id && $edit_email_meta ) : ?>
		<?php
		$email_setting = $settings['emails'][ $edit_email_id ] ?? [];
		$status = $email_setting['status'] ?? 'system';
		$email_data = $email_setting['email'] ?? [];
		$subject = $email_data['subject'] ?? ( $defaults[ $edit_email_id ]['email']['subject'] ?? '' );
		$body = $email_data['body'] ?? ( $defaults[ $edit_email_id ]['email']['body'] ?? '' );
		$recipient_label = ( $edit_email_meta['recipient'] ?? 'user' ) === 'site_admin' ? __( 'Site Admin', 'wp-powersuite' ) : __( 'User', 'wp-powersuite' );
		?>
		<?php
		PageHero::render_for_module(
			[
				'icon'    => 'dashicons-email-alt',
				'title'   => sprintf(
					/* translators: 1: recipient label, 2: email title */
					__( 'To: %1$s %2$s', 'wp-powersuite' ),
					$recipient_label,
					$edit_email_meta['title'] ?? $edit_email_id
				),
				'tagline' => (string) ( $edit_email_meta['description'] ?? '' ),
				'actions' => [
					[
						'label' => __( 'All emails', 'wp-powersuite' ),
						'url'   => $list_url,
						'icon'  => 'dashicons-arrow-left-alt',
					],
					[
						'label' => __( 'Template Design', 'wp-powersuite' ),
						'url'   => $template_url,
						'icon'  => 'dashicons-admin-appearance',
					],
				],
			]
		);
		?>

		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="wpps-cwe-email-form" data-email-id="<?php echo esc_attr( $edit_email_id ); ?>" data-wpps-unsaved-form="1">
			<input type="hidden" name="action" value="wpps_custom_wp_emails_save_email" />
			<input type="hidden" name="email_id" value="<?php echo esc_attr( $edit_email_id ); ?>" />
			<input type="hidden" name="return_to_edit" value="<?php echo esc_attr( $edit_email_id ); ?>" />
			<?php wp_nonce_field( 'wpps_custom_wp_emails_email' ); ?>

			<div class="wpps-cwe-panel">
				<h2 class="wpps-cwe-section-title"><?php esc_html_e( 'Email Content Status', 'wp-powersuite' ); ?></h2>
				<p>
					<label><input type="radio" name="status" value="active" <?php checked( $status, 'active' ); ?> /> <?php esc_html_e( 'Customized Content', 'wp-powersuite' ); ?></label>
					&nbsp;&nbsp;
					<label><input type="radio" name="status" value="system" <?php checked( $status, 'system' ); ?> /> <?php esc_html_e( 'System Default', 'wp-powersuite' ); ?></label>
					<?php if ( ! empty( $edit_email_meta['can_disable'] ) ) : ?>
					&nbsp;&nbsp;
					<label><input type="radio" name="status" value="disabled" <?php checked( $status, 'disabled' ); ?> /> <?php esc_html_e( 'Disabled', 'wp-powersuite' ); ?></label>
					<?php endif; ?>
				</p>
				<div id="wpps-system-default-info" class="wpps-cwe-notice-box" style="display:<?php echo $status === 'system' ? 'block' : 'none'; ?>;">
					<strong><?php esc_html_e( 'System Default', 'wp-powersuite' ); ?></strong> <?php esc_html_e( 'This email will use the system default content. If you want to customize the email subject and body please switch to Customized Content.', 'wp-powersuite' ); ?>
				</div>
				<div id="wpps-disabled-info" class="wpps-cwe-notice-box" style="display:<?php echo $status === 'disabled' ? 'block' : 'none'; ?>;">
					<strong><?php esc_html_e( 'Disabled', 'wp-powersuite' ); ?></strong> <?php esc_html_e( 'This email will not be sent.', 'wp-powersuite' ); ?>
				</div>
				<div id="wpps-customized-fields" style="display:<?php echo $status === 'active' ? 'block' : 'none'; ?>;">
					<table class="form-table">
						<tr>
							<th scope="row"><?php esc_html_e( 'Email Subject', 'wp-powersuite' ); ?></th>
							<td>
								<div style="display:flex;gap:8px;align-items:center;">
									<input type="text" name="subject" value="<?php echo esc_attr( $subject ); ?>" class="large-text wpps-cwe-input" style="flex:1;" />
									<button type="button" class="button button-secondary wpps-smartcode-trigger" data-target="subject" data-email-id="<?php echo esc_attr( $edit_email_id ); ?>">+ <?php esc_html_e( 'SmartCode', 'wp-powersuite' ); ?></button>
								</div>
							</td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e( 'Email Body', 'wp-powersuite' ); ?></th>
							<td>
								<?php
								wp_editor(
									$body,
									'body_' . $edit_email_id,
									[
										'textarea_name' => 'body',
										'textarea_rows' => 14,
										'media_buttons' => true,
										'teeny'         => false,
										'quicktags'     => true,
										'tinymce'       => [ 'toolbar1' => 'formatselect,bold,italic,link,blockquote,bullist,numlist,alignleft,aligncenter,alignright' ],
									]
								);
								?>
							</td>
						</tr>
					</table>
					<div class="wpps-cwe-actions">
						<div class="wpps-cwe-actions-left">
							<button type="button" class="button button-secondary wpps-set-default" data-email-id="<?php echo esc_attr( $edit_email_id ); ?>"><?php esc_html_e( 'Get Default Subject & Body', 'wp-powersuite' ); ?></button>
							<button type="button" class="button button-secondary wpps-preview-email" data-email-id="<?php echo esc_attr( $edit_email_id ); ?>"><?php esc_html_e( 'Preview Email', 'wp-powersuite' ); ?></button>
							<button type="button" class="button button-secondary wpps-send-test-email" data-email-id="<?php echo esc_attr( $edit_email_id ); ?>"><?php esc_html_e( 'Send Test Email', 'wp-powersuite' ); ?></button>
						</div>
						<button type="submit" class="button button-primary"><?php esc_html_e( 'Save Settings', 'wp-powersuite' ); ?></button>
					</div>
				</div>
				<div class="wpps-cwe-actions" id="wpps-save-row-system" style="display:<?php echo ( $status === 'system' || $status === 'disabled' ) ? 'flex' : 'none'; ?>;">
					<button type="submit" class="button button-primary"><?php esc_html_e( 'Save Settings', 'wp-powersuite' ); ?></button>
				</div>
			</div>
		</form>

		<?php
		$user_smartcodes  = [];
		$site_smartcodes  = [];
		foreach ( $edit_smartcodes ?? [] as $code => $label ) {
			if ( strpos( $code, 'user.' ) !== false || strpos( $code, 'user_' ) !== false ) {
				$user_smartcodes[ $code ] = $label;
			} else {
				$site_smartcodes[ $code ] = $label;
			}
		}
		?>
		<div id="wpps-smartcode-panel" class="wpps-cwe-smartcode-panel">
			<div class="wpps-cwe-smartcode-panel-tabs">
				<button type="button" class="wpps-cwe-smartcode-tab is-active" data-tab="user"><?php esc_html_e( 'User Data', 'wp-powersuite' ); ?></button>
				<button type="button" class="wpps-cwe-smartcode-tab" data-tab="site"><?php esc_html_e( 'Site Data', 'wp-powersuite' ); ?></button>
			</div>
			<div class="wpps-cwe-smartcode-panel-content">
				<div class="wpps-cwe-smartcode-tab-pane is-active" data-pane="user">
					<?php foreach ( $user_smartcodes as $code => $label ) : ?>
						<button type="button" class="wpps-cwe-smartcode-item" data-code="<?php echo esc_attr( $code ); ?>">
							<span class="wpps-cwe-smartcode-label"><?php echo esc_html( $label ); ?></span>
							<code class="wpps-cwe-smartcode-code"><?php echo esc_html( $code ); ?></code>
						</button>
					<?php endforeach; ?>
				</div>
				<div class="wpps-cwe-smartcode-tab-pane" data-pane="site">
					<?php foreach ( $site_smartcodes as $code => $label ) : ?>
						<button type="button" class="wpps-cwe-smartcode-item" data-code="<?php echo esc_attr( $code ); ?>">
							<span class="wpps-cwe-smartcode-label"><?php echo esc_html( $label ); ?></span>
							<code class="wpps-cwe-smartcode-code"><?php echo esc_html( $code ); ?></code>
						</button>
					<?php endforeach; ?>
				</div>
			</div>
		</div>
	<?php else : ?>
		<?php
		PageHero::render_for_module(
			[
				'icon'    => 'dashicons-email-alt',
				'title'   => __( 'Customize WP Emails', 'wp-powersuite' ),
				'tagline' => __( 'Customize default WordPress system emails. Set status per email and edit subject/body with SmartCodes. Global branding from Template Design applies only when an email uses Customized Content.', 'wp-powersuite' ),
				'actions' => [
					[
						'label' => __( 'Template Design', 'wp-powersuite' ),
						'url'   => $template_url,
						'icon'  => 'dashicons-admin-appearance',
					],
				],
			]
		);
		?>

		<!-- List view: grouped by recipient -->
		<?php foreach ( [ 'user' => __( 'System Emails send to User', 'wp-powersuite' ), 'site_admin' => __( 'System Emails send to Site Admin', 'wp-powersuite' ) ] as $recipient_key => $section_title ) : ?>
			<?php $section_emails = $emails_by_recipient[ $recipient_key ] ?? []; ?>
			<?php if ( empty( $section_emails ) ) continue; ?>
			<div class="wpps-cwe-panel">
				<h2 class="wpps-cwe-section-title"><?php echo esc_html( $section_title ); ?></h2>
				<table class="wpps-cwe-table widefat">
					<thead>
						<tr>
							<th scope="col" style="width:45%;"><?php esc_html_e( 'Description', 'wp-powersuite' ); ?></th>
							<th scope="col" style="width:20%;"><?php esc_html_e( 'Status', 'wp-powersuite' ); ?></th>
							<th scope="col" style="width:15%;"><?php esc_html_e( 'Actions', 'wp-powersuite' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php foreach ( $section_emails as $email_id => $email_meta ) : ?>
							<?php
							$email_setting = $settings['emails'][ $email_id ] ?? [];
							$status = $email_setting['status'] ?? 'system';
							$status_label = $status === 'active' ? __( 'Customized', 'wp-powersuite' ) : ( $status === 'disabled' ? __( 'Disabled', 'wp-powersuite' ) : __( 'System Default', 'wp-powersuite' ) );
							$status_class = $status === 'active' ? 'wpps-cwe-status-customized' : '';
							?>
							<tr>
								<td>
									<strong><?php echo esc_html( $email_meta['title'] ?? $email_id ); ?></strong>
									<p class="description" style="margin:4px 0 0;"><?php echo esc_html( $email_meta['description'] ?? '' ); ?></p>
								</td>
								<td>
									<span class="wpps-cwe-status-badge <?php echo esc_attr( $status_class ); ?>"><?php echo esc_html( $status_label ); ?></span>
								</td>
								<td>
									<a href="<?php echo esc_url( NetworkScope::adminUrl( 'admin.php', [ 'page' => 'powersuite-custom-wp-emails', 'edit' => $email_id ] ) ); ?>" class="button button-secondary"><?php esc_html_e( 'Edit', 'wp-powersuite' ); ?></a>
								</td>
							</tr>
						<?php endforeach; ?>
					</tbody>
				</table>
			</div>
		<?php endforeach; ?>
	<?php endif; ?>
</div>

<div id="wpps-preview-modal" class="wpps-cwe-modal" role="dialog" aria-modal="true" aria-labelledby="wpps-preview-subject">
	<div class="wpps-cwe-modal-backdrop"></div>
	<div class="wpps-cwe-modal-content">
		<h3 id="wpps-preview-subject"></h3>
		<iframe id="wpps-cwe-preview-iframe" class="wpps-cwe-preview-frame" height="450" title="<?php esc_attr_e( 'Email preview', 'wp-powersuite' ); ?>"></iframe>
		<p class="wpps-cwe-modal-actions"><button type="button" class="wpps-cwe-btn wpps-cwe-btn-secondary wpps-close-preview"><?php esc_html_e( 'Close', 'wp-powersuite' ); ?></button></p>
	</div>
</div>

<div id="wpps-test-email-modal" class="wpps-cwe-modal" role="dialog" aria-modal="true" aria-labelledby="wpps-test-email-modal-title">
	<div class="wpps-cwe-modal-backdrop"></div>
	<div class="wpps-cwe-modal-content" style="max-width:400px;">
		<h3 id="wpps-test-email-modal-title"><?php esc_html_e( 'Send Test Email', 'wp-powersuite' ); ?></h3>
		<p class="description"><?php esc_html_e( 'Test emails use sample data and placeholder security links—they never include real password reset or confirmation URLs.', 'wp-powersuite' ); ?></p>
		<p>
			<label for="wpps-test-email-to" style="display:block;margin-bottom:6px;font-weight:600;"><?php esc_html_e( 'Send to email address', 'wp-powersuite' ); ?></label>
			<input type="email" id="wpps-test-email-to" class="wpps-cwe-input regular-text" style="width:100%;" placeholder="<?php esc_attr_e( 'Enter email address', 'wp-powersuite' ); ?>" />
		</p>
		<p style="margin-top:16px;display:flex;gap:8px;">
			<button type="button" class="button button-primary wpps-test-email-send"><?php esc_html_e( 'Send', 'wp-powersuite' ); ?></button>
			<button type="button" class="button button-secondary wpps-test-email-cancel"><?php esc_html_e( 'Cancel', 'wp-powersuite' ); ?></button>
		</p>
	</div>
</div>

<script>
(function() {
	var defaults = <?php echo wp_json_encode( $defaults ?? [] ); ?>;

	// Unsaved changes warning
	var unsavedForms = document.querySelectorAll('[data-wpps-unsaved-form]');
	unsavedForms.forEach(function(form) {
		var dirty = false;
		form.addEventListener('input', function() { dirty = true; });
		form.addEventListener('change', function() { dirty = true; });
		form.addEventListener('submit', function() { dirty = false; });
		window.addEventListener('beforeunload', function(e) {
			if (dirty) {
				e.preventDefault();
				e.returnValue = '';
			}
		});
	});

	// Status radio toggle
	document.querySelectorAll('input[name="status"]').forEach(function(radio) {
		radio.addEventListener('change', function() {
			var val = this.value;
			var systemInfo = document.getElementById('wpps-system-default-info');
			var disabledInfo = document.getElementById('wpps-disabled-info');
			var fields = document.getElementById('wpps-customized-fields');
			var saveRow = document.getElementById('wpps-save-row-system');
			if (systemInfo) systemInfo.style.display = val === 'system' ? 'block' : 'none';
			if (disabledInfo) disabledInfo.style.display = val === 'disabled' ? 'block' : 'none';
			if (fields) fields.style.display = val === 'active' ? 'block' : 'none';
			if (saveRow) saveRow.style.display = ( val === 'system' || val === 'disabled' ) ? 'flex' : 'none';
		});
	});

	// Set Default
	document.querySelectorAll('.wpps-set-default').forEach(function(btn) {
		btn.addEventListener('click', function() {
			var id = btn.dataset.emailId;
			var def = defaults[id];
			if (!def || !def.email) return;
			var form = btn.closest('form');
			if (!form) return;
			var subj = form.querySelector('input[name="subject"]');
			if (subj) subj.value = def.email.subject || '';
			if (typeof tinymce !== 'undefined') {
				var ed = tinymce.get('body_' + id);
				if (ed) ed.setContent(def.email.body || '');
			}
		});
	});

	// SmartCode panel
	var smartcodePanel = document.getElementById('wpps-smartcode-panel');
	var smartcodeTarget = null;
	function positionSmartcodePanel(btn) {
		if (!smartcodePanel) return;
		var rect = btn.getBoundingClientRect();
		var panelHeight = 280;
		var viewportH = window.innerHeight;
		var spaceBelow = viewportH - rect.bottom;
		var spaceAbove = rect.top;
		smartcodePanel.style.left = Math.max(8, Math.min(rect.left, document.documentElement.clientWidth - 320)) + 'px';
		smartcodePanel.style.width = '300px';
		if (spaceBelow >= panelHeight || spaceBelow >= spaceAbove) {
			smartcodePanel.style.top = (rect.bottom + 4) + 'px';
			smartcodePanel.style.bottom = 'auto';
		} else {
			smartcodePanel.style.bottom = (viewportH - rect.top + 4) + 'px';
			smartcodePanel.style.top = 'auto';
		}
	}
	if (smartcodePanel) {
		document.querySelectorAll('.wpps-smartcode-trigger').forEach(function(btn) {
			btn.addEventListener('click', function(e) {
				e.preventDefault();
				e.stopPropagation();
				smartcodeTarget = { type: this.dataset.target, emailId: this.dataset.emailId };
				positionSmartcodePanel(this);
				smartcodePanel.classList.add('is-open');
			});
		});
		document.querySelectorAll('.wpps-cwe-smartcode-item').forEach(function(btn) {
			if (!btn.dataset.code) return;
			btn.addEventListener('click', function() {
				var code = this.dataset.code;
				if (!smartcodeTarget) return;
				if (smartcodeTarget.type === 'subject') {
					var inp = document.querySelector('.wpps-cwe-email-form input[name="subject"]');
					if (inp) inp.value += code;
				} else {
					var ed = typeof tinymce !== 'undefined' ? tinymce.get('body_' + smartcodeTarget.emailId) : null;
					if (ed && !ed.hidden) ed.execCommand('mceInsertContent', false, code);
				}
				smartcodePanel.classList.remove('is-open');
			});
		});
		document.querySelectorAll('.wpps-cwe-smartcode-tab').forEach(function(tab) {
			tab.addEventListener('click', function() {
				var t = this.dataset.tab;
				smartcodePanel.querySelectorAll('.wpps-cwe-smartcode-tab').forEach(function(x) { x.classList.remove('is-active'); });
				smartcodePanel.querySelectorAll('.wpps-cwe-smartcode-tab-pane').forEach(function(x) { x.classList.remove('is-active'); });
				this.classList.add('is-active');
				var pane = smartcodePanel.querySelector('.wpps-cwe-smartcode-tab-pane[data-pane="' + t + '"]');
				if (pane) pane.classList.add('is-active');
			});
		});
		document.addEventListener('click', function(e) {
			if (smartcodePanel && !smartcodePanel.contains(e.target) && !e.target.closest('.wpps-smartcode-trigger')) {
				smartcodePanel.classList.remove('is-open');
			}
		});
	}

	// Preview
	document.querySelectorAll('.wpps-preview-email').forEach(function(btn) {
		btn.addEventListener('click', function() {
			var form = document.querySelector('.wpps-cwe-email-form');
			if (!form) return;
			var id = form.dataset.emailId;
			var subject = form.querySelector('input[name="subject"]')?.value || '';
			var body = '';
			var ed = typeof tinymce !== 'undefined' ? tinymce.get('body_' + id) : null;
			if (ed && !ed.hidden) body = ed.getContent();
			else {
				var ta = form.querySelector('textarea[name="body"]');
				if (ta) body = ta.value;
			}
			var modal = document.getElementById('wpps-preview-modal');
			var previewEl = document.getElementById('wpps-cwe-preview-iframe');
			var subjectEl = document.getElementById('wpps-preview-subject');
			if (!modal || !previewEl || !subjectEl) return;
			subjectEl.textContent = '<?php echo esc_js( __( 'Loading preview...', 'wp-powersuite' ) ); ?>';
			previewEl.srcdoc = '<p style="padding:20px;text-align:center;color:#666;"><em><?php echo esc_js( __( 'Loading...', 'wp-powersuite' ) ); ?></em></p>';
			modal.classList.add('is-open');
			fetch(ajaxurl, {
				method: 'POST',
				headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
				body: 'action=wpps_custom_wp_emails_preview&nonce=<?php echo esc_js( wp_create_nonce( 'wpps_custom_wp_emails' ) ); ?>&email_id=' + encodeURIComponent(id) + '&subject=' + encodeURIComponent(subject) + '&body=' + encodeURIComponent(body)
			}).then(function(r) { return r.json(); }).then(function(res) {
				if (res.success && res.data && res.data.body) {
					subjectEl.textContent = res.data.subject || subject || '(No subject)';
					previewEl.srcdoc = res.data.body;
				} else {
					subjectEl.textContent = subject || '(No subject)';
					previewEl.srcdoc = '<p style="padding:20px;color:#c00;">' + (res.data && res.data.message ? res.data.message : '<?php echo esc_js( __( 'Preview failed.', 'wp-powersuite' ) ); ?>') + '</p>';
				}
			}).catch(function() {
				subjectEl.textContent = subject || '(No subject)';
				previewEl.srcdoc = '<p style="padding:20px;color:#c00;"><?php echo esc_js( __( 'Preview failed.', 'wp-powersuite' ) ); ?></p>';
			});
		});
	});
	function closePreview() {
		document.getElementById('wpps-preview-modal').classList.remove('is-open');
	}
	document.querySelector('.wpps-close-preview')?.addEventListener('click', closePreview);
	document.querySelector('#wpps-preview-modal .wpps-cwe-modal-backdrop')?.addEventListener('click', closePreview);

	// Send Test Email
	var testEmailModal = document.getElementById('wpps-test-email-modal');
	var testEmailToInput = document.getElementById('wpps-test-email-to');
	var testEmailPending = null;
	document.querySelectorAll('.wpps-send-test-email').forEach(function(btn) {
		btn.addEventListener('click', function() {
			testEmailPending = { emailId: this.dataset.emailId };
			if (testEmailToInput) testEmailToInput.value = '';
			if (testEmailModal) testEmailModal.classList.add('is-open');
			if (testEmailToInput) testEmailToInput.focus();
		});
	});
	function closeTestEmailModal() {
		if (testEmailModal) testEmailModal.classList.remove('is-open');
		testEmailPending = null;
	}
	document.querySelector('.wpps-test-email-cancel')?.addEventListener('click', closeTestEmailModal);
	document.querySelector('#wpps-test-email-modal .wpps-cwe-modal-backdrop')?.addEventListener('click', closeTestEmailModal);
	document.querySelector('.wpps-test-email-send')?.addEventListener('click', function() {
		if (!testEmailPending) return;
		var toEmail = (testEmailToInput && testEmailToInput.value || '').trim();
		if (!toEmail) {
			alert('<?php echo esc_js( __( 'Please enter an email address.', 'wp-powersuite' ) ); ?>');
			return;
		}
		var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
		if (!emailRegex.test(toEmail)) {
			alert('<?php echo esc_js( __( 'Please enter a valid email address.', 'wp-powersuite' ) ); ?>');
			return;
		}
		var form = document.querySelector('.wpps-cwe-email-form');
		if (!form) return;
		var id = testEmailPending.emailId;
		var subject = form.querySelector('input[name="subject"]')?.value || '';
		var body = '';
		var ed = typeof tinymce !== 'undefined' ? tinymce.get('body_' + id) : null;
		if (ed && !ed.hidden) body = ed.getContent();
		else {
			var ta = form.querySelector('textarea[name="body"]');
			if (ta) body = ta.value;
		}
		var sendBtn = document.querySelector('.wpps-test-email-send');
		var origText = sendBtn ? sendBtn.textContent : '';
		if (sendBtn) { sendBtn.disabled = true; sendBtn.textContent = '<?php echo esc_js( __( 'Sending...', 'wp-powersuite' ) ); ?>'; }
		var data = new URLSearchParams();
		data.append('action', 'wpps_custom_wp_emails_test_email');
		data.append('nonce', '<?php echo esc_js( wp_create_nonce( 'wpps_custom_wp_emails' ) ); ?>');
		data.append('email_id', id);
		data.append('subject', subject);
		data.append('body', body);
		data.append('to_email', toEmail);
		fetch(ajaxurl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: data.toString() })
			.then(function(r) { return r.json(); })
			.then(function(res) {
				if (res.success) {
					alert(res.data && res.data.message ? res.data.message : '<?php echo esc_js( __( 'Test email sent successfully.', 'wp-powersuite' ) ); ?>');
					closeTestEmailModal();
				} else {
					alert(res.data && res.data.message ? res.data.message : '<?php echo esc_js( __( 'Failed to send test email.', 'wp-powersuite' ) ); ?>');
				}
			})
			.catch(function() {
				alert('<?php echo esc_js( __( 'Failed to send test email.', 'wp-powersuite' ) ); ?>');
			})
			.finally(function() {
				if (sendBtn) { sendBtn.disabled = false; sendBtn.textContent = origText; }
			});
	});
})();
</script>
