/**
 * VMPFence Frontend 2FA Management JavaScript
 * Handles 2FA setup, disable, and backup code regeneration on frontend
 * 
 * @package VMPFence
 * @since 2.1.0
 */

(function($) {
    'use strict';

    let qrCodeData = null;
    let backupCodes = null;

    /**
     * Initialize
     */
    function init() {
        attachEventHandlers();
    }

    /**
     * Attach event handlers
     */
    function attachEventHandlers() {
        // Setup 2FA button
        $('.vmpfence-setup-2fa-btn').on('click', function() {
            startSetup();
        });

        // Cancel setup
        $('.vmpfence-cancel-setup-btn').on('click', function() {
            cancelSetup();
        });

        // Verify setup
        $('.vmpfence-verify-2fa-btn').on('click', function() {
            verifySetup();
        });

        // Finish setup
        $('.vmpfence-finish-setup-btn').on('click', function() {
            finishSetup();
        });

        // Disable 2FA
        $('.vmpfence-disable-2fa-btn').on('click', function() {
            disable2FA();
        });

        // Regenerate backup codes
        $('.vmpfence-regenerate-backup-codes').on('click', function() {
            regenerateBackupCodes();
        });

        // Allow Enter key on verification code input
        $('.vmpfence-2fa-verify-code').on('keypress', function(e) {
            if (e.which === 13) {
                e.preventDefault();
                verifySetup();
            }
        });
    }

    /**
     * Show loading overlay
     */
    function showLoading() {
        $('.vmpfence-loading-overlay').fadeIn(200);
    }

    /**
     * Hide loading overlay
     */
    function hideLoading() {
        $('.vmpfence-loading-overlay').fadeOut(200);
    }

    /**
     * Show message
     */
    function showMessage(message, type) {
        const $messages = $('.vmpfence-messages');
        const $msg = $('<div class="message ' + type + '"></div>').text(message);
        $messages.html($msg);
        
        // Auto-hide success messages after 5 seconds
        if (type === 'success') {
            setTimeout(function() {
                $msg.fadeOut(function() {
                    $(this).remove();
                });
            }, 5000);
        }
    }

    /**
     * Start 2FA setup
     */
    function startSetup() {
        showLoading();
        
        $.ajax({
            url: vmpfenceFrontend2FA.ajaxurl,
            type: 'POST',
            data: {
                action: 'vmpfence_setup_2fa',
                nonce: vmpfenceFrontend2FA.nonce
            },
            success: function(response) {
                hideLoading();
                
                if (response.success) {
                    qrCodeData = response.data;
                    
                    // Show QR code
                    $('.vmpfence-qr-code-container').html(
                        '<img src="' + response.data.qr_code_url + '" alt="QR Code" />'
                    );
                    
                    // Show setup modal
                    $('.vmpfence-2fa-setup-modal').fadeIn();
                    
                    // Focus on code input
                    setTimeout(function() {
                        $('.vmpfence-2fa-verify-code').focus();
                    }, 300);
                } else {
                    showMessage(response.data.message || 'Failed to start 2FA setup', 'error');
                }
            },
            error: function() {
                hideLoading();
                showMessage('Network error while starting 2FA setup', 'error');
            }
        });
    }

    /**
     * Cancel setup
     */
    function cancelSetup() {
        $('.vmpfence-2fa-setup-modal').fadeOut();
        $('.vmpfence-2fa-verify-code').val('');
        $('.vmpfence-qr-code-container').empty();
        qrCodeData = null;
    }

    /**
     * Verify setup
     */
    function verifySetup() {
        const code = $('.vmpfence-2fa-verify-code').val().trim();
        
        if (!/^\d{6}$/.test(code)) {
            showMessage('Please enter a valid 6-digit code', 'error');
            return;
        }
        
        showLoading();
        
        $.ajax({
            url: vmpfenceFrontend2FA.ajaxurl,
            type: 'POST',
            data: {
                action: 'vmpfence_verify_2fa_setup',
                nonce: vmpfenceFrontend2FA.nonce,
                code: code
            },
            success: function(response) {
                hideLoading();
                
                if (response.success) {
                    // Store backup codes
                    backupCodes = response.data.backup_codes || [];
                    
                    // Hide step 1, show complete
                    $('.vmpfence-2fa-setup-step-1').hide();
                    $('.vmpfence-2fa-setup-complete').show();
                    
                    // Display backup codes
                    displayBackupCodes(backupCodes, '.vmpfence-2fa-setup-complete .vmpfence-backup-codes-list');
                } else {
                    showMessage(response.data.message || 'Invalid code. Please try again.', 'error');
                    $('.vmpfence-2fa-verify-code').val('').focus();
                }
            },
            error: function() {
                hideLoading();
                showMessage('Network error while verifying code', 'error');
            }
        });
    }

    /**
     * Finish setup
     */
    function finishSetup() {
        showLoading();
        
        $.ajax({
            url: vmpfenceFrontend2FA.ajaxurl,
            type: 'POST',
            data: {
                action: 'vmpfence_enable_2fa',
                nonce: vmpfenceFrontend2FA.nonce
            },
            success: function(response) {
                hideLoading();
                
                if (response.success) {
                    // Reload page to show enabled state
                    location.reload();
                } else {
                    showMessage(response.data.message || 'Failed to enable 2FA', 'error');
                }
            },
            error: function() {
                hideLoading();
                showMessage('Network error while enabling 2FA', 'error');
            }
        });
    }

    /**
     * Disable 2FA
     */
    function disable2FA() {
        if (!confirm('Are you sure you want to disable Two-Factor Authentication? This will make your account less secure.')) {
            return;
        }
        
        showLoading();
        
        $.ajax({
            url: vmpfenceFrontend2FA.ajaxurl,
            type: 'POST',
            data: {
                action: 'vmpfence_disable_2fa',
                nonce: vmpfenceFrontend2FA.nonce
            },
            success: function(response) {
                hideLoading();
                
                if (response.success) {
                    // Reload page to show disabled state
                    location.reload();
                } else {
                    showMessage(response.data.message || 'Failed to disable 2FA', 'error');
                }
            },
            error: function() {
                hideLoading();
                showMessage('Network error while disabling 2FA', 'error');
            }
        });
    }

    /**
     * Regenerate backup codes
     */
    function regenerateBackupCodes() {
        if (!confirm('This will invalidate your current backup codes. Do you want to continue?')) {
            return;
        }
        
        showLoading();
        
        $.ajax({
            url: vmpfenceFrontend2FA.ajaxurl,
            type: 'POST',
            data: {
                action: 'vmpfence_regenerate_backup_codes',
                nonce: vmpfenceFrontend2FA.nonce
            },
            success: function(response) {
                hideLoading();
                
                if (response.success && response.data.backup_codes) {
                    // Display new backup codes
                    displayBackupCodes(response.data.backup_codes, '.vmpfence-backup-codes-container .vmpfence-backup-codes-list');
                    $('.vmpfence-backup-codes-container').slideDown();
                    showMessage('Backup codes regenerated successfully', 'success');
                } else {
                    showMessage(response.data.message || 'Failed to regenerate backup codes', 'error');
                }
            },
            error: function() {
                hideLoading();
                showMessage('Network error while regenerating backup codes', 'error');
            }
        });
    }

    /**
     * Display backup codes
     */
    function displayBackupCodes(codes, container) {
        const $container = $(container);
        $container.empty();
        
        if (!codes || codes.length === 0) {
            $container.html('<p>No backup codes available</p>');
            return;
        }
        
        codes.forEach(function(code) {
            $container.append('<span class="backup-code">' + code + '</span>');
        });
    }

    // Initialize when document is ready
    $(document).ready(function() {
        init();
    });

})(jQuery);
