/**
 * CartCue — Live email preview pane.
 *
 * Wraps the email action card in a split-pane layout (form on the left, sticky
 * iframe preview on the right). Listens to subject/body changes, debounces, and
 * POSTs to the existing cartcue_preview_email AJAX endpoint with inline=1.
 *
 * Mounts only when the action card has a `[body]` textarea (i.e. it's a
 * send_email action). Safe to load on every play-editor page — does nothing
 * when there's nothing to preview.
 */
(function ($) {
	'use strict';

	if (!window.cartcueAdmin || !cartcueAdmin.nonces || !cartcueAdmin.nonces.preview_email) {
		return;
	}

	var DEBOUNCE_MS = 350;
	var strings = (cartcueAdmin.buildFeatures && cartcueAdmin.buildFeatures.strings) || {};

	function debounce(fn, wait) {
		var t;
		return function () {
			var ctx = this, args = arguments;
			clearTimeout(t);
			t = setTimeout(function () { fn.apply(ctx, args); }, wait);
		};
	}

	function wrapActionCardBody($card) {
		if ($card.children('.ap-action-card__body').length) {
			return $card.children('.ap-action-card__body').first();
		}
		var $wrap = $('<div class="ap-action-card__body"></div>');
		$card.children().not('.ap-live-preview').detach().appendTo($wrap);
		$card.prepend($wrap);
		return $wrap;
	}

	function unmountPreviewPaneFor($card) {
		$card.find('.ap-live-preview').remove();
		$card.find('.ap-preview-panel-toggle').remove();
		$card.removeClass('ap-action-card--split ap-action-card--preview-collapsed');
		var $wrap = $card.children('.ap-action-card__body');
		if ($wrap.length) {
			$wrap.children().detach().appendTo($card);
			$wrap.remove();
		}
		$card.removeData('cartcuePreviewMounted');
	}

	var PREVIEW_STORAGE_KEY = 'cartcue_live_preview_open';

	function isPreviewOpen() {
		return window.localStorage.getItem(PREVIEW_STORAGE_KEY) === '1';
	}

	function mountPreviewToggle($card, $pane, attempt) {
		attempt = attempt || 0;
		var $stepHead = $card.find('.ap-email-step--content .ap-email-step__head').first();
		if (!$stepHead.length) {
			if (attempt < 8) {
				setTimeout(function () { mountPreviewToggle($card, $pane, attempt + 1); }, 80);
			}
			return;
		}
		if ($stepHead.find('.ap-preview-panel-toggle').length) {
			return;
		}

		var $toggle = $(
			'<button type="button" class="ap-preview-panel-toggle" aria-controls="ap-live-preview-pane" aria-expanded="false">' +
				'<i class="ti ti-eye" aria-hidden="true"></i>' +
				'<span class="ap-preview-panel-toggle__text">Show live preview</span>' +
			'</button>'
		);
		$stepHead.append($toggle);
		$pane.attr('id', 'ap-live-preview-pane');

		function setPreviewOpen(open) {
			$card.toggleClass('ap-action-card--preview-collapsed', !open);
			$pane.toggle(open);
			$toggle.attr('aria-expanded', open ? 'true' : 'false');
			$toggle.toggleClass('is-active', open);
			$toggle.find('.ap-preview-panel-toggle__text').text(
				open
					? (strings.previewHide || 'Hide live preview')
					: (strings.previewShow || 'Show live preview')
			);
			try {
				window.localStorage.setItem(PREVIEW_STORAGE_KEY, open ? '1' : '0');
			} catch (err) {
				// Ignore private browsing quota errors.
			}
			if (open && $pane.data('cartcuePreviewFetch')) {
				$pane.data('cartcuePreviewFetch')();
			}
		}

		$toggle.on('click', function () {
			setPreviewOpen($card.hasClass('ap-action-card--preview-collapsed'));
		});

		setPreviewOpen(isPreviewOpen());
	}

	function mountPreviewPaneFor($card) {
		if ($card.data('cartcuePreviewMounted')) { return; }
		var $body = $card.find('textarea[name*="[body]"]').first();
		if (!$body.length) { return; }

		$card.data('cartcuePreviewMounted', true);

		// One grid row: form stack (left) + live preview (right, toggleable).
		$card.addClass('ap-action-card--split');
		wrapActionCardBody($card);

		var playId = parseInt($card.data('play-id'), 10) || 0;
		var adminEmail = (cartcueAdmin && cartcueAdmin.adminEmail) ? cartcueAdmin.adminEmail : '';

		// Build the preview pane (preview + send test live together).
		var $pane = $(
			'<aside class="ap-live-preview" aria-live="polite" aria-label="Live email preview">' +
				'<div class="ap-live-preview__head">' +
					'<span class="ap-live-preview__title">Preview</span>' +
					'<div class="ap-live-preview__vp-group" role="group" aria-label="Preview device">' +
						'<button type="button" class="ap-live-preview__vp-btn is-active" data-vp="desktop">Desktop</button>' +
						'<button type="button" class="ap-live-preview__vp-btn" data-vp="mobile">Mobile</button>' +
					'</div>' +
					'<span class="ap-live-preview__status" data-status>—</span>' +
				'</div>' +
				'<div class="ap-live-preview__subject-row">' +
					'<span class="ap-live-preview__subject-label">Subject</span>' +
					'<span class="ap-live-preview__subject" data-preview-subject></span>' +
				'</div>' +
				'<div class="ap-live-preview__iframe-wrap">' +
					'<iframe class="ap-live-preview__iframe" data-preview-iframe ' +
					'  title="Email preview" referrerpolicy="no-referrer" sandbox="allow-same-origin"></iframe>' +
					'<div class="ap-live-preview__empty" data-preview-empty>' +
						(strings.previewEmpty || 'Start typing — your email shows up here in real time.') +
					'</div>' +
					'<button type="button" class="ap-live-preview__refresh" data-preview-refresh title="Force refresh">↻</button>' +
				'</div>' +
				'<div class="ap-live-preview__test-bar">' +
					'<label class="ap-live-preview__test-label" for="ap-test-to">Send test to</label>' +
					'<input type="email" id="ap-test-to" class="ap-input ap-test-to-input" ' +
					'  value="" placeholder="you@example.com">' +
					'<button type="button" id="ap-test-btn" class="ap-btn ap-btn-test" data-play="' + playId + '">' +
					'<i class="ti ti-send" aria-hidden="true"></i> Send test</button>' +
				'</div>' +
			'</aside>'
		);
		$card.append($pane);

		var $legacyTest = $card.find('.ap-uni-test-inline');
		if ($legacyTest.length) {
			var legacyEmail = $legacyTest.find('.ap-test-to-input').val();
			if (legacyEmail) {
				$pane.find('.ap-test-to-input').val(legacyEmail);
			}
			$legacyTest.remove();
		}
		$pane.find('.ap-test-to-input').each(function () {
			if (!$(this).val()) {
				$(this).val(adminEmail);
			}
		});

		$card.find('.cartcue-builder').addClass('cartcue-builder--external-preview');
		mountPreviewToggle($card, $pane);

		var $iframeWrap = $pane.find('.ap-live-preview__iframe-wrap');
		var $iframe  = $pane.find('[data-preview-iframe]');
		var $subject = $pane.find('[data-preview-subject]');
		var $status  = $pane.find('[data-status]');
		var $empty   = $pane.find('[data-preview-empty]');

		function setStatus(text, kind) {
			$status.text(text || '').attr('data-kind', kind || '');
		}

		var lastBody = '';
		var inflight = null;

		function fetchPreview() {
			var subjectVal = $card.find('input[name*="[subject]"]').first().val() || '';
			var bodyVal    = $body.val() || '';
			var triggerSlug = $('input[name="trigger_slug"]:checked').val() || 'order_paid';

			if (!bodyVal.trim()) {
				$iframe.attr('srcdoc', '');
				$empty.show();
				$subject.text(subjectVal || '—');
				setStatus('');
				return;
			}

			$empty.hide();
			setStatus(strings.previewLoading || 'Rendering…', 'loading');

			if (inflight && inflight.abort) { inflight.abort(); }

			inflight = $.post(cartcueAdmin.ajaxUrl, {
				action: 'cartcue_preview_email',
				nonce: cartcueAdmin.nonces.preview_email,
				subject: subjectVal,
				body: bodyVal,
				trigger_slug: triggerSlug,
				inline: 1
			}).done(function (res) {
				if (res && res.success && res.data) {
					$subject.text(res.data.subject || subjectVal || '—');
					$iframe.attr('srcdoc', res.data.html || '');
					setStatus('Updated · ' + new Date().toLocaleTimeString(), 'ok');
					lastBody = bodyVal;
				} else {
					setStatus('Preview unavailable', 'err');
				}
			}).fail(function () {
				setStatus('Preview unavailable', 'err');
			});
		}

		var debounced = debounce(fetchPreview, DEBOUNCE_MS);

		// Wire inputs.
		$card.on('input change', 'textarea[name*="[body]"], input[name*="[subject]"]', debounced);
		// TinyMCE / classic editor — listen on the iframe contents once initialized.
		var tinymceHook = setInterval(function () {
			if (typeof window.tinymce !== 'undefined') {
				var ed = window.tinymce.activeEditor;
				if (ed && !ed._cartcueHooked) {
					ed._cartcueHooked = true;
					ed.on('input change keyup undo redo', function () {
						// Sync TinyMCE content back into the textarea before previewing.
						ed.save();
						debounced();
					});
				}
			}
		}, 600);
		setTimeout(function () { clearInterval(tinymceHook); }, 10000);

		// Trigger change → trigger sample data changes too.
		$(document).on('change', 'input[name="trigger_slug"]', debounced);

		$pane.on('click', '[data-preview-refresh]', function () { fetchPreview(); });

		$pane.on('click', '.ap-live-preview__vp-btn', function () {
			var vp = $(this).data('vp') || 'desktop';
			$pane.find('.ap-live-preview__vp-btn').removeClass('is-active');
			$(this).addClass('is-active');
			$iframeWrap.attr('data-viewport', vp);
		});

		$pane.data('cartcuePreviewFetch', fetchPreview);

		// Initial render when preview panel is visible.
		if (!$card.hasClass('ap-action-card--preview-collapsed')) {
			setTimeout(fetchPreview, 250);
		}
	}

	$(function () {
		// One mount per email-action card on the page.
		$('#ap-actions-list .ap-action-card').each(function () {
			var $card = $(this);
			var slug  = $card.find('.ap-action-type').val();
			if ('send_email' === slug) {
				mountPreviewPaneFor($card);
			}
		});

		// Mount / tear down when the action type changes.
		$(document).on('change', '.ap-action-type', function () {
			var $card = $(this).closest('.ap-action-card');
			if ('send_email' !== $(this).val()) {
				unmountPreviewPaneFor($card);
				return;
			}
			// Wait a tick for the fields to render.
			setTimeout(function () { mountPreviewPaneFor($card); }, 50);
		});
	});

})(jQuery);
