/**
 * Invizo standalone checkout: Stripe Payment Element + optional privacy acceptance.
 */
(function ($) {
	'use strict';

	var cfg = window.InvizoCheckout || {};
	var plans = cfg.plans || {};

	var stripe = null;
	var elements = null;
	var phase = 'idle';
	var lastPayload = null;
	var mounting = false;
	var paymentElementRef = null;
	var autoMountTimer = null;

	function setPaymentSurfaceState(state) {
		var $wrap = $('#invizo-payment-element-wrap');
		var isLoading = state === 'loading';
		var isReady = state === 'ready';
		$wrap.toggleClass('invizo-checkout-editorial__payment-wrap--loading', isLoading);
		$wrap.toggleClass('invizo-checkout-editorial__payment-wrap--ready', isReady);
		$wrap.attr('aria-busy', isLoading ? 'true' : 'false');
	}

	function featureIconSvg(i) {
		i = i % 3;
		if (i === 1) {
			return '<svg class="invizo-checkout-editorial__svg" width="22" height="22" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 6h16v12H4V6zm2 2v8h12V8H6z" stroke="currentColor" stroke-width="1.5"/><path d="M8 12h8M8 15h5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>';
		}
		if (i === 2) {
			return '<svg class="invizo-checkout-editorial__svg" width="22" height="22" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 3l8 4v6c0 5-3.5 9-8 10-4.5-1-8-5-8-10V7l8-4z" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/></svg>';
		}
		return '<svg class="invizo-checkout-editorial__svg" width="22" height="22" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 5a2 2 0 012-2h12a2 2 0 012 2v14l-8-3-8 3V5z" stroke="currentColor" stroke-width="1.5"/></svg>';
	}

	function renderFeatureList(features) {
		var ul = document.getElementById('invizo-summary-features');
		if (!ul) {
			return;
		}
		ul.innerHTML = '';
		(features || []).forEach(function (line, idx) {
			var li = document.createElement('li');
			li.className = 'invizo-checkout-editorial__feature';
			li.innerHTML =
				'<span class="invizo-checkout-editorial__feature-icon" aria-hidden="true">' +
				featureIconSvg(idx) +
				'</span><p class="invizo-checkout-editorial__feature-line"></p>';
			li.querySelector('.invizo-checkout-editorial__feature-line').textContent = line;
			ul.appendChild(li);
		});
	}

	function renderPlanSummary(planId) {
		var id = String(planId);
		var p = plans[id];
		if (!p) {
			return;
		}
		var titleEl = document.getElementById('invizo-summary-title');
		var recurringEl = document.getElementById('invizo-summary-recurring-line');
		var dueEl = document.getElementById('invizo-summary-due-today');
		var trialRow = document.getElementById('invizo-summary-trial-row');
		var trialLine = document.getElementById('invizo-summary-trial-line');
		var fig = document.getElementById('invizo-summary-figure');
		var pf = p.priceFormatted != null ? p.priceFormatted : String(p.price);
		var trialDays = parseInt(p.trialDays, 10) || 0;
		if (titleEl) {
			titleEl.textContent = p.title || '';
		}
		if (recurringEl) {
			recurringEl.textContent = '$' + pf + (p.intervalPhrase || '');
		}
		if (dueEl) {
			dueEl.textContent = trialDays > 0 ? '$0.00' : '$' + pf;
		}
		if (trialRow && trialLine) {
			if (trialDays > 0) {
				trialRow.classList.remove('invizo-checkout-editorial__pricing-row--hidden');
				trialRow.removeAttribute('hidden');
				trialLine.textContent = p.trialLine || '';
			} else {
				trialRow.classList.add('invizo-checkout-editorial__pricing-row--hidden');
				trialRow.setAttribute('hidden', 'hidden');
				trialLine.textContent = '';
			}
		}
		if (fig) {
			fig.innerHTML = '';
			if (p.media) {
				var img = document.createElement('img');
				img.src = p.media;
				img.alt = '';
				img.loading = 'lazy';
				img.width = 120;
				img.height = 120;
				fig.appendChild(img);
			} else {
				var ph = document.createElement('div');
				ph.className = 'invizo-checkout-editorial__figure-placeholder';
				ph.setAttribute('aria-hidden', 'true');
				fig.appendChild(ph);
			}
		}
		renderFeatureList(p.features);
		var hidden = document.getElementById('invizo-plan-id');
		if (hidden) {
			hidden.value = id;
		}
	}

	function buildFormData(action, extra) {
		var fd = new FormData();
		fd.append('action', action);
		fd.append('nonce', cfg.nonce);
		fd.append('plan_id', $('#invizo-plan-id').val() || '');
		fd.append('email', ($('#invizo-email').val() || '').trim());
		fd.append('name', ($('#invizo-fname').val() || '').trim());
		fd.append('billing_country', ($('#invizo-billing-country').val() || '').trim());
		fd.append('billing_city', ($('#invizo-billing-city').val() || '').trim());
		fd.append('billing_postcode', ($('#invizo-billing-postcode').val() || '').trim());
		if (cfg.privacy_required) {
			fd.append('privacy_accepted', $('#invizo-privacy-accept').is(':checked') ? '1' : '0');
		}
		if (extra) {
			Object.keys(extra).forEach(function (k) {
				if (extra[k] !== undefined && extra[k] !== null) {
					fd.append(k, String(extra[k]));
				}
			});
		}
		return fd;
	}

	function paymentElementCreateOptions() {
		var opts = { layout: 'tabs' };
		var em = ($('#invizo-email').val() || '').trim();
		var nm = ($('#invizo-fname').val() || '').trim();
		var city = ($('#invizo-billing-city').val() || '').trim();
		var zip = ($('#invizo-billing-postcode').val() || '').trim();
		var country = ($('#invizo-billing-country').val() || '').trim();
		var bd = {};
		if (em) {
			bd.email = em;
		}
		if (nm) {
			bd.name = nm;
		}
		if (city || zip || country) {
			bd.address = {};
			if (city) {
				bd.address.city = city;
			}
			if (zip) {
				bd.address.postal_code = zip;
			}
			if (country) {
				bd.address.country = country;
			}
		}
		if (Object.keys(bd).length) {
			opts.defaultValues = { billingDetails: bd };
		}
		return opts;
	}

	function ajaxPost(action, extra) {
		return fetch(cfg.ajax_url, {
			method: 'POST',
			body: buildFormData(action, extra),
			credentials: 'same-origin',
		}).then(function (r) {
			var ct = (r.headers.get('content-type') || '').toLowerCase();
			if (ct.indexOf('application/json') === -1) {
				return r.text().then(function (t) {
					var snippet = (t || '').replace(/<[^>]+>/g, ' ').trim().substring(0, 180);
					throw new Error(snippet || 'Unexpected response from server. Try refreshing the page.');
				});
			}
			return r.json();
		});
	}

	function stripeAppearance() {
		return {
			theme: 'stripe',
			variables: {
				colorPrimary: '#0c0e0f',
				colorBackground: '#f2f4f5',
				colorText: '#0c0e0f',
				colorDanger: '#9f403d',
				fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif',
				borderRadius: '4px',
			},
		};
	}

	function resetCheckoutFlow() {
		phase = 'idle';
		elements = null;
		lastPayload = null;
		if (paymentElementRef) {
			try {
				paymentElementRef.unmount();
			} catch (e) {
				/* ignore */
			}
			paymentElementRef = null;
		}
		$('#payment-element').empty();
		$('#button-text').text(cfg.btn_subscribe || '');
		$('#invizo-payment-placeholder').removeClass('invizo-checkout-editorial__payment-hint--hidden');
		setPaymentSurfaceState('loading');
	}

	function showMsg(text) {
		var $el = $('#payment-message');
		if (text) {
			$el.removeClass('invizo-checkout-editorial__message--hidden').text(text);
		} else {
			$el.addClass('invizo-checkout-editorial__message--hidden').text('');
		}
	}

	function redirectAfterSuccess(flags) {
		flags = flags || {};
		var parts = ['invizo_subscribed=1'];
		if (flags.pending_email_verification) {
			parts.push('invizo_pending_verify=1');
		}
		var qs = parts.join('&');
		var base = (cfg.success_redirect_url || '').trim();
		if (base) {
			var sep = base.indexOf('?') >= 0 ? '&' : '?';
			window.location.href = base + sep + qs;
			return;
		}
		var u = window.location.href.split('#')[0];
		window.location.href = u + (u.indexOf('?') >= 0 ? '&' : '?') + qs;
	}

	function setLoading(on) {
		$('#invizo-checkout-loader').toggleClass('invizo-checkout-editorial__loader--hidden', !on);
		$('#submit').prop('disabled', on);
	}

	async function mountPaymentElement(options) {
		options = options || {};
		var fromButton = !!options.fromButton;

		if (phase === 'ready' || phase === 'free_ready') {
			return true;
		}
		if (phase === 'loading') {
			return false;
		}
		if (mounting) {
			return false;
		}

		if (typeof Stripe === 'undefined' || !cfg.stripe_pk) {
			setPaymentSurfaceState('idle');
			showMsg(cfg.i18n_stripe_load || '');
			return false;
		}

		mounting = true;
		phase = 'loading';
		setPaymentSurfaceState('loading');
		var $btnText = $('#button-text');

		if (fromButton) {
			setLoading(true);
			$btnText.text(cfg.btn_processing || '…');
		} else {
			$('#invizo-payment-element-wrap').addClass('invizo-checkout-editorial__payment-wrap--busy');
		}

		try {
			if (!stripe) {
				stripe = Stripe(cfg.stripe_pk);
			}

			var json = await ajaxPost('invizo_create_subscription_intent');
			if (!json || !json.success) {
				throw new Error((json && json.data && json.data.message) || 'Request failed');
			}
			var data = json.data;
			lastPayload = data;

			if (data.clientSecret === 'free_active') {
				phase = 'free_ready';
				setPaymentSurfaceState('idle');
				$('#invizo-payment-placeholder').addClass('invizo-checkout-editorial__payment-hint--hidden');
				$btnText.text(cfg.btn_subscribe || '');
				return true;
			}

			if (paymentElementRef) {
				try {
					paymentElementRef.unmount();
				} catch (e2) {
					/* ignore */
				}
				paymentElementRef = null;
			}
			$('#payment-element').empty();

			elements = stripe.elements({
				clientSecret: data.clientSecret,
				appearance: stripeAppearance(),
			});
			paymentElementRef = elements.create('payment', paymentElementCreateOptions());
			paymentElementRef.on('ready', function () {
				phase = 'ready';
				setPaymentSurfaceState('ready');
				$('#invizo-payment-placeholder').addClass('invizo-checkout-editorial__payment-hint--hidden');
				$('#button-text').text(cfg.btn_complete_payment || cfg.btn_subscribe || '');
			});
			paymentElementRef.on('loaderror', function (event) {
				phase = 'idle';
				setPaymentSurfaceState('idle');
				$('#invizo-payment-placeholder').removeClass('invizo-checkout-editorial__payment-hint--hidden');
				$('#button-text').text(cfg.btn_subscribe || '');
				showMsg((event && event.error && event.error.message) || cfg.i18n_stripe_load || '');
			});
			paymentElementRef.mount('#payment-element');
			return true;
		} catch (e) {
			phase = 'idle';
			lastPayload = null;
			setPaymentSurfaceState('idle');
			showMsg(e.message || 'Something went wrong');
			$btnText.text(cfg.btn_subscribe || '');
			return false;
		} finally {
			mounting = false;
			if (fromButton) {
				setLoading(false);
			}
			$('#invizo-payment-element-wrap').removeClass('invizo-checkout-editorial__payment-wrap--busy');
		}
	}

	function tryAutoMount() {
		clearTimeout(autoMountTimer);
		autoMountTimer = setTimeout(function () {
			if (phase !== 'idle' || mounting) {
				return;
			}
			mountPaymentElement({ fromButton: false });
		}, 80);
	}

	$('#invizo-payment-form').on('submit', function (e) {
		e.preventDefault();
	});

	$(document).on('change', '#invizo-plan-picker', function () {
		resetCheckoutFlow();
		showMsg('');
		renderPlanSummary($(this).val());
		tryAutoMount();
	});

	$('#invizo-privacy-accept').on('change', tryAutoMount);

	$(function () {
		tryAutoMount();
	});

	$('#submit').on('click', async function () {
		showMsg('');

		try {
			if (cfg.privacy_required && !$('#invizo-privacy-accept').is(':checked')) {
				showMsg(cfg.i18n_privacy_error || '');
				return;
			}

			if (phase === 'idle') {
				var mounted = await mountPaymentElement({ fromButton: true });
				if (!mounted) {
					return;
				}
				if (!(lastPayload && lastPayload.clientSecret === 'free_active')) {
					return;
				}
			}

			if (phase === 'loading') {
				return;
			}

			if (lastPayload && lastPayload.clientSecret === 'free_active') {
				var freeEmail = ($('#invizo-email').val() || '').trim();
				if (!freeEmail || freeEmail.indexOf('@') < 1) {
					showMsg(cfg.i18n_email_pay || cfg.i18n_fill_details || '');
					return;
				}
				setLoading(true);
				$('#button-text').text(cfg.btn_processing || '…');
				var freeConfirm = await ajaxPost('invizo_confirm_subscription_order', {
					payment_intent: 'free',
					subscription_id: lastPayload.subscription_id,
				});
				if (!freeConfirm.success) {
					throw new Error((freeConfirm.data && freeConfirm.data.message) || 'Confirmation failed');
				}
				setLoading(false);
				redirectAfterSuccess({
					pending_email_verification: !!(freeConfirm.data && freeConfirm.data.pending_email_verification),
				});
				return;
			}

			if (phase !== 'ready') {
				return;
			}

			var payEmail = ($('#invizo-email').val() || '').trim();
			if (!payEmail || payEmail.indexOf('@') < 1) {
				showMsg(cfg.i18n_email_pay || cfg.i18n_fill_details || '');
				return;
			}

			setLoading(true);
			$('#button-text').text(cfg.btn_processing || '…');

			var returnUrl = window.location.href.split('#')[0];
			var kind = (lastPayload && lastPayload.intent_kind) || 'payment';
			var paymentIntentId = '';
			var setupIntentId = '';

			if (kind === 'setup') {
				var sr = await stripe.confirmSetup({
					elements: elements,
					confirmParams: { return_url: returnUrl },
					redirect: 'if_required',
				});
				if (sr.error) {
					throw new Error(sr.error.message);
				}
				if (sr.setupIntent) {
					setupIntentId = sr.setupIntent.id;
				}
			} else {
				var pr = await stripe.confirmPayment({
					elements: elements,
					confirmParams: { return_url: returnUrl },
					redirect: 'if_required',
				});
				if (pr.error) {
					throw new Error(pr.error.message);
				}
				if (pr.paymentIntent) {
					paymentIntentId = pr.paymentIntent.id;
				}
			}

			if (!paymentIntentId && !setupIntentId) {
				setLoading(false);
				$('#button-text').text(cfg.btn_complete_payment || cfg.btn_subscribe || '');
				return;
			}

			var confirmExtra = {
				subscription_id: lastPayload.subscription_id,
				payment_intent: paymentIntentId,
				setup_intent: setupIntentId,
			};
			var cj = await ajaxPost('invizo_confirm_subscription_order', confirmExtra);
			if (!cj.success) {
				throw new Error((cj.data && cj.data.message) || 'Confirmation failed');
			}

			setLoading(false);
			redirectAfterSuccess({
				pending_email_verification: !!(cj.data && cj.data.pending_email_verification),
			});
		} catch (e) {
			setLoading(false);
			$('#button-text').text(
				phase === 'ready' ? cfg.btn_complete_payment || cfg.btn_subscribe || '' : cfg.btn_subscribe || ''
			);
			showMsg(e.message || 'Something went wrong');
		}
	});
})(jQuery);
