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

(function($) {
    'use strict';

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

    function initEmail2FA() {
        // Enable Email 2FA button
        $('#guard-dog-enable-email-2fa').on('click', function() {
            enableEmail2FA();
        });

        // Disable Email 2FA button
        $('#guard-dog-disable-email-2fa').on('click', function() {
            disableEmail2FA();
        });

        // Verify Email 2FA code button
        $('#guard-dog-verify-email-2fa-button').on('click', function() {
            verifyEmail2FACode();
        });
    }

    function enableEmail2FA() {
        const button = $('#guard-dog-enable-email-2fa');
        const userId = button.data('user-id');
        const nonce = button.data('nonce');
        const setupSection = $('#guard-dog-email-2fa-setup-section');
        const feedbackDiv = $('#guard-dog-email-2fa-setup-feedback');

        // Disable button and show loading state
        button.prop('disabled', true).text(guard_dog_email_2fa.strings.enabling || 'Sending Code...');

        $.ajax({
            url: guard_dog_email_2fa.ajax_url,
            type: 'POST',
            data: {
                action: 'guard_dog_enable_email_2fa',
                user_id: userId,
                _wpnonce: nonce
            },
            success: function(response) {
                if (response.success) {
                    if (response.data.requires_verification) {
                        // Show verification form
                        setupSection.addClass('show');
                        button.hide();
                        showResultMessage(feedbackDiv, response.data.message, 'success');
                    } else {
                        showMessage(response.data.message, 'success');
                        // Reload page to update UI
                        setTimeout(function() {
                            location.reload();
                        }, 1500);
                    }
                } else {
                    showMessage(response.data.message || 'Failed to enable email 2FA', 'error');
                }
            },
            error: function() {
                showMessage('Network error. Please try again.', 'error');
            },
            complete: function() {
                button.prop('disabled', false).text(guard_dog_email_2fa.strings.enable_button || 'Enable Email 2FA');
            }
        });
    }

    function disableEmail2FA() {
        const button = $('#guard-dog-disable-email-2fa');
        const userId = button.data('user-id');
        const nonce = button.data('nonce');

        // Confirm before disabling
        if (!confirm(guard_dog_email_2fa.strings.confirm_disable || 'Are you sure you want to disable email two-factor authentication?')) {
            return;
        }

        // Disable button and show loading state
        button.prop('disabled', true).text('Disabling...');

        $.ajax({
            url: guard_dog_email_2fa.ajax_url,
            type: 'POST',
            data: {
                action: 'guard_dog_disable_email_2fa',
                user_id: userId,
                _wpnonce: nonce
            },
            success: function(response) {
                if (response.success) {
                    showMessage(response.data.message, 'success');
                    // Reload the page to show updated status
                    setTimeout(function() {
                        window.location.reload();
                    }, 2000);
                } else {
                    showMessage(response.data.message || 'Failed to disable email 2FA', 'error');
                }
            },
            error: function() {
                showMessage('Network error. Please try again.', 'error');
            },
            complete: function() {
                button.prop('disabled', false).text('Disable Email 2FA');
            }
        });
    }

    function verifyEmail2FACode() {
        const button = $('#guard-dog-verify-email-2fa-button');
        const userId = $('#guard-dog-enable-email-2fa').data('user-id');
        const code = $('#guard-dog-email-2fa-verify-code').val();
        const feedbackDiv = $('#guard-dog-email-2fa-setup-feedback');


        if (!code || code.length !== 6) {
            showResultMessage(feedbackDiv, 'Please enter a valid 6-digit verification code.', 'error');
            return;
        }

        // Get the verify nonce - make sure it exists
        const verifyNonce = guard_dog_email_2fa.nonces && guard_dog_email_2fa.nonces.verifyCode 
            ? guard_dog_email_2fa.nonces.verifyCode 
            : '';


        if (!verifyNonce) {
            showResultMessage(feedbackDiv, 'Security token missing. Please refresh the page and try again.', 'error');
            return;
        }

        // Disable button and show loading state
        button.prop('disabled', true).text('Verifying...');

        const requestData = {
            action: 'guard_dog_verify_email_2fa_code',
            user_id: userId,
            code: code,
            _wpnonce: verifyNonce
        };


        $.ajax({
            url: guard_dog_email_2fa.ajax_url,
            type: 'POST',
            data: requestData,
            success: function(response) {
                if (response.success) {
                    showResultMessage(feedbackDiv, response.data.message, 'success');
                    // Reload the page to show updated status
                    setTimeout(function() {
                        window.location.reload();
                    }, 2000);
                } else {
                    showResultMessage(feedbackDiv, response.data.message || 'Invalid verification code.', 'error');
                }
            },
            error: function(xhr, status, error) {
                showResultMessage(feedbackDiv, 'Network error. Please try again.', 'error');
            },
            complete: function() {
                button.prop('disabled', false).text('Verify & Enable');
            }
        });
    }

    function showMessage(message, type) {
        // Create a temporary message element
        const messageDiv = $('<div class="notice notice-' + type + ' is-dismissible"><p>' + message + '</p></div>');
        
        // Insert at the top of the page
        $('.wrap h1').after(messageDiv);
        
        // Auto-dismiss after 5 seconds
        setTimeout(function() {
            messageDiv.fadeOut(function() {
                messageDiv.remove();
            });
        }, 5000);
    }

    function showResultMessage(container, message, type) {
        container.html('<div class="notice notice-' + type + '"><p>' + message + '</p></div>');
        
        // Auto-hide after 5 seconds
        setTimeout(function() {
            container.fadeOut();
        }, 5000);
    }

    function updateEmail2FAStatus(enabled) {
        const email2FASection = $('#guard-dog-email-2fa-section');
        const setupSection = $('#guard-dog-email-2fa-setup-section');
        const enableButton = $('#guard-dog-enable-email-2fa');
        const statusCell = email2FASection.find('table tr:first-child td');

        if (enabled) {
            // Hide setup section and enable button
            setupSection.hide();
            enableButton.hide();

            // Update status to show enabled
            statusCell.html(`
                <p>
                    <span class="guard-dog-2fa-status-enabled">
                        <span class="dashicons dashicons-yes-alt"></span>
                        Enabled
                    </span>
                </p>
                <p class="description">
                    You will receive a 6-digit verification code via email when logging in.
                </p>
                <button type="button" id="guard-dog-disable-email-2fa" class="button" 
                        data-user-id="${enableButton.data('user-id')}" 
                        data-nonce="${guard_dog_email_2fa.nonces.disable}">
                    Disable Email 2FA
                </button>
            `);

            // Re-bind event handlers for new elements
            initEmail2FA();
        } else {
            // Show enable button
            enableButton.show();

            // Update status to show disabled
            statusCell.html(`
                <p>
                    <span class="guard-dog-2fa-status-disabled">
                        <span class="dashicons dashicons-no-alt"></span>
                        Disabled
                    </span>
                </p>
                <button type="button" id="guard-dog-enable-email-2fa" class="button button-primary" 
                        data-user-id="${enableButton.data('user-id')}" 
                        data-nonce="${enableButton.data('nonce')}">
                    Enable Email 2FA
                </button>
                <p class="description">
                    Enable email-based two-factor authentication. You will receive a 6-digit code via email when logging in.
                </p>
                
                <!-- Email 2FA Setup Section -->
                <div id="guard-dog-email-2fa-setup-section" class="guard-dog-email-2fa-setup-section">
                    <h4>Email 2FA Setup</h4>
                    <p>A verification code has been sent to your email address. Please enter the code below to complete the setup.</p>
                    
                    <p>
                        <label for="guard-dog-email-2fa-verify-code">Verification Code: </label>
                        <input type="text" id="guard-dog-email-2fa-verify-code" name="guard_dog_email_2fa_verify_code" size="6" maxlength="6" autocomplete="off" />
                        <button type="button" id="guard-dog-verify-email-2fa-button" class="button button-secondary guard-dog-verify-button">
                            Verify & Enable
                        </button>
                    </p>
                    <div id="guard-dog-email-2fa-setup-feedback" class="guard-dog-email-2fa-feedback"></div>
                </div>
            `);

            // Re-bind event handlers for new elements
            initEmail2FA();
        }
    }

})(jQuery);
