/* 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');
    var $enrollEmailButton = $('#enroll-email-2fa');

    if ($setupButton.length) {
        $setupButton.on('click', function(e) {
            e.preventDefault();
            generateAdminQRCode();
        });
    }

    if ($generateQrButton.length) {
        $generateQrButton.on('click', function(e) {
            e.preventDefault();
            generateAdminQRCode();
        });
    }

    if ($resetButton.length) {
        $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();
            }
        });
    }

    if ($enrollEmailButton.length) {
        $enrollEmailButton.on('click', function(e) {
            e.preventDefault();
            if (confirm(admin_2fa_config.messages.email_enroll_confirm || 'Enable two-factor authentication using email codes?')) {
                enrollEmail2FA();
            }
        });
    }

    if ($codeInput.length) {
        $codeInput.on('input', function () {
            var inputValue = $(this).val();
            inputValue = inputValue.replace(/\D/g, '');
            inputValue = inputValue.slice(0, 6);
            $(this).val(inputValue);
            $verifyButton.prop('disabled', inputValue.length !== 6);
        });
    }

    if ($verifyButton.length) {
        $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() {
        if ($setupButton.length) {
            $setupButton.prop('disabled', true);
        }
        if ($generateQrButton.length) {
            $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) {
                if ($setupButton.length) {
                    $setupButton.prop('disabled', false);
                }
                if ($generateQrButton.length) {
                    $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 () {
                if ($setupButton.length) {
                    $setupButton.prop('disabled', false);
                }
                if ($generateQrButton.length) {
                    $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');
                    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');
            }
        });
    }

    /**
     * Enroll user in email-based 2FA
     */
    function enrollEmail2FA() {
        $enrollEmailButton.prop('disabled', true);
        showMessage('Enabling email 2FA...', 'info');

        $.ajax({
            url: admin_2fa_config.ajaxurl,
            type: 'POST',
            data: {
                action: 'secnin_admin_enroll_email_2fa',
                user_id: admin_2fa_config.user_id,
                nonce: admin_2fa_config.nonce
            },
            success: function (response) {
                if (response.success) {
                    showMessage(response.data.message || admin_2fa_config.messages.email_enroll_success, 'success');
                    setTimeout(function() {
                        window.location.reload();
                    }, 2000);
                } else {
                    $enrollEmailButton.prop('disabled', false);
                    showMessage(response.data.message || admin_2fa_config.messages.unknown_error, 'error');
                }
            },
            error: function () {
                $enrollEmailButton.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
    if ($('#admin-copy-secret').length) {
        $('#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.');
            });
        }
        });
    }
});
