(function($) {
	'use strict';
	const cfg = window.wpps2faProfile || {};
	if (!cfg.ajaxUrl || !cfg.nonce || !cfg.userId) return;

	function setupAuthenticator() {
		var btn = $('#wpps-2fa-setup-auth');
		var modal = $('#wpps-2fa-setup-modal');
		btn.prop('disabled', true);
		modal.find('#wpps-2fa-setup-loading').show();
		modal.find('#wpps-2fa-setup-body').hide();
		modal.show();
		$('#wpps-2fa-verify-code').val('');
		$('#wpps-2fa-setup-error').hide();
		$.post(cfg.ajaxUrl, {
			action: 'wpps_2fa_setup_authenticator',
			nonce: cfg.nonce,
			user_id: cfg.userId
		}).done(function(r) {
			if (r.success && r.data) {
				var qrImg = $('#wpps-2fa-qr-img');
				var qrFb = $('#wpps-2fa-qr-fallback');
				if (r.data.qr_data_uri) {
					qrImg.attr('src', r.data.qr_data_uri).attr('alt', 'QR Code').show();
					qrFb.hide();
				} else {
					qrImg.attr('src', '').attr('alt', '').hide();
					qrFb.show();
				}
				var rawSecret = r.data.secret || '';
				var displaySecret = rawSecret.replace(/(.{4})/g, '$1 ').trim();
				$('#wpps-2fa-secret-key').data('raw-secret', rawSecret).text(displaySecret);
				modal.find('#wpps-2fa-setup-loading').hide();
				modal.find('#wpps-2fa-setup-body').show();
			} else {
				modal.find('#wpps-2fa-setup-error').text(r.data && r.data.message ? r.data.message : 'Could not load setup.').show();
				modal.find('#wpps-2fa-setup-loading').hide();
			}
		}).fail(function() {
			modal.find('#wpps-2fa-setup-error').text('Request failed. Please try again.').show();
			modal.find('#wpps-2fa-setup-loading').hide();
		}).always(function() {
			btn.prop('disabled', false);
		});
	}

	function confirmSetup() {
		const code = $('#wpps-2fa-verify-code').val().replace(/\D/g, '');
		if (code.length !== 6) {
			$('#wpps-2fa-setup-error').text('Please enter a 6-digit code.').show();
			return;
		}
		var errEl = $('#wpps-2fa-setup-error');
		var btn = $('#wpps-2fa-confirm-setup');
		btn.prop('disabled', true);
		errEl.hide();
		$.post(cfg.ajaxUrl, {
			action: 'wpps_2fa_verify_authenticator',
			nonce: cfg.nonce,
			user_id: cfg.userId,
			code: code
		}).done(function(r) {
			if (r.success && r.data && r.data.backup_codes) {
				$('#wpps-2fa-setup-modal').hide();
				showBackupCodes(r.data.backup_codes, true);
			} else {
				var msg = (r.data && r.data.message) ? r.data.message : 'Invalid or expired code. Please try again.';
				errEl.text(msg).show();
				errEl[0].scrollIntoView({ behavior: 'smooth', block: 'nearest' });
			}
		}).fail(function() {
			errEl.text('Request failed. Please try again.').show();
			errEl[0].scrollIntoView({ behavior: 'smooth', block: 'nearest' });
		}).always(function() {
			btn.prop('disabled', false);
		});
	}

	function showBackupCodes(codes, fromSetup) {
		var list = $('#wpps-2fa-backup-codes-list').empty();
		codes.forEach(function(c) {
			list.append($('<div/>').text(c));
		});
		$('#wpps-2fa-backup-modal').data({ codes: codes, fromSetup: !!fromSetup }).show();
	}

	function exportBackupCodes() {
		var codes = $('#wpps-2fa-backup-modal').data('codes') || [];
		if (!codes.length) return;
		var text = codes.join('\n');
		var blob = new Blob([text], { type: 'text/plain' });
		var url = URL.createObjectURL(blob);
		var a = document.createElement('a');
		a.href = url;
		a.download = '2fa-backup-codes-' + (new Date().toISOString().slice(0, 10)) + '.txt';
		a.style.display = 'none';
		document.body.appendChild(a);
		a.click();
		document.body.removeChild(a);
		URL.revokeObjectURL(url);
	}

	$('#wpps-2fa-setup-auth').on('click', setupAuthenticator);
	$('#wpps-2fa-cancel-setup').on('click', function() {
		$('#wpps-2fa-setup-modal').hide();
		$('#wpps-2fa-setup-error').hide();
	});
	$('#wpps-2fa-confirm-setup').on('click', confirmSetup);
	$('#wpps-2fa-copy-secret').on('click', function() {
		var el = $('#wpps-2fa-secret-key');
		var key = (el.data('raw-secret') || el.text().replace(/\s/g, '') || '').trim();
		if (!key) return;
		if (navigator.clipboard && navigator.clipboard.writeText) {
			navigator.clipboard.writeText(key);
		} else {
			var ta = $('<textarea>').val(key).appendTo('body').select();
			document.execCommand('copy');
			ta.remove();
		}
	});
	$('#wpps-2fa-copy-backup').on('click', function() {
		var codes = $('#wpps-2fa-backup-modal').data('codes') || [];
		var text = codes.join('\n');
		if (navigator.clipboard && navigator.clipboard.writeText) {
			navigator.clipboard.writeText(text);
		} else {
			var ta = $('<textarea>').val(text).appendTo('body').select();
			document.execCommand('copy');
			ta.remove();
		}
	});
	$('#wpps-2fa-export-backup').on('click', exportBackupCodes);
	$('#wpps-2fa-close-backup').on('click', function() {
		var fromSetup = $('#wpps-2fa-backup-modal').data('fromSetup');
		$('#wpps-2fa-backup-modal').hide();
		if (fromSetup) location.reload();
	});

	// Method checkboxes: show/hide "Default method at login" and prevent unchecking last method
	function countCheckedMethods() {
		var email = $('input[name="wpps_2fa_use_email"]');
		var auth = $('input[name="wpps_2fa_use_authenticator"]');
		var n = 0;
		if (email.length && !email.prop('disabled')) n += email.is(':checked') ? 1 : 0;
		if (auth.length && !auth.prop('disabled')) n += auth.is(':checked') ? 1 : 0;
		return n;
	}
	function updatePrimaryWrapVisibility() {
		var primaryWrap = $('#wpps-2fa-primary-wrap');
		if (!primaryWrap.length) return;
		if (countCheckedMethods() >= 2) primaryWrap.show(); else primaryWrap.hide();
	}
	$('#wpps-2fa-profile-section').on('change', 'input[name="wpps_2fa_use_email"], input[name="wpps_2fa_use_authenticator"]', function() {
		var $chk = $(this);
		if (!$chk.prop('checked') && countCheckedMethods() === 0) {
			$chk.prop('checked', true);
			return;
		}
		updatePrimaryWrapVisibility();
	});
	updatePrimaryWrapVisibility();

	$('input[name="wpps_2fa_method"]').on('change', function() {
		const method = $(this).val();
		if (method === 'email' || method === 'authenticator') {
			$.post(cfg.ajaxUrl, {
				action: 'wpps_2fa_switch_method',
				nonce: cfg.nonce,
				user_id: cfg.userId,
				method: method
			});
		}
	});

	$('#wpps-2fa-regenerate-backup').on('click', function() {
		if (!confirm('Regenerate backup codes? Your old codes will stop working.')) return;
		$.post(cfg.ajaxUrl, {
			action: 'wpps_2fa_regenerate_backup_codes',
			nonce: cfg.nonce,
			user_id: cfg.userId
		}).done(function(r) {
			if (r.success && r.data && r.data.backup_codes) {
				showBackupCodes(r.data.backup_codes, false);
			}
		});
	});

	$('#wpps-2fa-remove-auth').on('click', function() {
		if (!confirm('Remove authenticator app? You will use email codes instead.')) return;
		$.post(cfg.ajaxUrl, {
			action: 'wpps_2fa_remove_authenticator',
			nonce: cfg.nonce,
			user_id: cfg.userId
		}).done(function(r) {
			if (r.success) location.reload();
		});
	});

	$('#wpps-2fa-disable-for-user').on('click', function() {
		if (!confirm('Disable two-factor authentication for this user? They will no longer be prompted for a code at login.')) return;
		var btn = $(this);
		btn.prop('disabled', true);
		$.post(cfg.ajaxUrl, {
			action: 'wpps_2fa_disable_for_user',
			nonce: cfg.nonce,
			user_id: cfg.userId
		}).done(function(r) {
			if (r.success) location.reload();
			else btn.prop('disabled', false);
		}).fail(function() { btn.prop('disabled', false); });
	});

	$('#wpps-2fa-enable-for-user').on('click', function() {
		var btn = $(this);
		btn.prop('disabled', true);
		$.post(cfg.ajaxUrl, {
			action: 'wpps_2fa_enable_for_user',
			nonce: cfg.nonce,
			user_id: cfg.userId
		}).done(function(r) {
			if (r.success) location.reload();
			else btn.prop('disabled', false);
		}).fail(function() { btn.prop('disabled', false); });
	});
})(jQuery);
