(function ($) {
	'use strict';

	var vars = (typeof ssInterestVars !== 'undefined') ? ssInterestVars : {};

	function getSelectedCount($container) {
		return $container.find('input[type="checkbox"]:checked').length;
	}

	function getSelectedPlan($form) {
		return $form.find('input[name="plan_id"]:checked');
	}

	function applyPlanLimits($form) {
		var $plan = getSelectedPlan($form);
		if (!$plan.length) {
			return;
		}

		var maxCategories = parseInt($plan.data('max-categories'), 10) || 0;
		var maxTags = parseInt($plan.data('max-tags'), 10) || 0;

		$form.find('.ss-interest-checkboxes[data-limit-type="categories"]').attr('data-limit', maxCategories);
		$form.find('.ss-interest-checkboxes[data-limit-type="tags"]').attr('data-limit', maxTags);

		enforcePlanLimits($form);
	}

	function enforcePlanLimits($form) {
		$form.find('.ss-interest-checkboxes').each(function () {
			var $group = $(this);
			var limit = parseInt($group.data('limit'), 10) || 0;
			var checked = getSelectedCount($group);

			$group.find('input[type="checkbox"]').each(function () {
				var $input = $(this);
				if (!$input.is(':checked') && limit > 0 && checked >= limit) {
					$input.prop('disabled', true);
				} else {
					$input.prop('disabled', false);
				}
			});
		});
	}

	function openModal($modal) {
		$modal.addClass('is-open').attr('aria-hidden', 'false');
		$('body').addClass('ss-interest-modal-open');
		$modal.find('.ss-interest-message').removeClass('is-error is-success').text('');
		applyPlanLimits($modal.find('.ss-interest-form'));
	}

	function closeModal($modal) {
		$modal.removeClass('is-open').attr('aria-hidden', 'true');
		$('body').removeClass('ss-interest-modal-open');
	}

	// ── Helper: remove a query param from the current URL without reload ──
	function removeQueryParam(param) {
		if (!window.history || !window.history.replaceState) {
			return;
		}
		var url = new URL(window.location.href);
		url.searchParams.delete(param);
		window.history.replaceState({}, '', url.toString());
	}

	// ── Auto-open: settings-based delay OR post-login redirect ──
	$(function () {
		var urlParams = new URLSearchParams(window.location.search);
		var openNow   = urlParams.has('ss_subscribe') && urlParams.get('ss_subscribe') === '1';

		if (openNow) {
			// User just logged in and was redirected back — open immediately.
			removeQueryParam('ss_subscribe');
			var $targetModal = $('.ss-interest-modal').first();
			if ($targetModal.length) {
				openModal($targetModal);
			}
		} else if (vars.auto_open) {
			var delay = parseInt(vars.auto_open_delay, 10) || 0;
			setTimeout(function () {
				var $autoModal = $('[data-ss-auto-open="1"] .ss-interest-modal').first();
				if ($autoModal.length) {
					openModal($autoModal);
				}
			}, delay * 1000);
		}
	});

	$(document).on('click', '[data-ss-open-interest-modal]', function (e) {
		e.preventDefault();
		var target = $(this).data('ss-open-interest-modal');
		openModal($(target));
	});

	$(document).on('click', '[data-ss-close-modal]', function () {
		closeModal($(this).closest('.ss-interest-modal'));
	});

	$(document).on('keydown', function (e) {
		if (e.key === 'Escape') {
			closeModal($('.ss-interest-modal.is-open'));
		}
	});

	$(document).on('change', '.ss-interest-form input[name="plan_id"]', function () {
		applyPlanLimits($(this).closest('.ss-interest-form'));
	});

	$(document).on('change', '.ss-interest-form input[type="checkbox"]', function () {
		enforcePlanLimits($(this).closest('.ss-interest-form'));
	});

	$(document).on('submit', '.ss-interest-form', function (e) {
		e.preventDefault();

		var $form = $(this);
		var $modal = $form.closest('.ss-interest-modal');
		var $message = $form.find('.ss-interest-message');
		var $submit = $form.find('[type="submit"]');
		var $plan = getSelectedPlan($form);
		var i18n = vars.i18n || {};

		if (!$plan.length) {
			$message.addClass('is-error').text(i18n.select_plan || 'Please select a plan.');
			return;
		}

		var categoryIds = [];
		var tagIds = [];

		$form.find('input[name="category_ids[]"]:checked').each(function () {
			categoryIds.push($(this).val());
		});

		$form.find('input[name="tag_ids[]"]:checked').each(function () {
			tagIds.push($(this).val());
		});

		$message.removeClass('is-error is-success').text('');
		$submit.prop('disabled', true).text(i18n.processing || 'Processing…');

		$.ajax({
			url: vars.ajax_url,
			type: 'POST',
			data: {
				action: 'submit_interest_subscription',
				nonce: vars.nonce,
				subscriber_name: $form.find('[name="subscriber_name"]').val(),
				subscriber_email: $form.find('[name="subscriber_email"]').val(),
				category_ids: categoryIds,
				tag_ids: tagIds,
				plan_id: $plan.val(),
				plan_source: $form.find('[name="plan_source"]').val() || 'interest'
			}
		}).done(function (response) {
			if (response.success) {
				$message.addClass('is-success').text(response.data.message);

				if (response.data.redirect) {
					window.location.href = response.data.redirect;
					return;
				}

				setTimeout(function () {
					closeModal($modal);
					$form[0].reset();
					applyPlanLimits($form);
					$message.removeClass('is-success').text('');
				}, 1800);
			} else {
				$message.addClass('is-error').text(response.data.message || i18n.error || 'Error.');
			}
		}).fail(function () {
			$message.addClass('is-error').text(i18n.error || 'Error.');
		}).always(function () {
			$submit.prop('disabled', false).text(i18n.submit || 'Subscribe');
		});
	});
})(jQuery);
