jQuery(document).ready(function($) {
	const getMessageElement = function() {
		return $('.sc-wordform-license-message-settings-info').first();
	};

	const getSupportLinks = function() {
		return '<a href="' + (wordform_admin_view_license_page_script_obj.support_page_url || '#') + '">in-plugin support page</a> or <a href="' + (wordform_admin_view_license_page_script_obj.softcoy_support_url || 'https://softcoy.com/support') + '" target="_blank" rel="noopener">SOFTCOY support</a>';
	};

	const showLicenseMessage = function(typeClass, html) {
		const updateInfoEle = getMessageElement();
		updateInfoEle.html(html || '').removeClass('active text-success text-error text-warning').addClass('active ' + typeClass);

		if (updateInfoEle.length && updateInfoEle[0] && typeof updateInfoEle[0].scrollIntoView === 'function') {
			updateInfoEle[0].scrollIntoView({ behavior: 'smooth', block: 'center' });
		}
	};

	const appendSupportLinks = function(message, jsonData) {
		let failHtml = message || 'License validation failed.';

		if (jsonData && jsonData.registeredLicenseUrl) {
			failHtml += '<div style="margin-top:10px;">Registered site: <strong>' + jsonData.registeredLicenseUrl + '</strong>. Please contact ' + getSupportLinks() + ' to resolve the activation.</div>';
		} else {
			failHtml += '<div style="margin-top:10px;">Please contact ' + getSupportLinks() + ' to resolve the activation.</div>';
		}

		return failHtml;
	};

	const parseJsonResponse = function(data) {
		if (typeof data === 'object') {
			return data;
		}

		return JSON.parse(data);
	};

	$('#scWordFormLicenseKey').on('submit', function() {
		const formElement = $(this);
		if (formElement.data('primaryAction') === 'upgrade') {
			formElement.find('.sc-wordform-upgrade-to-pro-btn').trigger('click');
			return false;
		}

		const params = { formData: formElement.serialize() };
		showLicenseMessage('text-warning', '<i class="fa-solid fa-spinner fa-spin"></i> Checking the license key and syncing this site. Please wait...');

		$.ajax({
			type: 'POST',
			url: wordform_admin_view_license_page_script_obj.adminajax_url,
			data: {
				action: 'sc_wordform_settings_wordform_license_key_save',
				security: wordform_admin_view_license_page_script_obj.nonce,
				params: params
			},
			success: function(data) {
				const jsonData = parseJsonResponse(data);

				if (jsonData.status === 'success') {
					showLicenseMessage('text-success', jsonData.successMsg);
					setTimeout(function() { window.location.reload(true); }, 3000);
					return;
				}

				if (jsonData.status === 'warning') {
					showLicenseMessage('text-warning', jsonData.warningMsg);
					return;
				}

				showLicenseMessage('text-error', appendSupportLinks(jsonData.failMsg, jsonData));
			},
			error: function() {
				showLicenseMessage('text-error', appendSupportLinks('License request failed. Please try again.', {}));
			}
		});

		return false;
	});

	$('body').on('click', '.sc-wordform-license-info-refresh-btn-text', function() {
		const refreshElement = $('.sc-wordform-license-info-refresh-btn-text');
		refreshElement.prop('disabled', true).html('<span class="dashicons dashicons-update"></span> Refreshing...');
		showLicenseMessage('text-warning', '<i class="fa-solid fa-spinner fa-spin"></i> Refreshing the latest license data. Please wait...');

		$.ajax({
			type: 'POST',
			url: wordform_admin_view_license_page_script_obj.adminajax_url,
			data: {
				action: 'sc_wordform_settings_wordform_license_key_data_refresh',
				security: wordform_admin_view_license_page_script_obj.nonce
			},
			success: function(data) {
				const jsonData = parseJsonResponse(data);

				if (jsonData.status === 'success') {
					showLicenseMessage('text-success', jsonData.successMsg || 'License data refreshed successfully.');
					setTimeout(function() { window.location.reload(true); }, 1200);
					return;
				}

				refreshElement.prop('disabled', false).html('<span class="dashicons dashicons-update"></span> Refresh');
				showLicenseMessage('text-error', appendSupportLinks(jsonData.failMsg || 'License refresh failed.', jsonData));
			},
			error: function() {
				refreshElement.prop('disabled', false).html('<span class="dashicons dashicons-update"></span> Refresh');
				showLicenseMessage('text-error', appendSupportLinks('License refresh request failed. Please try again.', {}));
			}
		});
	});

	$('body').on('click', '.sc-wordform-upgrade-to-pro-btn', function() {
		const buttonElement = $(this);
		const formElement = $('#scWordFormLicenseKey');
		const params = { formData: formElement.serialize() };

		buttonElement.prop('disabled', true).text('Installing Pro...');
		showLicenseMessage('text-warning', '<i class="fa-solid fa-spinner fa-spin"></i> Checking the license and preparing the Pro package. Please wait...');

		$.ajax({
			type: 'POST',
			url: wordform_admin_view_license_page_script_obj.adminajax_url,
			data: {
				action: 'sc_wordform_upgrade_to_pro',
				security: wordform_admin_view_license_page_script_obj.nonce,
				params: params
			},
			success: function(data) {
				const jsonData = parseJsonResponse(data);

				if (jsonData.status === 'success') {
					showLicenseMessage('text-success', jsonData.successMsg);
					if (jsonData.redirectUrl) {
						setTimeout(function() { window.location.href = jsonData.redirectUrl; }, 1800);
					} else {
						window.location.reload(true);
					}
					return;
				}

				if (jsonData.status === 'warning') {
					showLicenseMessage('text-warning', jsonData.warningMsg);
				} else {
					showLicenseMessage('text-error', appendSupportLinks(jsonData.failMsg, jsonData));
				}

				buttonElement.prop('disabled', false).text('Upgrade to Pro');
			},
			error: function() {
				showLicenseMessage('text-error', appendSupportLinks('Upgrade request failed. Please try again.', {}));
				buttonElement.prop('disabled', false).text('Upgrade to Pro');
			}
		});
	});

	$('body').on('click', '.wordform-license-visibility-toggle', function() {
		const buttonElement = $(this);
		const targetElement = $('#' + buttonElement.data('target'));
		const isVisible = buttonElement.attr('data-visible') === '1';

		if (!targetElement.length) {
			return;
		}

		targetElement.text(isVisible ? targetElement.data('masked') : targetElement.data('revealed'));
		buttonElement.attr('data-visible', isVisible ? '0' : '1');
		buttonElement.find('.wordform-license-visibility-label').text(isVisible ? 'Show' : 'Hide');
		buttonElement.find('i').attr('class', isVisible ? 'fa-regular fa-eye' : 'fa-regular fa-eye-slash');
	});
});
