<?php

namespace Awesomemotive\Rewardswp\Views\Admin;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Awesomemotive\Rewardswp\Abstracts\AbstractView;
use Awesomemotive\Rewardswp\Controllers\Admin\EmailsAdminController;
use Awesomemotive\Rewardswp\Factories\ViewsFactory;
use Awesomemotive\Rewardswp\Helpers\IconHelper;
use Awesomemotive\Rewardswp\Interfaces\ViewInterface;
use Awesomemotive\Rewardswp\Services\EmailsService;
use Awesomemotive\Rewardswp\Views\Admin\Parts\EmailsListContentView;
use Awesomemotive\Rewardswp\Views\Admin\Parts\EmailsSettingsContentView;
use function Awesomemotive\Rewardswp\Helpers\get_option_value;
use function Awesomemotive\Rewardswp\Helpers\array_to_json;
use function Awesomemotive\Rewardswp\Helpers\get_upgrade_upsell_data;
use function Awesomemotive\Rewardswp\Helpers\get_view_component;
use function Awesomemotive\Rewardswp\Helpers\svg_kses;
use function Awesomemotive\Rewardswp\Helpers\kses;

/**
 * Class EmailsManagementView
 *
 * Main view for email management with tabs.
 *
 * @since 1.1.0
 */
class EmailsManagementView extends AbstractView implements ViewInterface {

	/**
	 * @since 1.1.0
	 * @var IconHelper
	 */
	private IconHelper $icon_helper;

	/**
	 * @since 1.1.0
	 * @var ViewsFactory
	 */
	private ViewsFactory $views_factory;

	/**
	 * @since 1.1.0
	 * @var EmailsService
	 */
	private EmailsService $emails_service;

	/**
	 * Constructor.
	 *
	 * @since 1.1.0
	 * @param IconHelper    $icon_helper
	 * @param ViewsFactory  $views_factory
	 * @param EmailsService $emails_service
	 */
	public function __construct(
		IconHelper $icon_helper,
		ViewsFactory $views_factory,
		EmailsService $emails_service
	) {
		$this->icon_helper    = $icon_helper;
		$this->views_factory  = $views_factory;
		$this->emails_service = $emails_service;
	}

	/**
	 * Render the save button.
	 *
	 * @since 1.1.0
	 *
	 * @param array $args {
	 *     Optional. Array of button arguments.
	 *     @type string $button_classes Additional classes for the button element.
	 * }
	 * @return void
	 */
	public function render_save_button( array $args = [] ): void {
		$default_button_classes = 'rewardswp-button items-center justify-center px-4 py-2 text-sm font-medium rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-offset-2 cursor-pointer text-white bg-blue-600 border border-transparent hover:bg-blue-700 focus:ring-blue-500 shrink-0 min-w-[120px] grid grid-cols-1 grid-rows-1 [grid-template-areas:stack] text-center place-items-center cursor-pointer';

		$args = wp_parse_args(
			$args,
			[
				'button_classes' => '',
			]
		);

		// Merge the default button classes with any additional classes
		$button_classes = trim( $default_button_classes . ' ' . $args['button_classes'] );
		?>

		<button
			x-on:click.prevent="saveSettings"
			type="submit"
			x-bind:disabled="isSaving || !canSave()"
			x-bind:class="{
				'cursor-not-allowed opacity-50': isSaving || !isSaving && !canSave(),
				'cursor-pointer': !isSaving && canSave()
			}"
			class="<?php echo esc_attr( $button_classes ); ?>"
		>
			<span
				class="[grid-area:stack] transition-opacity duration-200"
				x-bind:class="{ 'invisible': isSaving, 'visible': !isSaving }"
			><?php esc_html_e( 'Save Changes', 'rewardswp' ); ?></span>
			<svg
				class="animate-spin h-5 w-5 [grid-area:stack] transition-opacity duration-200 invisible"
				x-bind:class="{ 'invisible': isSaving !== true, 'visible': isSaving === true }"
				xmlns="http://www.w3.org/2000/svg"
				fill="none"
				viewBox="0 0 24 24"
			>
				<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
				<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
			</svg>
			<svg
				class="h-5 w-5 [grid-area:stack] transition-opacity duration-200 invisible"
				x-bind:class="{ 'invisible': isSaving !== 'complete', 'visible': isSaving === 'complete' }"
				xmlns="http://www.w3.org/2000/svg"
				fill="none"
				viewBox="0 0 24 24"
				stroke="currentColor"
			>
				<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
			</svg>
		</button>

