/**
 * Brainwerk Security Suite — 2FA controls on the user-profile screen.
 *
 * profile.php wraps its whole body in a single <form>, and HTML forbids nested
 * forms, so the 2FA buttons can't live in their own <form>. Instead each button
 * carries data-* attributes and this script builds a one-shot form on submit.
 * All data comes from the DOM (no server-generated JS), so this ships as a
 * static enqueued file rather than an inline <script> block.
 */
( function () {
	'use strict';

	function buildForm( action, fields ) {
		var f = document.createElement( 'form' );
		f.method = 'post';
		f.action = action;
		f.style.display = 'none';
		Object.keys( fields ).forEach( function ( name ) {
			var i = document.createElement( 'input' );
			i.type = 'hidden';
			i.name = name;
			i.value = fields[ name ];
			f.appendChild( i );
		} );
		document.body.appendChild( f );
		f.submit();
	}

	// --- Regenerate / disable buttons (2FA already active) ------------------
	document.querySelectorAll( '.shieldforge-2fa-action' ).forEach( function ( btn ) {
		btn.addEventListener( 'click', function () {
			var msg = btn.getAttribute( 'data-confirm' );
			if ( msg && ! window.confirm( msg ) ) {
				return;
			}
			buildForm( btn.getAttribute( 'data-action' ), {
				action: btn.getAttribute( 'data-handler' ),
				_wpnonce: btn.getAttribute( 'data-nonce' ),
				user_id: btn.getAttribute( 'data-user' )
			} );
		} );
	} );

	// --- Setup wizard: confirm and enable ----------------------------------
	var confirmBtn = document.getElementById( 'shieldforge_2fa_confirm_btn' );
	var codeInput = document.getElementById( 'shieldforge_2fa_code' );
	if ( confirmBtn && codeInput ) {
		var submit = function () {
			var code = ( codeInput.value || '' ).replace( /\s+/g, '' );
			if ( ! code ) {
				codeInput.focus();
				return;
			}
			buildForm( confirmBtn.getAttribute( 'data-action' ), {
				action: 'shieldforge_2fa_setup',
				_wpnonce: confirmBtn.getAttribute( 'data-nonce' ),
				user_id: confirmBtn.getAttribute( 'data-user' ),
				shieldforge_2fa_code: code
			} );
		};
		confirmBtn.addEventListener( 'click', submit );
		codeInput.addEventListener( 'keydown', function ( e ) {
			if ( e.key === 'Enter' ) {
				e.preventDefault();
				submit();
			}
		} );
	}
} )();
