/* global admin_2fa_config, jQuery */
/**
 * Admin 2FA setup functionality
 */

jQuery(document).ready(function ($) {
    var $setupButton = $('#setup-2fa');
    var $qrContainer = $('#admin-2fa-qr-container');
    var $qrImg = $('#admin-qr-code-img');
    var $qrError = $('#admin-qr-code-err');
    var $qrSpinner = $('#admin-qr-spinner');
    var $generateQrButton = $('#admin-generate-qr');
    var $verifyButton = $('#admin-verify-2fa');
    var $codeInput = $('#admin-2fa-code');
    var $verifyMsg = $('#admin-2fa-verify-msg');
    var $resetButton = $('#reset-2fa');

    // Setup 2FA button click
    $setupButton.on('click', function(e) {
        e.preventDefault();
        generateAdminQRCode();
    });

    // Generate QR button click
    $generateQrButton.on('click', function(e) {
        e.preventDefault();
        generateAdminQRCode();
    });

    // Reset 2FA button click
    $resetButton.on('click', function(e) {
        e.preventDefault();
        if (confirm(admin_2fa_config.messages.reset_confirm || 'Are you sure you want to reset 2FA for this user?')) {
            resetAdmin2FA();
        }
    });

    // Code input validation
    $codeInput.on('input', function () {
        var inputValue = $(this).val();
        
        // Remove any non-digit characters
        inputValue = inputValue.replace(/\D/g, '');
        
        // Limit to 6 digits
        inputValue = inputValue.slice(0, 6);
        
        // Update input value
        $(this).val(inputValue);
        
        // Enable/disable verify button based on input validity
        $verifyButton.prop('disabled', inputValue.length !== 6);
    });

    // Verify button click
    $verifyButton.on('click', function(e) {
        e.preventDefault();
        var code = $codeInput.val();
        
        if (code.length !== 6) {
            showMessage('Please enter a valid 6-digit code.', 'error');
            return;
        }
        
        verifyAdmin2FA(code);
    });

    /**
     * Generate QR code for admin 2FA setup
     */
    function generateAdminQRCode() {
        $setupButton.prop('disabled', true);
        $generateQrButton.prop('disabled', true);
        $qrSpinner.addClass('is-active');
        $qrError.empty();
        $qrContainer.show();

        $.ajax({
            url: admin_2fa_config.ajaxurl,
            type: 'POST',
            data: {
                action: 'secnin_admin_generate_qr',
                user_id: admin_2fa_config.user_id,
                nonce: admin_2fa_config.nonce
            },
            success: function (response) {
                $setupButton.prop('disabled', false);
                $generateQrButton.prop('disabled', false);
                $qrSpinner.removeClass('is-active');
                
                if (response.success && response.data && response.data.qr_code) {
                    $qrError.empty();
                    $qrImg.attr('src', response.data.qr_code);
                    $generateQrButton.show();
                    
                    // Show and populate the secret key if available
                    if (response.data.secret) {
                        $('#admin-secret-key').val(response.data.secret);
                        $('#admin-secret-container').show();
                    }
                    // showMessage(response.data.message, 'success');
                } else {
                    $qrError.html('<p class="error">' + 
                        (response.data && response.data.message ? response.data.message : admin_2fa_config.messages.qr_error) + '</p>');
                }
            },
            error: function () {
                $setupButton.prop('disabled', false);
                $generateQrButton.prop('disabled', false);
                $qrSpinner.removeClass('is-active');
                $qrError.html('<p class="error">' + admin_2fa_config.messages.network_error + '</p>');
            }
        });
    }

    /**
     * Verify 2FA code for admin setup
     */
    function verifyAdmin2FA(code) {
        $verifyButton.prop('disabled', true);
        $codeInput.prop('disabled', true);
        showMessage(admin_2fa_config.messages.verifying, 'info');

        $.ajax({
            url: admin_2fa_config.ajaxurl,
            type: 'POST',
            data: {
                action: 'secnin_admin_verify_2fa',
                user_id: admin_2fa_config.user_id,
                nonce: admin_2fa_config.nonce,
                code: code
            },
            success: function (response) {
                if (response.success) {
                    showMessage(response.data.message, 'success');
                    // Reload the page after a short delay to show updated status
                    setTimeout(function() {
                        window.location.reload();
                    }, 2000);
                } else {
                    $verifyButton.prop('disabled', false);
                    $codeInput.prop('disabled', false);
                    showMessage(response.data.message || admin_2fa_config.messages.invalid_code, 'error');
                }
            },
            error: function () {
                $verifyButton.prop('disabled', false);
                $codeInput.prop('disabled', false);
                showMessage(admin_2fa_config.messages.network_error, 'error');
            }
        });
    }

    /**
     * Reset 2FA for user
     */
    function resetAdmin2FA() {
        $resetButton.prop('disabled', true);
        showMessage('Resetting 2FA...', 'info');

        $.ajax({
            url: admin_2fa_config.ajaxurl,
            type: 'POST',
            data: {
                action: 'secnin_admin_reset_2fa',
                user_id: admin_2fa_config.user_id,
                nonce: admin_2fa_config.nonce
            },
            success: function (response) {
                if (response.success) {
                    showMessage(response.data.message, 'success');
                    // Reload the page after a short delay to show updated status
                    setTimeout(function() {
                        window.location.reload();
                    }, 2000);
                } else {
                    $resetButton.prop('disabled', false);
                    showMessage(response.data.message || admin_2fa_config.messages.unknown_error, 'error');
                }
            },
            error: function () {
                $resetButton.prop('disabled', false);
                showMessage(admin_2fa_config.messages.network_error, 'error');
            }
        });
    }

    /**
     * Show message to user
     */
    function showMessage(message, type) {
        var cssClass = 'notice notice-' + (type === 'error' ? 'error' : type === 'success' ? 'success' : 'info');
        $verifyMsg.html('<div class="' + cssClass + '"><p>' + message + '</p></div>');
    }

    // Add click handler for the Copy Secret button
    $('#admin-copy-secret').on('click', function(e) {
        e.preventDefault();
        var secretInput = document.getElementById('admin-secret-key');
        secretInput.select();
        secretInput.setSelectionRange(0, 99999); // For mobile devices
        
        try {
            document.execCommand('copy');
            var $button = $(this);
            var originalText = $button.text();
            $button.text('Copied!');
            setTimeout(function() {
                $button.text(originalText);
            }, 2000);
        } catch (err) {
            // Fallback for browsers that don't support execCommand
            navigator.clipboard.writeText(secretInput.value).then(function() {
                var $button = $('#admin-copy-secret');
                var originalText = $button.text();
                $button.text('Copied!');
                setTimeout(function() {
                    $button.text(originalText);
                }, 2000);
            }).catch(function() {
                alert('Failed to copy secret key. Please select and copy manually.');
            });
        }
    });
});
