/**
 * ArkHost Security Pack - 2FA Profile Scripts
 *
 * Handles 2FA setup, verification, disable, and backup code regeneration
 * on the user profile page. Dynamic values are passed via arksp2fa object
 * (wp_localize_script).
 */

/* global jQuery, ajaxurl, arksp2fa, qrcode */

jQuery(document).ready(function($) {

	$('#arksp-setup-2fa').on('click', function() {
		$('#arksp-2fa-setup').show();
		$(this).hide();

		// Generate new secret.
		$.post(ajaxurl, {
			action: 'arksp_generate_2fa_secret',
			user_id: arksp2fa.userId,
			_ajax_nonce: arksp2fa.nonce
		}, function(response) {
			if (response.success) {
				$('#arksp-2fa-secret').text(response.data.secret);

				// Generate QR code client-side.
				var qr = qrcode(0, 'M');
				qr.addData(response.data.otpauth);
				qr.make();
				$('#arksp-2fa-qr').html(qr.createSvgTag(5, 0));
			}
		});
	});

	$('#arksp-verify-2fa-setup').on('click', function() {
		var code = $('#arksp-2fa-verify-code').val();
		$.post(ajaxurl, {
			action: 'arksp_verify_2fa_setup',
			user_id: arksp2fa.userId,
			code: code,
			_ajax_nonce: arksp2fa.nonce
		}, function(response) {
			if (response.success && response.data.backup_codes) {
				// Show backup codes - user MUST save these.
				var codesHtml = '<div style="background:#d4edda;border:1px solid #c3e6cb;padding:20px;margin:10px 0;border-radius:4px;">';
				codesHtml += '<h3 style="margin-top:0;color:#155724;">' + arksp2fa.strings.twoFaEnabledTitle + '</h3>';
				codesHtml += '<p style="color:#dc3232;font-weight:bold;">' + arksp2fa.strings.codesNotShownAgain + '</p>';
				codesHtml += '<pre style="background:#fff;padding:15px;font-size:14px;line-height:1.8;">' + response.data.backup_codes.join('\n') + '</pre>';
				codesHtml += '<p>' + arksp2fa.strings.storeCodesInfo + '</p>';
				codesHtml += '<button type="button" class="button button-primary" onclick="location.reload();">' + arksp2fa.strings.savedCodes + '</button>';
				codesHtml += '</div>';
				$('#arksp-2fa-setup').html(codesHtml);
			} else if (response.success) {
				location.reload();
			} else {
				$('#arksp-2fa-setup-result').html('<p style="color:red;">' + response.data.message + '</p>');
			}
		});
	});

	$('#arksp-disable-2fa').on('click', function() {
		if (confirm(arksp2fa.strings.confirmDisable)) {
			$.post(ajaxurl, {
				action: 'arksp_disable_2fa',
				user_id: arksp2fa.userId,
				_ajax_nonce: arksp2fa.nonce
			}, function(response) {
				if (response.success) {
					location.reload();
				}
			});
		}
	});

	$('#arksp-regenerate-backup-codes').on('click', function() {
		if (confirm(arksp2fa.strings.confirmRegenerate)) {
			$.post(ajaxurl, {
				action: 'arksp_regenerate_backup_codes',
				user_id: arksp2fa.userId,
				_ajax_nonce: arksp2fa.nonce
			}, function(response) {
				if (response.success) {
					$('#arksp-new-backup-codes').text(response.data.codes.join('\n'));
					$('#arksp-backup-codes-display').show();
				}
			});
		}
	});
});