		<?php
	}

	/**
	 * Get preloaded emails data for Alpine.js.
	 *
	 * @since 1.1.0
	 *
	 * @return array Emails data indexed by ID for JavaScript lookup.
	 */
	private function get_preloaded_emails_data(): array {
		return $this->emails_service->get_emails_with_complete_edit_data_indexed( false );
	}

	/**
	 * Render the template.
	 *
	 * @since 1.1.0
	 *
	 * @param array $args {
	 *     Optional arguments.
	 *     @type string $page_title The page title.
	 * }
	 *
	 * @return void
	 */
	public function render( array $args = [] ): void {
		// Get active tab from URL query string or default to 'emails'.
		$tab_raw      = filter_input( INPUT_GET, 'tab', FILTER_UNSAFE_RAW );
		$tab_param    = is_string( $tab_raw ) ? sanitize_text_field( wp_unslash( $tab_raw ) ) : '';
		$allowed_tabs = [ 'emails', 'settings' ];
		$active_tab   = in_array( $tab_param, $allowed_tabs, true ) ? $tab_param : 'emails';

		// Get email ID for deep-linking to email editing.
		$email_raw          = filter_input( INPUT_GET, 'email', FILTER_UNSAFE_RAW );
		$deep_link_email_id = is_string( $email_raw ) ? absint( $email_raw ) : 0;

		$args = wp_parse_args(
			$args,
			[
				'page_title' => esc_html__( 'Emails', 'rewardswp' ),
			]
		);

		// Get preloaded emails data for Alpine.js
		$preloaded_emails = $this->get_preloaded_emails_data();

		// Pre-compute values for x-data to avoid newlines in JS literals.
		// These are computed here so the PHP formatter doesn't add newlines inside the JS object.
		$email_statuses = [];
		foreach ( $preloaded_emails as $email_id_key => $email_data ) {
			$email_statuses[ $email_id_key ] = ! empty( $email_data['is_enabled'] );
		}
		$email_statuses_json = array_to_json( $email_statuses, false );

		// Email settings values for Alpine state
		$from_name  = get_option_value( \Awesomemotive\Rewardswp\Settings\Options\Emails\FromNameOption::class );
		$from_email = get_option_value( \Awesomemotive\Rewardswp\Settings\Options\Emails\FromEmailOption::class );

		// Logo preview URL computation.
		$logo_data          = get_option_value( \Awesomemotive\Rewardswp\Settings\Options\Emails\EmailLogoOption::class );
		$logo_attachment_id = $logo_data['attachment_id'] ?? 0;
		$logo_size          = $logo_data['size'] ?? 'medium';
		$logo_preview_url   = '';
		if ( $logo_attachment_id ) {
			$image_data = wp_get_attachment_image_src( $logo_attachment_id, $logo_size );
			if ( $image_data ) {
				$logo_preview_url = $image_data[0];
				// Force HTTPS if current site is HTTPS to avoid Mixed Content issues.
				if ( is_ssl() && strpos( $logo_preview_url, 'http://' ) === 0 ) {
					$logo_preview_url = str_replace( 'http://', 'https://', $logo_preview_url );
				}
			}
		}

		// Pre-compute upsell data for email features (used in inline upgrade card).
		$upsell_email_banner        = get_upgrade_upsell_data( 'email_banner', 'email_management' );
		$upsell_points_expiry_email = get_upgrade_upsell_data( 'points_expiry_email', 'email_management' );
		$upsell_friend_reward_email   = get_upgrade_upsell_data( 'friend_reward_email', 'email_management' );
		$upsell_birthday_reward_email = get_upgrade_upsell_data( 'birthday_reward_email', 'email_management' );

		?>

		<!-- Alpine Store for Email Upgrade Content -->
		<script>
			document.addEventListener('alpine:init', () => {
				Alpine.store('emailUpgrade', {
					content:
					<?php
					echo wp_json_encode(
						[
							'email_banner'        => [
								'title'         => __( 'Add a banner image', 'rewardswp' ),
								'message'       => __( 'Upgrade to add a custom banner image to enhance the look of your email.', 'rewardswp' ),
								'features'      => [
									__( 'Custom banner images', 'rewardswp' ),
									__( 'Professional email design', 'rewardswp' ),
									__( 'Enhanced brand visibility', 'rewardswp' ),
								],
								'required_plan' => $upsell_email_banner['required_plan'],
								'button_text'   => $upsell_email_banner['button_text'],
								'button_url'    => $upsell_email_banner['button_url'],
								'compare_url'   => $upsell_email_banner['compare_url'],
							],
							'points_expiry_email' => [
								'title'         => __( 'Unlock Points Expiry Email', 'rewardswp' ),
								'message'       => __( 'Automatically notify members before their points expire so they have time to redeem.', 'rewardswp' ),
								'features'      => [
									__( 'Recover revenue from expiring points', 'rewardswp' ),
									__( 'Customizable subject line and branding', 'rewardswp' ),
								],
								'required_plan' => $upsell_points_expiry_email['required_plan'],
								'button_text'   => $upsell_points_expiry_email['button_text'],
								'button_url'    => $upsell_points_expiry_email['button_url'],
								'compare_url'   => $upsell_points_expiry_email['compare_url'],
							],
							'friend_reward_email' => [
								'title'         => __( 'Unlock Friend Reward Email', 'rewardswp' ),
								'message'       => __( 'Automatically email referred friends their reward when they are referred.', 'rewardswp' ),
								'features'      => [
									__( 'Convert referred friends into paying customers', 'rewardswp' ),
									__( 'Automatic coupon delivery with expiry dates', 'rewardswp' ),
								],
								'required_plan' => $upsell_friend_reward_email['required_plan'],
								'button_text'   => $upsell_friend_reward_email['button_text'],
								'button_url'    => $upsell_friend_reward_email['button_url'],
								'compare_url'   => $upsell_friend_reward_email['compare_url'],
							],
							'birthday_reward_email' => [
								'title'         => __( 'Unlock Birthday Reward Email', 'rewardswp' ),
								'message'       => __( 'Works with your Birthday bonus earn action to automatically email members when their bonus points are awarded.', 'rewardswp' ),
								'features'      => [
									__( 'Bring members back to your store on their birthday', 'rewardswp' ),
									__( 'Fully customizable subject line and branding', 'rewardswp' ),
								],
								'required_plan' => $upsell_birthday_reward_email['required_plan'],
								'button_text'   => $upsell_birthday_reward_email['button_text'],
								'button_url'    => $upsell_birthday_reward_email['button_url'],
								'compare_url'   => $upsell_birthday_reward_email['compare_url'],
							],
						]
					);
					?>
				});
			});
		</script>

		<div
			x-data="{
				activeTab: 'emails',
				isSaving: false,
				fieldErrors: {},
				formHasErrors: false,
				formFeedbackMessage: null,
				formFeedbackClasses: 'text-red-500',

				// Email editing state
				isEditingEmail: false,
				isLoadingEmail: false, // Keep for UI compatibility but not used
				currentEmail: null,
				originalEmailData: null,
				iframeExists: false, // Control iframe existence

				// Preloaded emails data (indexed by ID for fast lookup)
				preloadedEmails: <?php echo array_to_json( $preloaded_emails, false ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Array is already escaped. ?>,

				// Email statuses (indexed by ID for fast lookup and reactive updates)
				emailStatuses: <?php echo $email_statuses_json; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Pre-escaped. ?>,

				// Original email statuses for dirty tracking (to detect changes)
				originalEmailStatuses: <?php echo $email_statuses_json; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Pre-escaped. ?>,

				// Email settings state
				fromName: '<?php echo esc_js( $from_name ); ?>',
				fromEmail: '<?php echo esc_js( $from_email ); ?>',
				logoAttachmentId: <?php echo esc_js( $logo_attachment_id ); ?>,
				logoSize: '<?php echo esc_js( $logo_size ); ?>',
				logoPreviewUrl: '<?php echo esc_js( $logo_preview_url ); ?>',

				// Original settings values for dirty tracking
				originalFromName: '<?php echo esc_js( $from_name ); ?>',
				originalFromEmail: '<?php echo esc_js( $from_email ); ?>',
				originalLogoAttachmentId: <?php echo esc_js( $logo_attachment_id ); ?>,
				originalLogoSize: '<?php echo esc_js( $logo_size ); ?>',

// Tab Navigation
				setActiveTab(tab) {
					this.activeTab = tab;
				},

				// Handle deep-linking via URL query parameters.
				handleUrlChange() {
					const params = new URLSearchParams(window.location.search);
					const tab = params.get('tab') || 'emails';
					const emailId = params.get('email');

					if (emailId) {
						const id = parseInt(emailId, 10);
						if (Number.isFinite(id)) {
							this.activeTab = 'emails';
							if (!this.currentEmail || parseInt(this.currentEmail.id) !== id || !this.isEditingEmail) {
								this.setEmailForEdit(id);
							}
						}
						return;
					}

					if (tab === 'emails' || tab === 'settings') {
						this.activeTab = tab;
						if (tab === 'emails' && this.isEditingEmail) {
							// Return to list when URL says emails without an email id.
							this.destroyIframe();
							this.isEditingEmail = false;
							this.isLoadingEmail = false;
							this.currentEmail = null;
							this.originalEmailData = null;
						}
					}
				},

				setFieldError(field, message) {
					this.fieldErrors[field] = message;
				},
				clearFieldError(field) {
					delete this.fieldErrors[field];
				},
				hasFieldErrors() {
					return Object.keys(this.fieldErrors).length &gt; 0;
				},
				setFormFeedback( message = null, type = 'error', timeout = 2000 ) {
					this.formFeedbackMessage = message || '<?php esc_html_e( 'Please resolve all issues in the form to continue.', 'rewardswp' ); ?>';
					this.formFeedbackClasses = 'success' === type
						? 'text-green-700'
						: 'text-red-500';

					this.formHasErrors = 'error' === type;

					if ( timeout &lt; 0 ) {
						return;
					}

					setTimeout( () => {
						this.formFeedbackMessage = null;
					}, timeout );
				},
					hasEmailStatusChanges() {
					for (const id in this.emailStatuses) {
						if (this.emailStatuses[id] !== this.originalEmailStatuses[id]) {
							return true;
						}
					}
					return false;
				},
				hasEmailContentChanges() {
					if (!this.currentEmail || !this.originalEmailData) {
						return false;
					}
					// Check if any editable fields have changed
					return this.currentEmail.subject !== this.originalEmailData.subject ||
						this.currentEmail.heading !== this.originalEmailData.heading ||
						this.currentEmail.body !== this.originalEmailData.body ||
						this.currentEmail.banner_attachment_id !== this.originalEmailData.banner_attachment_id;
				},
				hasSettingsChanges() {
					// Check if any settings have changed
					return this.fromName !== this.originalFromName ||
						this.fromEmail !== this.originalFromEmail ||
						this.logoAttachmentId != this.originalLogoAttachmentId ||
						this.logoSize !== this.originalLogoSize;
				},
				canSave() {
					if (this.currentEmail && this.currentEmail.is_locked) {
						return false;
					}

					if (this.formHasErrors || this.hasFieldErrors()) {
						return false;
					}

					// On settings tab, check for settings changes or email status changes
					if (this.activeTab === 'settings') {
						return this.hasSettingsChanges() || this.hasEmailStatusChanges();
					}

					// On emails tab, check for status changes OR content changes (when editing an email)
					return this.hasEmailStatusChanges() || this.hasEmailContentChanges();
				},

				// Iframe management functions
				destroyIframe() {
					const container = document.getElementById('email-preview-container-inline');
					if (container) {
						container.innerHTML = '';
					}
					this.iframeExists = false;
				},

				createNewIframe(emailId) {
					if (!emailId) return;

					const container = document.getElementById('email-preview-container-inline');
					if (!container) return;

					// Show loading immediately
					const loadingElement = document.getElementById('email-preview-loading-inline');
					if (loadingElement) {
						loadingElement.style.display = 'flex';
					}

					// Create new iframe element
					const iframe = document.createElement('iframe');
					iframe.id = 'email-preview-frame-inline';
					iframe.className = 'w-full border-0';
					iframe.style.minHeight = '200px';
					iframe.style.height = '400px';
					iframe.title = '<?php esc_attr_e( 'Email Preview', 'rewardswp' ); ?>';
					iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox');

					// Set src with timestamp to force fresh load
					const timestamp = new Date().getTime();
					iframe.src = '<?php echo esc_js( admin_url( 'admin.php?page=rewardswp-emails&action=preview&iframe=1&email_id=' ) ); ?>' + emailId + '&t=' + timestamp;

					// Add load event listener
					iframe.addEventListener('load', () => {
						if (loadingElement) {
							loadingElement.style.display = 'none';
						}
						// Make links open in new tab instead of navigating inside iframe.
						const doc = iframe.contentDocument;
						if (doc && !doc.querySelector('base')) {
							const base = doc.createElement('base');
							base.target = '_blank';
							doc.head.appendChild(base);
						}
						// Request initial height from iframe
						if (iframe.contentWindow) {
							iframe.contentWindow.postMessage({ type: 'request-height' }, '*');
						}
					});

					// Add iframe to container
					container.appendChild(iframe);
					this.iframeExists = true;
				},

				// Email editing functions
				setEmailForEdit(emailId) {
					// Find the email in preloaded data
					const email = this.preloadedEmails[emailId];
					if (!email) {
						alert('<?php esc_html_e( 'Email not found.', 'rewardswp' ); ?>');
						return;
					}

					// Destroy existing iframe first
					this.destroyIframe();

					// Set current email data (make a deep copy to avoid reference issues)
					this.currentEmail = JSON.parse(JSON.stringify(email));
					// Sync is_enabled with current emailStatuses (in case user toggled before editing)
					this.currentEmail.is_enabled = this.emailStatuses[emailId] ?? this.currentEmail.is_enabled;
					this.originalEmailData = JSON.parse(JSON.stringify(email));
					this.isEditingEmail = true;
					this.isLoadingEmail = false; // Not used but kept for compatibility
					this.activeTab = 'emails';

					// Update URL for deep-linking.
					const newUrl = new URL(window.location);
					newUrl.searchParams.set('tab', 'emails');
					newUrl.searchParams.set('email', emailId);
					history.pushState(null, '', newUrl);

					// Reset form states
					this.fieldErrors = {};
					this.formHasErrors = false;
					this.formFeedbackMessage = null;

					// Create new iframe after a short delay to ensure DOM is ready
					this.$nextTick(() => {
						setTimeout(() => {
							this.createNewIframe(emailId);
						}, 50);
					});
				},

				// Update preloaded emails data with current email changes
				updatePreloadedEmailData() {
					if (!this.currentEmail) {
						return;
					}

					// Update the preloaded data with current email changes
					const emailId = this.currentEmail.id;
					if (this.preloadedEmails[emailId]) {
						// Create a deep copy of current email to avoid reference issues
						this.preloadedEmails[emailId] = JSON.parse(JSON.stringify(this.currentEmail));
					}
				},

				backToEmailsList() {
					// Destroy iframe when going back to list.
					this.destroyIframe();

					this.isEditingEmail = false;
					this.isLoadingEmail = false;
					this.currentEmail = null;
					this.originalEmailData = null;
					this.fieldErrors = {};
					this.formHasErrors = false;
					this.formFeedbackMessage = null;

					// Update URL to remove email parameter.
					const newUrl = new URL(window.location);
					newUrl.searchParams.set('tab', 'emails');
					newUrl.searchParams.delete('email');
					history.pushState(null, '', newUrl);
				},

				// Save individual email settings
				saveEmailSettings() {
					if (!this.currentEmail) {
						alert('<?php esc_html_e( 'No email selected for editing.', 'rewardswp' ); ?>');
						return;
					}

					if (!this.currentEmail.has_access) {
						if (this.currentEmail.feature_slug) {
							this.openUpgradeModal(this.currentEmail.feature_slug);
						}
						return;
					}

					this.isSaving = true;

					const formData = new FormData();
					formData.append('action', 'rewardswp_save_individual_email');
					formData.append('email_id', this.currentEmail.id);
					formData.append('subject', this.currentEmail.subject);
					// Preserve 0 as a valid value (no banner). Avoid || fallbacks.
					const bannerId = (typeof this.currentEmail.banner_attachment_id !== 'undefined')
						? Number(this.currentEmail.banner_attachment_id)
						: Number(this.currentEmail.logo_attachment_id || 0);
					// Only send string sizes; skip arrays to avoid breaking JS
					const bannerSize = (typeof this.currentEmail.banner_size === 'string')
						? this.currentEmail.banner_size
						: (typeof this.currentEmail.logo_size === 'string' ? this.currentEmail.logo_size : '');
					formData.append('banner_attachment_id', isNaN(bannerId) ? 0 : bannerId);
					if (bannerSize) {
						formData.append('banner_size', bannerSize);
					}
					formData.append('_ajax_nonce', '<?php echo esc_js( wp_create_nonce( EmailsAdminController::AJAX_NONCE ) ); ?>');

					// Add email statuses to form data so they're saved too
					for (const id in this.emailStatuses) {
						formData.append('email_statuses[' + id + ']', this.emailStatuses[id] ? '1' : '0');
					}

					fetch('<?php echo esc_js( admin_url( 'admin-ajax.php' ) ); ?>', {
						method: 'POST',
						body: formData
					})
					.then(response => response.json())
					.then(data => {
						if (data.success) {
							this.isSaving = 'complete';
							// Update preloaded emails data with current changes
							this.updatePreloadedEmailData();
							// Refresh the preview to show the logo changes
							this.refreshPreview();
							// Reset dirty tracking for email statuses and content
							this.originalEmailStatuses = JSON.parse(JSON.stringify(this.emailStatuses));
							this.originalEmailData = JSON.parse(JSON.stringify(this.currentEmail));
							setTimeout(() => {
								this.isSaving = false;
							}, 2000);
						} else {
							this.setFormFeedback(data.data || '<?php esc_html_e( 'Error saving email settings.', 'rewardswp' ); ?>', 'error');
							this.isSaving = false;
						}
					})
					.catch(error => {
						console.error('Error saving email:', error);
						this.setFormFeedback('<?php esc_html_e( 'A network error occurred. Please try again.', 'rewardswp' ); ?>', 'error');
						this.isSaving = false;
					});
				},

				// Refresh preview iframe
				refreshPreview() {
					if (this.currentEmail && this.currentEmail.id) {
						// Destroy and recreate iframe for fresh content
						this.destroyIframe();
						this.$nextTick(() => {
							setTimeout(() => {
								this.createNewIframe(this.currentEmail.id);
							}, 50);
						});
					}
				},

				// Send test email
				sendTestEmail(emailId) {
					if (!emailId) {
						alert('<?php esc_html_e( 'Invalid email ID.', 'rewardswp' ); ?>');
						return Promise.resolve();
					}

					const formData = new FormData();
					formData.append('action', 'rewardswp_send_test_email');
					formData.append('email_id', emailId);
					formData.append('rewardswp_email_nonce', '<?php echo esc_js( wp_create_nonce( 'rewardswp_update_email' ) ); ?>');

					return fetch('<?php echo esc_js( admin_url( 'admin-ajax.php' ) ); ?>', {
						method: 'POST',
						body: formData
					})
					.then(response => response.json())
					.then(data => {
						if (data.success) {
							// Show success toast
							window.dispatchEvent(new CustomEvent('rewardswp-toast', {
								detail: { message: data.data, type: 'success' }
							}));
						} else {
							// Show error toast
							window.dispatchEvent(new CustomEvent('rewardswp-toast', {
								detail: { message: data.data || '<?php esc_html_e( 'Error sending test email.', 'rewardswp' ); ?>', type: 'error' }
							}));
						}
					})
					.catch(error => {
						console.error('Error sending test email:', error);
						// Show error toast
						window.dispatchEvent(new CustomEvent('rewardswp-toast', {
							detail: { message: '<?php esc_html_e( 'A network error occurred. Please try again.', 'rewardswp' ); ?>', type: 'error' }
						}));
					});
				},

				// Open upgrade modal for Pro features
				openUpgradeModal(feature) {
					window.dispatchEvent(new CustomEvent('show-upgrade-modal', { detail: feature }));
				},

				saveSettings() {
					this.isSaving = true;

					const form = document.getElementById( 'emails-settings-form' );
					const formData = new FormData( form );

					formData.append( 'action', 'rewardswp_save_email_settings' );
					formData.append( '_ajax_nonce', '<?php echo esc_js( wp_create_nonce( EmailsAdminController::AJAX_NONCE ) ); ?>' );

					// Add email statuses to form data
					for (const id in this.emailStatuses) {
						formData.append('email_statuses[' + id + ']', this.emailStatuses[id] ? '1' : '0');
					}

					fetch('<?php echo esc_js( admin_url( 'admin-ajax.php' ) ); ?>', {
						method: 'POST',
						body: formData,
					} )
					.then( ( response ) => response.json() )
					.then( ( response ) => {
						if (response.success) {
							this.isSaving = 'complete';
							// Reset dirty tracking after successful save
							this.originalEmailStatuses = JSON.parse(JSON.stringify(this.emailStatuses));
							this.originalFromName = this.fromName;
							this.originalFromEmail = this.fromEmail;
							this.originalLogoAttachmentId = this.logoAttachmentId;
							this.originalLogoSize = this.logoSize;
							setTimeout(() => {
								this.isSaving = false;
							}, 2000);
						} else {
							this.setFormFeedback( response.data.message, 'error' );
							this.isSaving = false;
						}
					} )
					.catch( ( error ) => {
						this.setFormFeedback( '<?php esc_html_e( 'An error occurred while saving settings.', 'rewardswp' ); ?>' );
						this.isSaving = false;
					} );
				}
			}"
			x-init="
				activeTab = '<?php echo esc_js( $active_tab ); ?>';

				// Handle browser back/forward navigation.
				window.addEventListener('popstate', (event) => {
					// Force a small delay to ensure iframe doesn't interfere.
					setTimeout(() => {
						handleUrlChange();
					}, 10);
				});

				// Initial parse for deep-link from URL.
				<?php if ( $deep_link_email_id > 0 ) : ?>
				setEmailForEdit(<?php echo esc_js( $deep_link_email_id ); ?>);
				<?php endif; ?>
			"
		>

			<div class="rewardswp-container max-[782px]:ml-[-10px] ml-[-20px]">
				<form id="emails-settings-form" method="post" x-on:submit="saveSettings">

					<?php
					/**
					 * Settings navigation.
					 */
					$tabs = [
						'emails'   => [
							'label'    => esc_html__( 'Emails', 'rewardswp' ),
							'href'     => add_query_arg(
								[
									'page' => 'rewardswp-emails',
									'tab'  => 'emails',
								],
								admin_url( 'admin.php' )
							),
							'pro_only' => false,
						],
						'settings' => [
							'label'    => esc_html__( 'Settings', 'rewardswp' ),
							'href'     => add_query_arg(
								[
									'page' => 'rewardswp-emails',
									'tab'  => 'settings',
								],
								admin_url( 'admin.php' )
							),
							'pro_only' => false,
						],
					];

					$common_classes   = 'px-4 py-5 text-sm whitespace-nowrap focus:outline-none focus:border-b-2 focus:border-blue-500';
					$active_classes   = 'text-blue-600 border-b-2 border-blue-500 ';
					$inactive_classes = 'text-gray-800 hover:text-gray-600';
					?>

					<div id="rewardswp-admin-emails-sentinel" class="absolute top-0 left-0 right-0"></div>

					<div class="px-8 pt-5 mx-auto max-w-7xl sr-only">
						<div class="mb-6 flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
							<h1 class="text-2xl font-semibold text-slate-900"><?php echo esc_html( $args['page_title'] ); ?></h1>
						</div>
					</div>


					<div
						id="rewardswp-admin-emails-header"
						class="shadow-gray-800/10 sticky max-[601px]:top-0 max-[783px]:top-[46px] top-[32px] bg-[#f0f0f1] z-10 border-b border-gray-300"
						x-ref="emailsHeader"
						x-show="!isEditingEmail"
					>
						<div class="px-5 mx-auto max-w-7xl flex justify-between items-center">
							<nav class="flex font-semibold overflow-x-auto scrollbar" aria-label="<?php esc_attr_e( 'Tabs', 'rewardswp' ); ?>">
								<?php foreach ( $tabs as $tab_key => $tab ) : ?>
									<a
										x-on:click.prevent="setActiveTab( '<?php echo esc_js( $tab_key ); ?>' ); history.pushState(null, '', '<?php echo esc_js( $tab['href'] ); ?>')"
										x-bind:class="{ '<?php echo esc_attr( $active_classes ); ?>': activeTab === '<?php echo esc_js( $tab_key ); ?>', '<?php echo esc_attr( $inactive_classes ); ?>': activeTab !== '<?php echo esc_js( $tab_key ); ?>' }"
										href="<?php echo esc_url( $tab['href'] ); ?>"
										class="<?php echo esc_attr( $common_classes ); ?>"
									>
										<?php echo esc_html( $tab['label'] ); ?>
									</a>
								<?php endforeach; ?>
							</nav>

							<?php $this->render_save_button( [ 'button_classes' => 'max-[783px]:hidden' ] ); ?>

						</div>
					</div>

					<div class="px-5 mx-auto max-w-7xl">

						<!-- Mobile Save Button -->
						<div class="mb-5"
							x-show="!isEditingEmail">
							<?php $this->render_save_button( [ 'button_classes' => 'min-[783px]:hidden place-self-end' ] ); ?>
						</div>

						<!-- Form Feedback -->
						<div x-show="formFeedbackMessage" x-cloak class="mb-5">
							<div
								x-bind:class="formFeedbackClasses"
								class="text-sm font-medium"
							>
								<span x-text="formFeedbackMessage"></span>
							</div>
						</div>

						<?php
						/**
						 * Emails Tab Content
						 */
						?>
						<div
							x-show="activeTab === 'emails'"
							id="emails"
							x-cloak
						>
							<!-- Email List View -->
							<div x-show="!isEditingEmail">
								<?php $this->views_factory->get_view( EmailsListContentView::class )->render(); ?>
							</div>

							<!-- Email Edit View -->
							<div x-show="isEditingEmail">
								<!-- Loading skeleton while fetching email data -->
								<div x-show="isLoadingEmail" x-cloak class="space-y-6">
									<div class="flex items-start justify-between">
										<div class="flex-1 min-w-0">
											<div class="h-5 w-36 bg-gray-200 rounded animate-pulse mb-2"></div>
											<div class="h-4 w-60 bg-gray-200 rounded animate-pulse"></div>
										</div>
										<div class="flex items-center ml-6 shrink-0">
											<div class="h-10 w-32 bg-gray-200 rounded animate-pulse"></div>
										</div>
									</div>
									<div class="grid grid-cols-1 lg:grid-cols-5 gap-6">
										<div class="lg:col-span-2 space-y-4">
											<div class="bg-white border border-gray-900/8 rounded-xl p-6 space-y-4">
												<div class="h-5 w-28 bg-gray-200 rounded animate-pulse"></div>
												<div class="h-10 w-full bg-gray-200 rounded animate-pulse"></div>
												<div class="h-16 w-full bg-gray-200 rounded animate-pulse"></div>
											</div>
										</div>
										<div class="lg:col-span-3">
											<div class="bg-white border border-gray-900/8 rounded-xl p-6">
												<div class="h-[400px] w-full bg-gray-200 rounded animate-pulse"></div>
											</div>
										</div>
									</div>
								</div>
								<!-- Real editor when loaded -->
								<div x-show="!isLoadingEmail" x-cloak>
									<?php $this->render_email_edit_inline(); ?>
								</div>
							</div>
						</div>

						<?php
						/**
						 * Settings Tab Content
						 */
						?>
						<div
							x-show="activeTab === 'settings'"
							id="settings"
							x-cloak
						>
							<?php $this->views_factory->get_view( EmailsSettingsContentView::class )->render(); ?>
						</div>

					</div>

					<!-- Bottom Save Button -->
					<div class="px-5 pt-2 max-w-7xl"
						x-show="!isEditingEmail">
						<?php $this->render_save_button( [ 'button_classes' => 'min-[783px]:hidden place-self-end' ] ); ?>
					</div>

				</form>
			</div>
		</div>

		<div class="rewardswp-container">
			<!-- Upgrade Modal with separate scope -->
			<?php
			// Pre-compute upsell data for email features.
			$upsell_email_banner        = get_upgrade_upsell_data( 'email_banner', 'email_management' );
			$upsell_points_expiry_email = get_upgrade_upsell_data( 'points_expiry_email', 'email_management' );
			$upsell_friend_reward_email = get_upgrade_upsell_data( 'friend_reward_email', 'email_management' );
			?>
			<div x-data="{
				upgradeModal: false,
				// Upgrade modal content
				upgradeModalContent: {
					email_banner: {
						title: '<?php esc_html_e( 'Add a banner image', 'rewardswp' ); ?>',
						message: '<?php esc_html_e( 'Upgrade to add a custom banner image to enhance the look of your email.', 'rewardswp' ); ?>',
						features: [
							'<?php esc_html_e( 'Custom banner images', 'rewardswp' ); ?>',
							'<?php esc_html_e( 'Professional email design', 'rewardswp' ); ?>',
							'<?php esc_html_e( 'Enhanced brand visibility', 'rewardswp' ); ?>',
						],
						required_plan: <?php echo esc_attr( wp_json_encode( $upsell_email_banner['required_plan'] ) ); ?>,
						button_text: '<?php echo esc_js( $upsell_email_banner['button_text'] ); ?>',
						button_url: <?php echo esc_attr( wp_json_encode( $upsell_email_banner['button_url'] ) ); ?>,
						compare_url: <?php echo esc_attr( wp_json_encode( $upsell_email_banner['compare_url'] ) ); ?>,
					},
					points_expiry_email: {
						title: '<?php esc_html_e( 'Points expiry email', 'rewardswp' ); ?>',
						message: '<?php esc_html_e( 'Automatically notify members before their points expire so they have time to redeem.', 'rewardswp' ); ?>',
						features: [
							'<?php esc_html_e( 'Send expiry reminders automatically', 'rewardswp' ); ?>',
							'<?php esc_html_e( 'Help members redeem before points expire', 'rewardswp' ); ?>',
						],
						required_plan: <?php echo esc_attr( wp_json_encode( $upsell_points_expiry_email['required_plan'] ) ); ?>,
						button_text: '<?php echo esc_js( $upsell_points_expiry_email['button_text'] ); ?>',
						button_url: <?php echo esc_attr( wp_json_encode( $upsell_points_expiry_email['button_url'] ) ); ?>,
						compare_url: <?php echo esc_attr( wp_json_encode( $upsell_points_expiry_email['compare_url'] ) ); ?>,
					},
					friend_reward_email: {
						title: '<?php esc_html_e( 'Friend reward email', 'rewardswp' ); ?>',
						message: '<?php esc_html_e( 'Automatically email referred friends their reward coupon after their first purchase.', 'rewardswp' ); ?>',
						features: [
							'<?php esc_html_e( 'Send friend reward emails automatically', 'rewardswp' ); ?>',
							'<?php esc_html_e( 'Generate and include coupon codes', 'rewardswp' ); ?>',
						],
						required_plan: <?php echo esc_attr( wp_json_encode( $upsell_friend_reward_email['required_plan'] ) ); ?>,
						button_text: '<?php echo esc_js( $upsell_friend_reward_email['button_text'] ); ?>',
						button_url: <?php echo esc_attr( wp_json_encode( $upsell_friend_reward_email['button_url'] ) ); ?>,
						compare_url: <?php echo esc_attr( wp_json_encode( $upsell_friend_reward_email['compare_url'] ) ); ?>,
					}
				},
				currentUpgradeModalContent: {
					title: '',
					message: '',
					features: [],
					required_plan: '',
					button_text: '',
					button_url: '',
					compare_url: ''
				}
			}">
				<?php
				$this->views_factory->get_view( \Awesomemotive\Rewardswp\Views\Admin\Modals\UpgradeModalView::class )->render();
				?>
			</div>
		</div>

		<!-- JavaScript for inline email editing -->
		<script>
			document.addEventListener('DOMContentLoaded', function() {
				// Handle iframe resizing for inline preview
				window.addEventListener('message', function(event) {
					if (event.data && event.data.type === 'iframe-resize' && event.data.height) {
						const inlineFrame = document.getElementById('email-preview-frame-inline');
						if (inlineFrame) {
							const newHeight = Math.max(200, Math.min(800, event.data.height)); // Min 200px, Max 800px
							inlineFrame.style.height = newHeight + 'px';
							// Also update the container height
							const container = document.getElementById('email-preview-container-inline');
							if (container) {
								container.style.height = newHeight + 'px';
							}
						}
					}
				});

				// Note: Subject changes no longer auto-refresh preview
				// Only banner changes will refresh the preview automatically
			});
		</script>

		<?php
	}

	/**
	 * Render the inline email edit content.
	 *
	 * @since 1.1.0
	 *
	 * @return void
	 */
	private function render_email_edit_inline(): void {
		?>
		<div x-show="currentEmail" class="space-y-6">

			<!-- Top bar: back link + save button, with border below -->
			<div class="flex items-center justify-between py-3 border-b border-gray-300">
				<button
					type="button"
					x-on:click="backToEmailsList()"
					class="inline-flex items-center text-sm text-gray-500 hover:text-gray-700 cursor-pointer">
					<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
						<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
					</svg>
					<?php esc_html_e( 'Back to Emails', 'rewardswp' ); ?>
				</button>

				<!-- Action Buttons -->
				<div class="flex items-center shrink-0">
					<div class="flex items-center">
							<button type="button"
									x-on:click="saveEmailSettings()"
									x-bind:disabled="isSaving || !canSave() || (currentEmail && !currentEmail.has_access)"
									x-bind:class="{
										'cursor-not-allowed opacity-50': isSaving || (!isSaving && !canSave()) || (currentEmail && !currentEmail.has_access),
										'cursor-pointer': !isSaving && canSave() && currentEmail?.has_access
									}"
									class="rewardswp-button items-center justify-center px-4 py-2 text-sm font-medium rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-offset-2 cursor-pointer text-white bg-blue-600 border border-transparent hover:bg-blue-700 focus:ring-blue-500 shrink-0 min-w-[120px] grid grid-cols-1 grid-rows-1 [grid-template-areas:stack] text-center place-items-center cursor-pointer">
									<span class="button-text [grid-area:stack] transition-opacity duration-200" x-bind:class="{ 'invisible': isSaving, 'visible': !isSaving }">
										<?php esc_html_e( 'Save Changes', 'rewardswp' ); ?>
									</span>
									<svg class="loading-spinner animate-spin h-5 w-5 [grid-area:stack] transition-opacity duration-200" x-bind:class="{ 'invisible': isSaving !== true, 'visible': isSaving === true }" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
										<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
										<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
									</svg>
									<svg class="success-check h-5 w-5 [grid-area:stack] transition-opacity duration-200" x-bind:class="{ 'invisible': isSaving !== 'complete', 'visible': isSaving === 'complete' }" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
										<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
									</svg>
							</button>
						</div>
				</div>
			</div>

			<!-- Email title and description -->
			<div>
				<h1 class="text-2xl font-semibold text-gray-900 mb-1" x-text="currentEmail ? currentEmail.display_title : ''"></h1>
				<p class="text-sm text-gray-600" x-text="currentEmail ? currentEmail.description : ''" x-show="currentEmail && currentEmail.description"></p>
			</div>

			<!-- Two Column Layout: Narrower settings, wider preview -->
			<div class="grid grid-cols-1 lg:grid-cols-5 gap-6">

				<!-- Left Column: Settings (2/5 = 40%) -->
				<div class="lg:col-span-2 space-y-6">
					<?php $this->render_email_settings_column_inline(); ?>
				</div>

				<!-- Right Column: Preview (3/5 = 60%) -->
				<div class="lg:col-span-3 space-y-6">
					<?php $this->render_email_preview_column_inline(); ?>
				</div>

			</div>

		</div>
		<?php
	}

	/**
	 * Render email settings column for inline editing.
	 *
	 * @since 1.1.0
	 *
	 * @return void
	 */
	private function render_email_settings_column_inline(): void {
		?>
		<div class="bg-white border border-gray-900/8 rounded-xl">
			<div class="px-6 pt-6 pb-4">
				<h2 x-show="currentEmail && currentEmail.has_access" class="text-lg font-medium text-gray-900 mb-6">
					<?php esc_html_e( 'Email Settings', 'rewardswp' ); ?>
				</h2>

				<!-- Email Settings Form (only for unlocked emails) -->
				<template x-if="currentEmail && currentEmail.has_access">
				<div class="space-y-6">
					<!-- Email Status Toggle -->
					<div class="flex items-center justify-between">
						<div
							class="flex items-center gap-3 cursor-pointer"
							x-on:click="if (currentEmail && currentEmail.has_access) { emailStatuses[currentEmail.id] = !emailStatuses[currentEmail.id]; }"
						>
							<label class="block text-sm font-medium text-gray-700 cursor-pointer">
								<?php esc_html_e( 'Status', 'rewardswp' ); ?>
							</label>
							<!-- Dynamic status badge -->
							<span x-show="currentEmail && emailStatuses[currentEmail.id]"
								class="inline-flex items-center justify-center px-2 py-1 rounded-full text-xs font-medium shrink-0 leading-none bg-green-100 text-green-800">
								<?php esc_html_e( 'Active', 'rewardswp' ); ?>
							</span>
							<span x-show="currentEmail && !emailStatuses[currentEmail.id]"
								class="inline-flex items-center justify-center px-2 py-1 rounded-full text-xs font-medium shrink-0 leading-none bg-red-100 text-red-800">
								<?php esc_html_e( 'Inactive', 'rewardswp' ); ?>
							</span>
						</div>
						<div>
						<?php
						// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Output is escaped within the component
						echo \Awesomemotive\Rewardswp\Helpers\get_view_component(
							'toggle',
							[
								'section'      => '',
								'name'         => '',
								'is_checked'   => false,
								'x_model'      => 'emailStatuses[currentEmail.id]',
								'no_input'     => true,
								'button_align' => 'left',
							]
						);
						?>
						</div>
					</div>

					<!-- Email Subject -->
					<div>
						<label for="email_subject_inline" class="block text-sm font-semibold mb-2">
							<?php esc_html_e( 'Subject', 'rewardswp' ); ?>
							<span class="text-red-500">*</span>
						</label>
						<div class="relative"
							x-data="mergeTagsDropdown([])"
							x-effect="updateMergeTags(currentEmail ? currentEmail.merge_tags || [] : [])">
						<div class="flex items-center rounded-md bg-white px-3 outline-1 -outline-offset-1 outline-gray-300 focus-within:outline-2 focus-within:-outline-offset-2 focus-within:outline-blue-600">
							<input type="text"
									id="email_subject_inline"
									name="subject"
									x-bind:value="currentEmail ? currentEmail.subject : ''"
									x-on:input="if (currentEmail) { currentEmail.subject = $event.target.value; }"
									class="block min-w-0 grow py-2 pr-8 text-base text-gray-900 placeholder:text-gray-400 focus:outline-none sm:text-sm/6"
									placeholder="<?php esc_attr_e( 'Enter email subject...', 'rewardswp' ); ?>"
									x-ref="subjectInput"
									required>

							<!-- Merge Tags Button -->
							<button type="button"
								class="shrink-0 flex items-center pl-2 text-gray-400 hover:text-blue-600 cursor-pointer"
								x-on:click="toggleDropdown($refs.subjectInput)"
								x-show="currentEmail && currentEmail.merge_tags && currentEmail.merge_tags.length > 0"
								data-tippy-content="<?php esc_attr_e( 'Insert merge tags', 'rewardswp' ); ?>">
								<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
									<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"></path>
								</svg>
							</button>
						</div>

							<!-- Merge Tags Dropdown -->
							<div class="absolute z-10 mt-1 w-full bg-white rounded-md shadow-lg border border-gray-200 transition-all duration-200"
								x-bind:class="dropdownClasses"
								x-show="isOpen"
								x-transition>

								<!-- Search Input -->
								<div class="p-3 border-b border-gray-100">
									<input type="text"
											class="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"
											placeholder="<?php esc_attr_e( 'Search merge tags...', 'rewardswp' ); ?>"
											x-model="searchQuery"
											x-ref="searchInput">
								</div>

								<!-- Merge Tags List -->
								<div class="max-h-64 overflow-y-auto p-2">
									<template x-for="mergeTag in filteredMergeTags" x-key="mergeTag.tag">
										<button type="button"
												class="w-full p-3 text-left bg-white hover:bg-slate-50 border border-gray-200 hover:border-gray-300 rounded-lg mb-2 transition-all duration-200 cursor-pointer"
												x-on:click="insertMergeTag(mergeTag)">
											<!-- Card layout similar to the image -->
											<div class="space-y-2">
												<!-- Tag title with code -->
												<div class="flex items-center space-x-2">
													<span class="text-sm font-medium text-gray-900" x-text="mergeTag.label || mergeTag.tag"></span>
													<code class="bg-gray-100 text-gray-600 px-2 py-1 rounded text-xs font-mono"
															x-text="'{' + mergeTag.tag + '}'"></code>
												</div>

												<!-- Description -->
												<div class="text-xs text-gray-600 leading-relaxed" x-show="mergeTag.description" x-text="mergeTag.description"></div>

												<!-- Example -->
												<div class="text-xs text-gray-500" x-show="mergeTag.example">
													<span class="font-medium"><?php esc_html_e( 'Example:', 'rewardswp' ); ?></span>
													<span class="ml-1" x-text="mergeTag.example"></span>
												</div>
											</div>
										</button>
									</template>

									<!-- No results -->
									<div x-show="filteredMergeTags.length === 0" class="px-4 py-3 text-sm text-gray-500 text-center">
										<?php esc_html_e( 'No merge tags found.', 'rewardswp' ); ?>
									</div>
								</div>
							</div>
						</div>

					</div>

					<!-- Email Banner -->
					<div>
						<?php if ( \Awesomemotive\Rewardswp\Helpers\can_access_rewardswp_feature( 'email_banner' ) ) : ?>
							<!-- PRO Banner Upload Component -->
							<?php
							$this->views_factory->get_view( \Awesomemotive\Rewardswp\Views\Admin\Components\MediaUploadComponentView::class )->render(
								[
									'label'         => __( 'Banner', 'rewardswp' ),
									'help_text'     => __( 'Recommended: 600px wide.', 'rewardswp' ),
									'x_model_id'    => 'currentEmail.banner_attachment_id',
									'x_model_url'   => 'currentEmail.banner_preview_url',
									'x_model_size'  => '',
									'preview_size'  => \Awesomemotive\Rewardswp\Services\EmailsService::EMAIL_BANNER_DEFAULT_SIZE,
									'button_text'   => __( 'Upload Banner', 'rewardswp' ),
									'change_text'   => __( 'Change', 'rewardswp' ),
									'remove_text'   => __( 'Remove', 'rewardswp' ),
									'select_title'  => __( 'Select Email Banner', 'rewardswp' ),
									'select_button' => __( 'Use This Banner', 'rewardswp' ),
									// trigger preview refresh reactively when banner changes
									'on_change'         => 'refreshPreview()',
									'max_height_class'  => 'max-h-20',
								]
							);
							?>
						<?php else : ?>
							<!-- Simple Upgrade Prompt for Banner -->
							<div class="space-y-2">
								<div class="flex items-center gap-2 mb-2">
									<span class="block text-sm font-medium text-gray-700">
										<?php esc_html_e( 'Banner', 'rewardswp' ); ?>
									</span>
									<span class="inline-flex">
										<?php echo wp_kses( get_view_component( 'badge', [ 'style' => 'pro' ] ), kses() ); ?>
									</span>
								</div>

								<?php $upsell_banner = get_upgrade_upsell_data( 'email_banner', 'email_management' ); ?>
								<div class="bg-white border border-gray-200 rounded-lg p-6 text-left">
									<h3 class="text-lg font-medium text-gray-900 mb-3">
										<?php esc_html_e( 'Add a banner image', 'rewardswp' ); ?>
									</h3>
									<p class="text-gray-500 text-sm mb-4">
										<?php esc_html_e( 'Upgrade to add a custom banner image to enhance the look of your email.', 'rewardswp' ); ?>
									</p>
									<a
										href="<?php echo esc_url( $upsell_banner['button_url'] ); ?>"
										target="_blank"
										rel="noopener noreferrer"
										class="inline-flex items-center gap-1 text-sm font-medium text-blue-600 hover:text-blue-500"
									>
										<?php esc_html_e( 'Upgrade to add email banners', 'rewardswp' ); ?>
										<?php echo wp_kses( $this->icon_helper->get_icon( 'external-link', 'h-4 w-4' ), svg_kses() ); ?>
									</a>
								</div>
							</div>
						<?php endif; ?>
					</div>

				</div>
				</template>

				<!-- Inline Upsell (for locked emails) -->
				<template x-if="currentEmail && !currentEmail.has_access">
					<div>
						<!-- Title -->
						<h3 class="text-xl font-semibold text-gray-900 mb-3"
							x-text="$store.emailUpgrade.content[currentEmail.feature_slug]?.title || '<?php echo esc_js( __( 'Upgrade Required', 'rewardswp' ) ); ?>'"></h3>

						<!-- Message -->
						<p class="text-gray-600 text-base mb-6 text-pretty"
							x-text="$store.emailUpgrade.content[currentEmail.feature_slug]?.message || ''"></p>

						<!-- Features List -->
						<ul class="space-y-3 mb-6 pl-0 list-none">
							<template x-for="feature in ($store.emailUpgrade.content[currentEmail.feature_slug]?.features || [])" :key="feature">
								<li class="flex items-center gap-2 text-base text-gray-700">
									<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="flex-shrink-0 text-green-500 h-5 w-5"><path d="M21.801 10A10 10 0 1 1 17 3.335"></path><path d="m9 11 3 3L22 4"></path></svg>
									<span x-text="feature"></span>
								</li>
							</template>
						</ul>

						<!-- Required Plan Notice -->
						<p class="text-sm text-gray-500 mb-4"
							x-html="$store.emailUpgrade.content[currentEmail.feature_slug]?.required_plan || ''"></p>

						<!-- Upgrade Button -->
						<a x-bind:href="$store.emailUpgrade.content[currentEmail.feature_slug]?.button_url || '#'"
							target="_blank"
							rel="noopener noreferrer"
							class="inline-flex justify-center w-full px-6 py-2.5 text-sm rounded-lg font-semibold shadow-sm cursor-pointer items-center transition-colors duration-150 text-white bg-blue-600 border border-transparent hover:bg-blue-700 focus:ring-blue-500 focus:outline-none focus:ring-2 focus:ring-offset-2"
							x-text="$store.emailUpgrade.content[currentEmail.feature_slug]?.button_text || '<?php echo esc_js( __( 'Upgrade Now', 'rewardswp' ) ); ?>'"></a>

						<!-- Compare Plans Link -->
						<div class="mt-3 text-center">
							<a x-bind:href="$store.emailUpgrade.content[currentEmail.feature_slug]?.compare_url || '#'"
								target="_blank"
								rel="noopener noreferrer"
								class="text-sm text-gray-500 hover:text-gray-700 hover:underline hover:underline-offset-4">
								<?php esc_html_e( 'Compare plans', 'rewardswp' ); ?>
							</a>
						</div>
					</div>
				</template>

			</div>
		</div>
		<?php
	}

	/**
	 * Render email preview column for inline editing.
	 *
	 * @since 1.1.0
	 *
	 * @return void
	 */
	private function render_email_preview_column_inline(): void {
		?>
		<div class="bg-white border border-gray-900/8 rounded-xl">
			<div class="p-6">
				<div class="flex items-center justify-between mb-1">
					<h2 class="text-lg font-medium text-gray-900">
						<?php esc_html_e( 'Email Preview', 'rewardswp' ); ?>
					</h2>
					<template x-if="currentEmail">
						<button type="button"
							x-data="{ isTestSending: false }"
							x-on:click="isTestSending = true; sendTestEmail(currentEmail.id).finally(() => { isTestSending = false; });"
							x-bind:disabled="isTestSending"
							class="border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 min-w-[90px] cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed px-3 py-1.5 grid grid-cols-1 grid-rows-1 [grid-template-areas:stack] text-center place-items-center">
							<span class="[grid-area:stack] transition-opacity duration-200" x-bind:class="{ 'invisible': isTestSending, 'visible': !isTestSending }"><?php esc_html_e( 'Send Test', 'rewardswp' ); ?></span>
							<svg class="animate-spin h-4 w-4 [grid-area:stack] transition-opacity duration-200" x-bind:class="{ 'invisible': !isTestSending, 'visible': isTestSending }" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
								<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
								<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
							</svg>
						</button>
					</template>
				</div>
				<p class="text-sm text-gray-500 mb-4"><?php esc_html_e( 'Preview uses sample data. The actual email will display real member data.', 'rewardswp' ); ?></p>

				<!-- Email envelope: subject + sender -->
				<template x-if="currentEmail">
					<div class="border border-gray-900/8 border-b-0 bg-white px-5 py-4">
						<p class="text-base font-semibold text-gray-900 truncate" x-text="(() => {
							let subject = currentEmail.subject || '';
							if (currentEmail.merge_tags) {
								currentEmail.merge_tags.forEach(tag => {
									if (tag.example) subject = subject.replaceAll('{' + tag.tag + '}', tag.example);
								});
							}
							return subject;
						})()"></p>
						<p class="text-sm text-gray-500 mt-0.5" x-text="fromName + ' <' + fromEmail + '>'"></p>
					</div>
				</template>

				<!-- Auto-Resizing Preview Frame with Loading -->
				<div class="border border-gray-900/8 overflow-hidden bg-gray-50 relative">
					<!-- Loading Spinner -->
					<div id="email-preview-loading-inline" class="absolute inset-0 flex items-center justify-center bg-gray-50 z-10" style="display: flex;">
						<div class="flex flex-col items-center space-y-3">
							<svg class="animate-spin h-6 w-6 text-gray-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
								<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
								<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
							</svg>
							<p class="text-sm text-gray-500"><?php esc_html_e( 'Loading preview...', 'rewardswp' ); ?></p>
						</div>
					</div>

					<!-- Dynamic iframe container -->
					<div id="email-preview-container-inline" class="w-full" style="min-height: 200px; height: 400px;">
						<!-- Iframe will be dynamically created here -->
					</div>
				</div>

			</div>
		</div>
		<?php
	}
}
