/**
 * SuiteMkt3k frontend behaviour for banner, popup (with step 2 slide-left) and subscription forms.
 */
(function () {
	'use strict';
	const cfg = window.SuiteMkt3kFront || {};

	function getCookie(name) {
		const value = '; ' + document.cookie;
		const parts = value.split('; ' + name + '=');
		if (parts.length === 2) return parts.pop().split(';').shift();
		return '';
	}
	function setCookie(name, value, days) {
		const d = new Date();
		d.setTime(d.getTime() + (days || 7) * 24 * 60 * 60 * 1000);
		document.cookie = name + '=' + value + ';expires=' + d.toUTCString() + ';path=/;SameSite=Lax';
	}

	function track(couponId, type) {
		if (!cfg.rest) return;
		try {
			fetch(cfg.rest + '/public/coupon/track', {
				method: 'POST',
				headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': cfg.nonce || '' },
				credentials: 'same-origin',
				body: JSON.stringify({ coupon_id: couponId, type: type })
			});
		} catch (e) {}
	}

	function copyCodeFrom(el) {
		const root = el.closest('[data-coupon-code]') || el.closest('[data-coupon]');
		const code = root ? (root.getAttribute('data-coupon-code') || '').trim() : '';
		if (code && navigator.clipboard) {
			navigator.clipboard.writeText(code);
			return code;
		}
		return '';
	}

	function initBanner() {
		document.querySelectorAll('.wmk-banner').forEach(function (banner) {
			const id = banner.getAttribute('data-coupon');
			if (getCookie('wmk_banner_' + id)) { banner.style.display = 'none'; return; }
			track(id, 'impression');
			const cta = banner.querySelector('.wmk-banner-cta');
			if (!cta) return;
			cta.addEventListener('click', function () {
				const action = cta.getAttribute('data-action');
				track(id, 'click');
				if (action === 'copy') {
					const copied = copyCodeFrom(banner);
					if (copied) {
						const codeEl = cta.querySelector('.wmk-cta-code');
						if (codeEl) codeEl.textContent = '✓ ' + copied;
					}
					setCookie('wmk_banner_' + id, '1', 7);
				} else {
					document.querySelectorAll('.wmk-popup-root[data-coupon="' + id + '"]').forEach(function (root) {
						setCookie('wmk_popup_' + id, '', -1);
						root.hidden = false;
						root.style.display = '';
						root.classList.add('is-step2');
					});
				}
			});
		});
	}

	function initPopup() {
		document.querySelectorAll('.wmk-popup-root').forEach(function (root) {
			const id = root.getAttribute('data-coupon');
			const delay = parseInt(root.getAttribute('data-delay') || '4', 10);
			if (getCookie('wmk_popup_' + id)) return;
			setTimeout(function(){ root.hidden = false; track(id, 'impression'); }, Math.max(0, delay) * 1000);

			function closePopup(e) {
				if (e) { e.preventDefault(); e.stopPropagation(); }
				root.hidden = true;
				root.style.display = 'none';
				setCookie('wmk_popup_' + id, '1', 7);
			}
			root.querySelectorAll('[data-close]').forEach(function(el){
				el.addEventListener('click', closePopup);
			});
			document.addEventListener('keydown', function (e) {
				if (e.key === 'Escape' && !root.hidden) closePopup(e);
			});

			const ctaStep1 = root.querySelector('.wmk-popup-step1 .wmk-popup-cta');
			if (ctaStep1) {
				ctaStep1.addEventListener('click', function () {
					const action = ctaStep1.getAttribute('data-action');
					track(id, 'click');
					if (action === 'optin') {
						root.classList.add('is-step2');
					} else {
						const copied = copyCodeFrom(root);
						if (copied) {
							const codeEl = ctaStep1.querySelector('.wmk-cta-code');
							if (codeEl) codeEl.textContent = '✓ ' + copied;
						}
					}
				});
			}

			const form = root.querySelector('.wmk-popup-form');
			if (form) {
				form.addEventListener('submit', function (e) {
					e.preventDefault();
					const data = new FormData(form);
					const body = {};
					data.forEach(function (v, k) { body[k] = v; });
					body._wpnonce = cfg.nonce;
					body.consent = !!body.consent;
					fetch(cfg.rest + '/public/coupon/optin', {
						method: 'POST',
						headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': cfg.nonce || '' },
						credentials: 'same-origin',
						body: JSON.stringify(body)
					}).then(function (res) { return res.json(); }).then(function (json) {
						if (json && json.ok) {
							form.innerHTML = '<p style="text-align:center;">' + (json.message || 'Thanks!') + '</p>';
							setCookie('wmk_popup_' + id, '1', 30);
						} else if (json && json.message) {
							alert(json.message);
						}
					});
				});
			}
		});
	}

	function initForms() {
		document.querySelectorAll('.wmk-form').forEach(function (form) {
			form.addEventListener('submit', function (e) {
				e.preventDefault();
				const msg = form.querySelector('.wmk-form-message');
				if (msg) { msg.hidden = true; msg.className = 'wmk-form-message'; msg.textContent = ''; }
				const data = new FormData(form);
				const body = {};
				data.forEach(function (v, k) { body[k] = v; });
				body.consent = !!body.consent;
				fetch(cfg.rest + '/public/subscribe', {
					method: 'POST',
					headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': body._wpnonce || cfg.nonce || '' },
					credentials: 'same-origin',
					body: JSON.stringify(body)
				}).then(function (res) { return res.json().then(function (j) { return { ok: res.ok, j: j }; }); }).then(function (r) {
					if (msg) {
						msg.hidden = false;
						msg.textContent = (r.j && r.j.message) ? r.j.message : '';
						msg.classList.add(r.ok ? 'is-success' : 'is-error');
						if (r.ok) form.reset();
					}
				});
			});
		});
	}

	function initCartBadge() {
		if (!cfg.cartBadgeEnabled) return;

		function resolveCartLinks() {
			return Array.prototype.slice.call(document.querySelectorAll(
				'a.et_pb_menu__cart-button, .site-header-cart a, .cart-contents, .wcmenucart-contents, a[href*="/carrito/"], a[href*="/cart/"]'
			)).filter(function (el) {
				return !!el && !el.closest('.wmk-popup-root');
			});
		}

		function paintBadge(count) {
			var links = resolveCartLinks();
			links.forEach(function (link) {
				link.classList.add('wmk-cart-link');
				var badge = link.querySelector('.wmk-cart-count-badge');
				if (!badge) {
					badge = document.createElement('span');
					badge.className = 'wmk-cart-count-badge';
					link.appendChild(badge);
				}
				badge.textContent = String(Math.max(0, Number(count) || 0));
				badge.style.display = (Number(count) || 0) > 0 ? 'inline-block' : 'none';
			});
		}

		function readCountFromDom() {
			var txt =
				(document.querySelector('.cart-contents-count') || {}).textContent ||
				(document.querySelector('.count') || {}).textContent ||
				'';
			var n = parseInt((txt || '').replace(/[^\d]/g, ''), 10);
			return isNaN(n) ? (Number(cfg.cartCount) || 0) : n;
		}

		function refreshCount() {
			if (!cfg.ajaxUrl) {
				paintBadge(readCountFromDom());
				return;
			}
			var body = new FormData();
			body.append('action', 'suitemkt3k_cart_count');
			if (cfg.publicNonce) {
				body.append('nonce', cfg.publicNonce);
			}
			fetch(cfg.ajaxUrl, { method: 'POST', body: body, credentials: 'same-origin' })
				.then(function (res) { return res.json(); })
				.then(function (json) {
					if (json && json.success && json.data) {
						paintBadge(Number(json.data.count) || 0);
						return;
					}
					paintBadge(readCountFromDom());
				})
				.catch(function () {
					paintBadge(readCountFromDom());
				});
		}

		paintBadge(Number(cfg.cartCount) || 0);
		refreshCount();

		document.body.addEventListener('added_to_cart', function () {
			refreshCount();
		});
		document.body.addEventListener('wc_fragments_refreshed', function () {
			refreshCount();
		});
		document.body.addEventListener('updated_wc_div', function () {
			refreshCount();
		});
		if (window.jQuery) {
			window.jQuery(document.body).on('added_to_cart wc_fragments_refreshed updated_wc_div', function () {
				refreshCount();
			});
		}
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', function(){ initBanner(); initPopup(); initForms(); initCartBadge(); });
	} else {
		initBanner(); initPopup(); initForms(); initCartBadge();
	}
})();
