/**
 * Live email preview for newsletter and cart-recovery designers.
 * Initial markup is server-rendered (PHP); this script syncs on user input
 * after Alpine has bound the form (see suitemkt3k-admin.js).
 */
(function (window) {
	'use strict';

	const cfg = window.suitemkt3kEmailPreview || {};

	function q(root, sel) {
		return root ? root.querySelector(sel) : null;
	}

	function val(form, name) {
		const el = form ? form.querySelector('[name="' + name + '"]') : null;
		if (!el) {
			return '';
		}
		if (el.type === 'checkbox') {
			return el.checked ? el.value : '';
		}
		return String(el.value || '');
	}

	function hexColor(form, name, fallback) {
		const raw = val(form, name).trim();
		if (/^#([A-Fa-f0-9]{3}|[A-Fa-f0-9]{6})$/.test(raw)) {
			return raw;
		}
		return fallback || cfg.defaultAccent || '#2AB2E5';
	}

	function replaceName(text, sample) {
		return String(text || '').split('{{name}}').join(sample);
	}

	function show(el, visible) {
		if (!el) {
			return;
		}
		el.classList.toggle('wmk-preview-hidden', !visible);
	}

	function setText(el, text) {
		if (el) {
			el.textContent = text;
		}
	}

	function gridInitial(grid) {
		const raw = grid.getAttribute('data-wmk-initial');
		if (!raw) {
			return null;
		}
		try {
			return JSON.parse(raw);
		} catch (e) {
			return null;
		}
	}

	function fieldOrInitial(form, name, initial, key) {
		const v = val(form, name);
		if ('' !== v) {
			return v;
		}
		if (initial && typeof initial[key] !== 'undefined' && null !== initial[key]) {
			return String(initial[key]);
		}
		return '';
	}

	function syncNewsletter(form, preview, initial) {
		const root = q(preview, '[data-wmk-preview-root]');
		if (!root || !form) {
			return;
		}

		const sample = cfg.previewName || 'there';
		let heading = fieldOrInitial(form, 'content[heading]', initial, 'heading');
		const subject = fieldOrInitial(form, 'subject', initial, 'subject');
		if (!heading) {
			heading = subject;
		}
		if (!heading) {
			heading = cfg.headingFallback || '';
		}

		let body = fieldOrInitial(form, 'content[body]', initial, 'body');
		if (!body) {
			body = cfg.bodyFallback || '';
		} else {
			body = replaceName(body, sample);
		}

		let cta = fieldOrInitial(form, 'content[cta_label]', initial, 'cta_label');
		if (!cta) {
			cta = cfg.ctaFallback || '';
		}

		const accentFallback = (initial && initial.accent) ? String(initial.accent) : (cfg.defaultAccent || '#2AB2E5');
		const accent = hexColor(form, 'content[accent]', accentFallback);
		const headerColorFallback = (initial && initial.header_color) ? String(initial.header_color) : accent;
		const headerColor = hexColor(form, 'content[header_color]', headerColorFallback);
		const secondaryFallback = (initial && initial.secondary_accent) ? String(initial.secondary_accent) : accent;
		const secondary = hexColor(form, 'content[secondary_accent]', secondaryFallback);
		const badgeLabel = fieldOrInitial(form, 'content[badge_label]', initial, 'badge_label');
		let ctaRadius = parseInt(fieldOrInitial(form, 'content[cta_radius]', initial, 'cta_radius'), 10);
		if (!isFinite(ctaRadius) || ctaRadius < 0) {
			ctaRadius = 10;
		}
		if (ctaRadius > 99) {
			ctaRadius = 99;
		}
		const template = fieldOrInitial(form, 'template_key', initial, 'template') || 'classic';
		const imageUrl = fieldOrInitial(form, 'content[image_url]', initial, 'image_url');
		const companyLogo = cfg.logoUrl || '';
		const brand = cfg.brand || '';
		const preheader = fieldOrInitial(form, 'content[preheader]', initial, 'preheader');
		const footerColorFallback = (initial && initial.footer_color) ? String(initial.footer_color) : '#94A3B8';
		const footerColor = hexColor(form, 'content[footer_color]', footerColorFallback);
		const ctaUrl = fieldOrInitial(form, 'content[cta_url]', initial, 'cta_url') || '#';
		const unsubText = fieldOrInitial(form, 'content[unsubscribe_text]', initial, 'unsubscribe_text');
		let unsubCta = fieldOrInitial(form, 'content[unsubscribe_cta]', initial, 'unsubscribe_cta');
		if (!unsubCta) {
			unsubCta = cfg.unsubscribeFallback || '';
		}

		const hasLogo = '' !== companyLogo;
		const hasImage = '' !== imageUrl;
		const isAnnounce = template === 'announce';
		const showBadge = template !== 'classic' && '' !== badgeLabel;

		root.className = 'wmk-preview-email wmk-pe-' + template;

		show(q(preview, '[data-wmk-preview-logo-wrap]'), hasLogo);
		show(q(preview, '[data-wmk-preview-accent-bar]'), hasLogo);
		show(q(preview, '[data-wmk-preview-header]'), !hasLogo);

		const accentBar = q(preview, '[data-wmk-preview-accent-bar]');
		const header = q(preview, '[data-wmk-preview-header]');
		const ctaEl = q(preview, '[data-wmk-preview-cta]');
		const announceBand = q(preview, '[data-wmk-preview-announce-band]');
		const headingEl = q(preview, '[data-wmk-preview-heading]');
		const headingBand = q(preview, '[data-wmk-preview-heading-band]');

		if (accentBar) {
			accentBar.style.background = accent;
		}
		if (header && !hasLogo) {
			header.style.background = headerColor;
		} else if (header) {
			header.style.background = '';
		}
		if (announceBand) {
			announceBand.style.background = secondary;
		}
		if (ctaEl) {
			ctaEl.style.borderRadius = ctaRadius + 'px';
			if (isAnnounce) {
				ctaEl.style.background = 'transparent';
				ctaEl.style.color = accent;
				ctaEl.style.border = '2px solid ' + accent;
			} else {
				ctaEl.style.background = accent;
				ctaEl.style.color = '#fff';
				ctaEl.style.border = '0';
			}
			ctaEl.href = ctaUrl;
		}

		const logoImg = q(preview, '[data-wmk-preview-logo]');
		if (logoImg && hasLogo) {
			logoImg.src = companyLogo;
		}

		show(q(preview, '[data-wmk-preview-image-wrap]'), hasImage && !isAnnounce);
		show(q(preview, '[data-wmk-preview-image-wrap-announce]'), hasImage && isAnnounce);
		const hero = q(preview, '[data-wmk-preview-image]');
		const heroAnnounce = q(preview, '[data-wmk-preview-image-announce]');
		if (hero) {
			hero.src = imageUrl;
		}
		if (heroAnnounce) {
			heroAnnounce.src = imageUrl;
		}

		setText(q(preview, '[data-wmk-preview-brand]'), brand);
		setText(headingEl, heading);
		setText(headingBand, heading);
		show(headingEl, !isAnnounce);
		show(announceBand, isAnnounce);
		setText(q(preview, '[data-wmk-preview-body]'), body);
		setText(q(preview, '[data-wmk-preview-cta]'), cta);

		const footerBrand = (cfg.footerText || brand || '').trim();
		const footerLegal = (cfg.footerAddress || '').trim();
		const footerBrandEl = q(preview, '[data-wmk-preview-footer-brand]');
		const footerLegalEl = q(preview, '[data-wmk-preview-footer-address]');
		show(footerBrandEl, '' !== footerBrand);
		setText(footerBrandEl, footerBrand);
		show(footerLegalEl, '' !== footerLegal);
		setText(footerLegalEl, footerLegal);

		const footerEl = q(preview, '[data-wmk-preview-footer]');
		show(footerEl, '' !== preheader);
		setText(footerEl, preheader);
		if (footerEl) {
			footerEl.style.color = footerColor;
		}

		const badgeAbove = q(preview, '[data-wmk-preview-badge-wrap]');
		const badgeInner = q(preview, '[data-wmk-preview-badge-wrap-inner]');
		const badgeAboveEl = q(preview, '[data-wmk-preview-badge]');
		const badgeInnerEl = q(preview, '[data-wmk-preview-badge-inner]');
		show(badgeAbove, showBadge && isAnnounce);
		show(badgeInner, showBadge && !isAnnounce);
		setText(badgeAboveEl, badgeLabel);
		setText(badgeInnerEl, badgeLabel);
		if (badgeAboveEl) {
			badgeAboveEl.style.color = accent;
			badgeAboveEl.style.background = accent + '22';
			if (isAnnounce && badgeAbove && badgeAbove.parentElement) {
				badgeAbove.style.textAlign = 'center';
			}
		}
		if (badgeInnerEl) {
			badgeInnerEl.style.color = secondary;
		}

		const bodyEl = q(preview, '.wmk-pe-body');
		if (bodyEl && template === 'welcome') {
			bodyEl.style.borderLeftColor = secondary;
		} else if (bodyEl) {
			bodyEl.style.borderLeftColor = '';
		}
		if (bodyEl && template === 'reminder') {
			bodyEl.style.borderColor = secondary;
		}

		setText(q(preview, '[data-wmk-preview-unsub-text]'), unsubText);
		setText(q(preview, '[data-wmk-preview-unsub-cta]'), unsubCta);
	}

	function syncCart(form, preview, initial) {
		const root = q(preview, '[data-wmk-preview-root]');
		if (!root || !form) {
			return;
		}

		const sample = cfg.previewName || 'there';
		let heading = fieldOrInitial(form, 'design[heading]', initial, 'heading');
		const subject = fieldOrInitial(form, 'subject', initial, 'subject');
		if (!heading) {
			heading = subject;
		}
		if (!heading) {
			heading = '—';
		}

		let body = fieldOrInitial(form, 'design[body]', initial, 'body');
		if (!body) {
			body = cfg.bodyFallback || '';
		} else {
			body = replaceName(body, sample);
		}

		const accentFallback = (initial && initial.accent) ? String(initial.accent) : (cfg.defaultAccent || '#2AB2E5');
		const accent = hexColor(form, 'design[accent]', accentFallback);
		let ctaRadius = parseInt(fieldOrInitial(form, 'design[cta_radius]', initial, 'cta_radius'), 10);
		if (!isFinite(ctaRadius) || ctaRadius < 0) {
			ctaRadius = 10;
		}
		if (ctaRadius > 99) {
			ctaRadius = 99;
		}
		const brand = cfg.brand || '';
		const preheader = fieldOrInitial(form, 'design[preheader]', initial, 'preheader');
		const ctaLabel = fieldOrInitial(form, 'design[cta_label]', initial, 'cta_label');
		const validityTpl = fieldOrInitial(form, 'design[validity_text]', initial, 'validity_text') || (cfg.validityTemplate || '');
		const hours = fieldOrInitial(form, 'discount_validity_hours', initial, 'discount_validity_hours') || '24';
		const percent = fieldOrInitial(form, 'discount_percent', initial, 'discount_percent');
		const couponSelect = form.querySelector('[name="recovery_coupon_id"]');
		const couponId = couponSelect ? parseInt(couponSelect.value, 10) || 0 : parseInt(initial && initial.attached_coupon_id, 10) || 0;
		let couponLabel = '';
		let couponName = '';
		if (couponSelect && couponSelect.selectedOptions && couponSelect.selectedOptions[0]) {
			couponLabel = couponSelect.selectedOptions[0].dataset.label || '';
			couponName = couponSelect.selectedOptions[0].dataset.name || '';
		} else if (initial) {
			couponLabel = String(initial.attached_coupon_label || '');
			couponName = String(initial.attached_coupon_name || '');
		}

		const companyLogo = cfg.logoUrl || '';
		const hasLogo = '' !== companyLogo;
		const hasCoupon = couponId > 0;
		const hasPercent = !hasCoupon && '' !== percent;

		show(q(preview, '[data-wmk-preview-logo-wrap]'), hasLogo);
		show(q(preview, '[data-wmk-preview-accent-bar]'), hasLogo);
		show(q(preview, '[data-wmk-preview-header]'), !hasLogo);

		const accentBar = q(preview, '[data-wmk-preview-accent-bar]');
		const header = q(preview, '[data-wmk-preview-header]');
		const ctaEl = q(preview, '[data-wmk-preview-cta]');

		if (accentBar) {
			accentBar.style.background = accent;
		}
		if (header) {
			header.style.background = accent;
		}
		if (ctaEl) {
			ctaEl.style.background = accent;
			ctaEl.style.borderRadius = ctaRadius + 'px';
		}

		const logoImg = q(preview, '[data-wmk-preview-logo]');
		if (logoImg && hasLogo) {
			logoImg.src = companyLogo;
		}

		setText(q(preview, '[data-wmk-preview-header-text]'), brand);
		setText(q(preview, '[data-wmk-preview-heading]'), heading);
		setText(q(preview, '[data-wmk-preview-body]'), body);

		show(q(preview, '[data-wmk-preview-coupon]'), hasCoupon);
		setText(q(preview, '[data-wmk-preview-coupon-label]'), couponLabel);
		setText(q(preview, '[data-wmk-preview-coupon-name]'), couponName);

		show(q(preview, '[data-wmk-preview-percent]'), hasPercent);
		setText(q(preview, '[data-wmk-preview-percent-value]'), percent);

		let validityLine = '';
		if ((hasCoupon || hasPercent) && validityTpl && hours) {
			validityLine = validityTpl
				.split('{{hours}}').join(hours)
				.split('{{code}}').join(couponName)
				.split('{{amount}}').join(couponLabel);
		}
		show(q(preview, '[data-wmk-preview-validity]'), '' !== validityLine);
		setText(q(preview, '[data-wmk-preview-validity-text]'), validityLine);

		show(q(preview, '[data-wmk-preview-cta-wrap]'), '' !== ctaLabel);
		setText(q(preview, '[data-wmk-preview-cta]'), ctaLabel);

		show(q(preview, '[data-wmk-preview-preheader-wrap]'), '' !== preheader);
		setText(q(preview, '[data-wmk-preview-preheader]'), preheader);

		const unsubText = fieldOrInitial(form, 'design[unsubscribe_text]', initial, 'unsubscribe_text');
		let unsubCta = fieldOrInitial(form, 'design[unsubscribe_cta]', initial, 'unsubscribe_cta');
		if (!unsubCta) {
			unsubCta = cfg.unsubscribeFallback || '';
		}
		setText(q(preview, '[data-wmk-preview-unsub-text]'), unsubText);
		setText(q(preview, '[data-wmk-preview-unsub-cta]'), unsubCta);

		const footerBrand = (cfg.footerText || brand || '').trim();
		const footerLegal = (cfg.footerAddress || '').trim();
		show(q(preview, '[data-wmk-preview-footer-brand]'), '' !== footerBrand);
		setText(q(preview, '[data-wmk-preview-footer-brand]'), footerBrand);
		show(q(preview, '[data-wmk-preview-footer-address]'), '' !== footerLegal);
		setText(q(preview, '[data-wmk-preview-footer-address]'), footerLegal);
	}

	function syncCoupon(form, preview, initial) {
		const root = q(preview, '[data-wmk-preview-root]');
		if (!root || !form) {
			return;
		}

		const sample = cfg.previewName || 'there';
		const sampleCampaign = cfg.sampleCampaign || 'Sample campaign';
		const sampleCode = cfg.sampleCode || 'SAMPLE10';
		const sampleMarketing = cfg.sampleMarketing || '';

		let heading = fieldOrInitial(form, 'design[heading]', initial, 'heading');
		const subject = fieldOrInitial(form, 'subject', initial, 'subject');
		if (!heading) {
			heading = subject;
		}
		if (!heading) {
			heading = '—';
		}
		heading = heading
			.split('{{name}}').join(sample)
			.split('{{coupon_name}}').join(sampleCampaign)
			.split('{{code}}').join(sampleCode);

		let body = fieldOrInitial(form, 'design[body]', initial, 'body');
		if (!body) {
			body = cfg.bodyFallback || '';
		} else {
			body = body
				.split('{{name}}').join(sample)
				.split('{{first_name}}').join(sample)
				.split('{{code}}').join(sampleCode)
				.split('{{coupon_name}}').join(sampleCampaign)
				.split('{{marketing}}').join(sampleMarketing);
		}

		const accentFallback = (initial && initial.accent) ? String(initial.accent) : (cfg.defaultAccent || '#2AB2E5');
		const accent = hexColor(form, 'design[accent]', accentFallback);
		let ctaRadius = parseInt(fieldOrInitial(form, 'design[cta_radius]', initial, 'cta_radius'), 10);
		if (!isFinite(ctaRadius) || ctaRadius < 0) {
			ctaRadius = 10;
		}
		if (ctaRadius > 99) {
			ctaRadius = 99;
		}
		const brand = cfg.brand || '';
		const preheader = fieldOrInitial(form, 'design[preheader]', initial, 'preheader');
		const ctaLabel = fieldOrInitial(form, 'design[cta_label]', initial, 'cta_label');
		const companyLogo = cfg.logoUrl || '';
		const hasLogo = '' !== companyLogo;

		show(q(preview, '[data-wmk-preview-logo-wrap]'), hasLogo);
		show(q(preview, '[data-wmk-preview-accent-bar]'), hasLogo);
		show(q(preview, '[data-wmk-preview-header]'), !hasLogo);

		const accentBar = q(preview, '[data-wmk-preview-accent-bar]');
		const header = q(preview, '[data-wmk-preview-header]');
		const ctaEl = q(preview, '[data-wmk-preview-cta]');

		if (accentBar) {
			accentBar.style.background = accent;
		}
		if (header) {
			header.style.background = accent;
		}
		if (ctaEl) {
			ctaEl.style.background = accent;
			ctaEl.style.borderRadius = ctaRadius + 'px';
		}

		const logoImg = q(preview, '[data-wmk-preview-logo]');
		if (logoImg && hasLogo) {
			logoImg.src = companyLogo;
		}

		setText(q(preview, '[data-wmk-preview-header-text]'), brand);
		setText(q(preview, '[data-wmk-preview-heading]'), heading);
		setText(q(preview, '[data-wmk-preview-body]'), body.replace(/<[^>]+>/g, ''));

		show(q(preview, '[data-wmk-preview-cta-wrap]'), '' !== ctaLabel);
		setText(q(preview, '[data-wmk-preview-cta]'), ctaLabel);

		show(q(preview, '[data-wmk-preview-preheader-wrap]'), '' !== preheader);
		setText(q(preview, '[data-wmk-preview-preheader]'), preheader);

		const unsubText = fieldOrInitial(form, 'design[unsubscribe_text]', initial, 'unsubscribe_text');
		let unsubCta = fieldOrInitial(form, 'design[unsubscribe_cta]', initial, 'unsubscribe_cta');
		if (!unsubCta) {
			unsubCta = cfg.unsubscribeFallback || '';
		}
		setText(q(preview, '[data-wmk-preview-unsub-text]'), unsubText);
		setText(q(preview, '[data-wmk-preview-unsub-cta]'), unsubCta);

		const footerBrand = (cfg.footerText || brand || '').trim();
		const footerLegal = (cfg.footerAddress || '').trim();
		show(q(preview, '[data-wmk-preview-footer-brand]'), '' !== footerBrand);
		setText(q(preview, '[data-wmk-preview-footer-brand]'), footerBrand);
		show(q(preview, '[data-wmk-preview-footer-address]'), '' !== footerLegal);
		setText(q(preview, '[data-wmk-preview-footer-address]'), footerLegal);
	}

	function bindDesigner(grid) {
		if (grid.getAttribute('data-wmk-preview-bound') === '1') {
			return;
		}
		grid.setAttribute('data-wmk-preview-bound', '1');

		const type = grid.getAttribute('data-wmk-designer');
		const form = grid.querySelector('form');
		const preview = grid.querySelector('[data-wmk-email-preview]');
		if (!form || !preview) {
			return;
		}

		const initial = gridInitial(grid);

		const sync = function () {
			if ('newsletter' === type) {
				syncNewsletter(form, preview, initial);
			} else if ('cart' === type) {
				syncCart(form, preview, initial);
			} else if ('coupon' === type) {
				syncCoupon(form, preview, initial);
			}
		};

		form.addEventListener('input', sync);
		form.addEventListener('change', sync);
	}

	window.wmkInitEmailPreview = function () {
		document.querySelectorAll('[data-wmk-designer]').forEach(bindDesigner);
	};

	window.wmkSyncEmailPreview = function () {
		document.querySelectorAll('[data-wmk-designer]').forEach(function (grid) {
			const form = grid.querySelector('form');
			const preview = grid.querySelector('[data-wmk-email-preview]');
			const type = grid.getAttribute('data-wmk-designer');
			const initial = gridInitial(grid);
			if (!form || !preview) {
				return;
			}
			if ('newsletter' === type) {
				syncNewsletter(form, preview, initial);
			} else if ('cart' === type) {
				syncCart(form, preview, initial);
			} else if ('coupon' === type) {
				syncCoupon(form, preview, initial);
			}
		});
	};
})(window);
