(function () {
	'use strict';

	var cfg =
		typeof aviAppsumoConfig === 'object' && aviAppsumoConfig
			? aviAppsumoConfig
			: typeof aviAppSumoRedeem === 'object' && aviAppSumoRedeem
				? aviAppSumoRedeem
				: {};
	var i18n =
		typeof window.aviAppsumoI18n === 'object' && window.aviAppsumoI18n
			? window.aviAppsumoI18n
			: {};

	function qs(id) {
		return document.getElementById(id);
	}

	function setMsg(el, text, isErr) {
		if (!el) return;
		el.textContent = text || '';
		el.style.color = isErr ? '#b91c1c' : '#166534';
	}

	function t(key, fallback) {
		if (i18n && typeof i18n[key] === 'string' && i18n[key]) return i18n[key];
		if (cfg && typeof cfg[key] === 'string' && cfg[key]) return cfg[key];
		return fallback || '';
	}

	window.aviStartGuardianCountdown = function (seconds) {
		var el = qs('avi-appsumo-trial-countdown');
		if (!el || typeof seconds !== 'number') return;
		var left = Math.max(0, Math.floor(seconds));
		el.textContent = String(left);
		var t = setInterval(function () {
			left -= 1;
			if (left < 0) {
				clearInterval(t);
				return;
			}
			el.textContent = String(left);
		}, 1000);
	};

	function getPmFromSetupIntent(si) {
		if (!si || !si.payment_method) return '';
		return typeof si.payment_method === 'string'
			? si.payment_method
			: si.payment_method.id || '';
	}

	var stripeInstance = null;
	var cardElement = null;
	var stripeMounted = false;

	function initStripeTrialUI() {
		var pk = cfg.stripePublicKey || window.aviStripePublicKey || '';
		var mountEl = qs('avi-card-element');
		if (!pk || typeof Stripe === 'undefined' || !mountEl || stripeMounted) {
			return;
		}
		stripeMounted = true;
		stripeInstance = Stripe(pk);
		var elements = stripeInstance.elements();
		cardElement = elements.create('card', {
			style: { base: { fontSize: '16px', color: '#32325d' } },
		});
		cardElement.mount('#avi-card-element');
		cardElement.on('change', function (event) {
			var err = qs('avi-card-errors');
			if (err) err.textContent = event.error ? event.error.message : '';
		});

		var skip = qs('avi-skip-trial');
		if (skip) {
			skip.addEventListener('click', function (e) {
				e.preventDefault();
				var isAg = !!window.aviAppsumoIsAgency;
				var url = isAg
					? cfg.redirectSkipAgency ||
						(window.location.origin
							? window.location.origin + '/agency-dashboard/?appsumo_welcome=1'
							: '/agency-dashboard/?appsumo_welcome=1')
					: cfg.redirectSkipTrial ||
						(window.location.origin
							? window.location.origin + '/premium-dashboard/?appsumo_welcome=1'
							: '/premium-dashboard/?appsumo_welcome=1');
				window.location.href = url;
			});
		}

		var btn = qs('avi-start-trial-btn');
		if (btn) {
			btn.addEventListener('click', onStartTrialClick);
		}
	}

	function showTrialStep(d) {
		var formStep = qs('avi-appsumo-form-step');
		var trialStep = qs('avi-appsumo-trial-step');
		if (formStep) formStep.style.display = 'none';
		if (trialStep) trialStep.style.display = 'block';
		var isAgency = !!(d && d.data && d.data.is_agency);
		window.aviAppsumoIsAgency = isAgency;
		window.aviAppsumoAccountType =
			d && d.data && d.data.account_type ? String(d.data.account_type) : 'individual';
		if (isAgency) {
			var titleEl = document.querySelector('.avi-trial-title');
			if (titleEl) {
				titleEl.textContent = 'Your agency access is activated!';
			}
			var descEl = document.querySelector('.avi-trial-desc');
			if (descEl) {
				descEl.textContent =
					"Enjoy 15 free Guardian days to protect your clients' Google profiles 24/7.";
			}
		}
		if (d && d.data && d.data.user_id) {
			window.aviAppsumoUserId = parseInt(d.data.user_id, 10) || 0;
		}
		if (cfg.nonce) {
			window.aviAppsumoNonce = cfg.nonce;
		}
		if (cfg.stripePublicKey) {
			window.aviStripePublicKey = cfg.stripePublicKey;
		}
		if (typeof window.aviStartGuardianCountdown === 'function') {
			window.aviStartGuardianCountdown(15);
		}
		initStripeTrialUI();
	}

	function onStartTrialClick() {
		var formBox = qs('avi-stripe-trial-form');
		var loadBox = qs('avi-trial-loading');
		var errEl = qs('avi-card-errors');
		if (!stripeInstance || !cardElement) {
			if (errEl) errEl.textContent = cfg.strStripeMissing || 'Stripe indisponible.';
			return;
		}
		if (formBox) formBox.style.display = 'none';
		if (loadBox) loadBox.style.display = 'block';
		if (errEl) errEl.textContent = '';

		var ajaxurl = cfg.ajaxurl || '';
		var nonce = cfg.nonce || window.aviAppsumoNonce || '';

		var fd = new FormData();
		fd.append('action', 'avision_appsumo_create_setup_intent');
		fd.append('nonce', nonce);
		if (window.aviAppsumoUserId) {
			fd.append('user_id', String(window.aviAppsumoUserId));
		}

		fetch(ajaxurl, { method: 'POST', body: fd, credentials: 'same-origin' })
			.then(function (r) {
				return r.json();
			})
			.then(function (data) {
				if (!data.success || !data.data || !data.data.client_secret) {
					if (formBox) formBox.style.display = 'block';
					if (loadBox) loadBox.style.display = 'none';
					var msg =
						data.data && data.data.message
							? data.data.message
							: t('error_generic', 'An error occurred. Please try again.');
					if (errEl) errEl.textContent = msg;
					return null;
				}
				var clientSecret = data.data.client_secret;
				return stripeInstance.confirmCardSetup(clientSecret, {
					payment_method: { card: cardElement },
				});
			})
			.then(function (result) {
				if (!result) return null;
				if (result.error) {
					var formBox2 = qs('avi-stripe-trial-form');
					var loadBox2 = qs('avi-trial-loading');
					if (formBox2) formBox2.style.display = 'block';
					if (loadBox2) loadBox2.style.display = 'none';
					if (errEl) errEl.textContent = result.error.message;
					return null;
				}
				var pmId = getPmFromSetupIntent(result.setupIntent);
				if (!pmId) {
					var fb = qs('avi-stripe-trial-form');
					var lb = qs('avi-trial-loading');
					if (fb) fb.style.display = 'block';
					if (lb) lb.style.display = 'none';
					if (errEl) errEl.textContent = cfg.strPmMissing || 'Moyen de paiement introuvable.';
					return null;
				}
				var fd2 = new FormData();
				fd2.append('action', 'avision_appsumo_start_guardian_trial');
				fd2.append('nonce', nonce);
				fd2.append('payment_method_id', pmId);
				if (window.aviAppsumoUserId) {
					fd2.append('user_id', String(window.aviAppsumoUserId));
				}
				return fetch(ajaxurl, {
					method: 'POST',
					body: fd2,
					credentials: 'same-origin',
				}).then(function (r2) {
					return r2.json();
				});
			})
			.then(function (data2) {
				if (!data2) return;
				var isAg = !!window.aviAppsumoIsAgency;
				var redir =
					data2.data && data2.data.redirect
						? data2.data.redirect
						: isAg
							? cfg.redirectAfterAgency ||
								(window.location.origin
									? window.location.origin +
										'/agency-dashboard/?appsumo_welcome=1&guardian=1'
									: '')
							: cfg.redirectAfterTrial ||
								(window.location.origin
									? window.location.origin +
										'/premium-dashboard/?appsumo_welcome=1&guardian=1'
									: '');
				if (data2.success && redir) {
					window.location.href = redir;
					return;
				}
				var fb3 = qs('avi-stripe-trial-form');
				var lb3 = qs('avi-trial-loading');
				if (fb3) fb3.style.display = 'block';
				if (lb3) lb3.style.display = 'none';
				var msg2 =
					data2.data && data2.data.message
						? data2.data.message
						: data2.data && data2.data.code
							? String(data2.data.code)
							: 'erreur';
				if (errEl) errEl.textContent = msg2;
			})
			.catch(function () {
				var fb4 = qs('avi-stripe-trial-form');
				var lb4 = qs('avi-trial-loading');
				if (fb4) fb4.style.display = 'block';
				if (lb4) lb4.style.display = 'none';
				if (errEl) errEl.textContent = t('error_network', 'Network error. Please try again.');
			});
	}

	document.addEventListener('DOMContentLoaded', function () {
		document.querySelectorAll('.avi-type-btn').forEach(function (btn) {
			btn.addEventListener('click', function () {
				document.querySelectorAll('.avi-type-btn').forEach(function (b) {
					b.classList.remove('active');
				});
				btn.classList.add('active');
			});
		});

		var form = qs('avi-appsumo-redeem-form');
		if (!form) return;
		form.addEventListener('submit', function (ev) {
			if (ev.preventDefault) ev.preventDefault();
			var msg = qs('avi-appsumo-redeem-msg');
			var loader = qs('avi-appsumo-redeem-loader');
			var btn = qs('avi-appsumo-redeem-submit');
			var emailEl = qs('avi-appsumo-email');
			var codeEl = qs('avi-appsumo-code');
			if (!emailEl || !codeEl) return;
			var email = (emailEl.value || '').trim();
			var code = (codeEl.value || '').trim();
			if (!email || !code) {
				setMsg(msg, t('strInvalid', 'Please enter an email and a code.'), true);
				return;
			}
			if (btn) btn.disabled = true;
			if (loader) loader.style.display = 'block';
			setMsg(msg, '', false);
			var fd = new FormData();
			fd.append('action', 'avision_appsumo_redeem');
			fd.append('nonce', cfg.nonce || '');
			fd.append('email', email);
			fd.append('code', code);
			var activeType = document.querySelector('.avi-type-btn.active');
			fd.append(
				'account_type',
				activeType && activeType.dataset && activeType.dataset.type
					? activeType.dataset.type
					: 'individual'
			);
			var ajaxurl = cfg.ajaxurl || '';
			fetch(ajaxurl, { method: 'POST', body: fd, credentials: 'same-origin' })
				.then(function (r) {
					return r.json();
				})
				.then(function (d) {
					if (d.success && d.data && d.data.user_id) {
						setMsg(msg, d.data.message || t('success', 'Account activated! Redirecting...'), false);
						var pk = cfg.stripePublicKey || '';
						var stripeOk = typeof Stripe !== 'undefined';
						if (cfg.hasStripeElements && pk && stripeOk) {
							showTrialStep(d);
							if (loader) loader.style.display = 'none';
							return;
						}
						var isAg = !!d.data.is_agency;
						var go =
							d.data.redirect_premium && d.data.redirect_agency
								? isAg
									? d.data.redirect_agency
									: d.data.redirect_premium
								: d.data.redirect ||
									(isAg ? cfg.redirectSkipAgency : cfg.redirectSkipTrial);
						if (go) {
							window.location.href = go;
						}
						return;
					}
					var codeErr =
						d.data && d.data.code
							? d.data.code
							: d.data && d.data.message
								? d.data.message
								: 'erreur';
					var human =
						codeErr === 'code_invalid'
							? t('strCodeInvalid', 'Invalid code.')
							: codeErr === 'code_already_used'
								? t('error_invalid_code', 'Invalid or already used code.')
								: codeErr === 'invalid_email_or_code'
									? t('error_invalid_email', 'Please enter a valid email address.')
									: String(codeErr);
					setMsg(msg, human, true);
				})
				.catch(function () {
					setMsg(msg, t('error_network', 'Network error. Please try again.'), true);
				})
				.finally(function () {
					var trialStep = qs('avi-appsumo-trial-step');
					var onTrial =
						trialStep &&
						trialStep.style.display === 'block';
					if (btn && !onTrial) btn.disabled = false;
					if (loader && !onTrial) loader.style.display = 'none';
				});
		});
	});
})();
