/**
 * ZA Creative Login Shield - Login Page 2FA
 */
(function() {
    'use strict';

    if ( typeof zacls2fa === 'undefined' ) {
        return;
    }

    document.addEventListener( 'DOMContentLoaded', function() {
        var verifyBtn = document.getElementById( 'zacls_verify_2fa' );
        var resendBtn = document.getElementById( 'zacls_resend_otp' );
        var codeField = document.getElementById( 'zacls_2fa_code' );
        var msgDiv = document.getElementById( 'zacls_2fa_message' );

        if ( verifyBtn ) {
            verifyBtn.addEventListener( 'click', function() {
                var code = codeField ? codeField.value.trim() : '';
                if ( ! code ) {
                    msgDiv.style.display = 'block';
                    msgDiv.style.color = '#dc3232';
                    msgDiv.textContent = zacls2fa.i18n.enterCode;
                    return;
                }
                var formData = new FormData();
                formData.append( 'action', 'zacls_verify_2fa' );
                formData.append( 'code', code );
                formData.append( 'token', zacls2fa.token );
                formData.append( 'nonce', zacls2fa.nonce );
                fetch( zacls2fa.ajaxUrl, {
                    method: 'POST',
                    body: formData
                } ).then( function( r ) { return r.json(); } ).then( function( d ) {
                    if ( d.success ) {
                        window.location.href = d.data.redirect;
                    } else {
                        msgDiv.style.display = 'block';
                        msgDiv.style.color = '#dc3232';
                        msgDiv.textContent = d.data.message;
                    }
                } );
            } );
        }

        if ( resendBtn ) {
            resendBtn.addEventListener( 'click', function() {
                var formData = new FormData();
                formData.append( 'action', 'zacls_send_otp' );
                formData.append( 'token', zacls2fa.token );
                formData.append( 'nonce', zacls2fa.nonce );
                fetch( zacls2fa.ajaxUrl, {
                    method: 'POST',
                    body: formData
                } ).then( function( r ) { return r.json(); } ).then( function( d ) {
                    msgDiv.style.display = 'block';
                    msgDiv.style.color = d.success ? '#46b450' : '#dc3232';
                    msgDiv.textContent = d.data ? d.data.message : '';
                } );
            } );
        }
    } );

})();
