/**
 * Guard Dog Two-Factor Authentication Login JavaScript
 *
 * @package GuardDog
 * @since 1.8.0
 */

(function($) {
    'use strict';

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

    function init2FALogin() {
        // Hide recovery link initially if method selector is present (both methods available)
        const methodSelector = $('.guard-dog-2fa-method-selector');
        const recoveryLinkContainer = $('#guard-dog-recovery-link-container');
        
        if (methodSelector.length > 0 && recoveryLinkContainer.length > 0) {
            recoveryLinkContainer.hide();
        }

        // Method switching for users with both app and email 2FA
        $('input[name="guard_dog_2fa_method"]').on('change', function() {
            const method = $(this).val();
            switch2FAMethod(method);
        });

        // Recovery code toggle
        $('#guard-dog-use-recovery-code').on('click', function(e) {
            e.preventDefault();
            showRecoveryForm();
        });

        $('#guard-dog-use-totp-code').on('click', function(e) {
            e.preventDefault();
            showTOTPForm();
        });

        // Send email code button
        $('#guard-dog-send-email-code').on('click', function(e) {
            e.preventDefault();
            sendEmailCode();
        });

        // Auto-send email code when email method is selected
        $('input[name="guard_dog_2fa_method"][value="email"]').on('change', function() {
            if ($(this).is(':checked')) {
                // Show status and send email
                const statusDiv = $('#guard-dog-2fa-email-status');
                statusDiv.html('<p class="guard-dog-2fa-sending">Sending verification code to your email...</p>').show();
                
                // Small delay to ensure form is visible
                setTimeout(function() {
                    sendEmailCodeForLogin();
                }, 100);
            }
        });
    }

    function switch2FAMethod(method) {
        const codeSection = $('.guard-dog-2fa-code-section');
        const recoveryLinkContainer = $('#guard-dog-recovery-link-container');

        // Show the code section now that a method is selected
        if (codeSection.length > 0) {
            codeSection.addClass('show');
            // Focus on the code input
            $('#guard_dog_2fa_code').focus();
        }

        // Show/hide recovery link based on method selection
        if (recoveryLinkContainer.length > 0) {
            if (method === 'app') {
                recoveryLinkContainer.show();
            } else {
                recoveryLinkContainer.hide();
            }
        }

        // For separate email form (when user has email-only 2FA)
        const emailForm = $('#emailform');
        if (emailForm.length > 0) {
            if (method === 'email') {
                emailForm.addClass('show');
                $('#guard_dog_email_2fa_code').focus();
            } else {
                emailForm.removeClass('show');
            }
        }
    }

    function showRecoveryForm() {
        $('#loginform').removeClass('show');
        $('#emailform').removeClass('show');
        $('#recoveryform').addClass('show');
        $('#guard_dog_2fa_recovery_code').focus();
        $('.guard-dog-2fa-recovery-info').addClass('show');
    }

    function showTOTPForm() {
        $('#recoveryform').removeClass('show');
        $('#emailform').removeClass('show');
        $('#loginform').addClass('show');
        $('#guard_dog_2fa_code').focus();
        $('.guard-dog-2fa-recovery-info').removeClass('show');
    }

    function sendEmailCode() {
        const button = $('#guard-dog-send-email-code');
        const statusSpan = $('#guard-dog-email-code-status');
        const username = $('input[name="log"]').val();
        const userId = guard_dog_login_2fa.userId || getUserIdFromForm();
        

        // Disable button and show loading state
        button.prop('disabled', true).text(guard_dog_login_2fa.strings.sending || 'Sending...');
        statusSpan.html('<span class="guard-dog-2fa-sending">Sending code...</span>');

        $.ajax({
            url: guard_dog_login_2fa.ajaxUrl,
            type: 'POST',
            data: {
                action: 'guard_dog_send_email_2fa_code',
                user_id: userId,
                _wpnonce: $('input[name="guard_dog_2fa_nonce"]').val()
            },
            success: function(response) {
                if (response.success) {
                    statusSpan.html('<span class="guard-dog-2fa-success">✓ ' + response.data.message + '</span>');
                    // Auto-focus the code input
                    $('#guard_dog_email_2fa_code').focus();
                } else {
                    statusSpan.html('<span class="guard-dog-2fa-error">✗ ' + (response.data.message || guard_dog_login_2fa.strings.error) + '</span>');
                }
            },
            error: function(xhr, status, error) {
                statusSpan.html('<span class="guard-dog-2fa-error">✗ ' + guard_dog_login_2fa.strings.networkError + '</span>');
            },
            complete: function() {
                button.prop('disabled', false).text('Send Code to Email');
                
                // Clear status after 5 seconds
                setTimeout(function() {
                    statusSpan.html('');
                }, 5000);
            }
        });
    }

    function sendEmailCodeForLogin() {
        const statusDiv = $('#guard-dog-2fa-email-status');
        const username = $('input[name="log"]').val();
        const userId = guard_dog_login_2fa.userId || getUserIdFromForm();
        
        // Prevent multiple simultaneous sends
        if (statusDiv.data('sending')) {
            return;
        }
        
        statusDiv.data('sending', true);

        $.ajax({
            url: guard_dog_login_2fa.ajaxUrl,
            type: 'POST',
            data: {
                action: 'guard_dog_send_email_2fa_code',
                user_id: userId,
                _wpnonce: $('input[name="guard_dog_2fa_nonce"]').val()
            },
            success: function(response) {
                if (response.success) {
                    statusDiv.html('<p class="guard-dog-2fa-success">Code sent! Check your email.</p>');
                } else {
                    statusDiv.html('<p class="guard-dog-2fa-error">' + (response.data.message || 'Error sending code. Please try again.') + '</p>');
                }
            },
            error: function(xhr, status, error) {
                statusDiv.html('<p class="guard-dog-2fa-error">Network error. Please try again.</p>');
            },
            complete: function() {
                statusDiv.data('sending', false);
                // Hide status after 5 seconds
                setTimeout(function() {
                    statusDiv.fadeOut();
                }, 5000);
            }
        });
    }

    function getUserIdFromForm() {
        // Try to get user ID from the form data
        // This is a fallback method - ideally the user ID should be passed to the form
        const username = $('input[name="log"]').val();
        
        // For now, we'll use a simple approach - in a real implementation,
        // the user ID should be available in the form or passed via AJAX
        return 0; // This will be handled server-side
    }

})(jQuery); 