/**
 * Guard Dog Unified Two-Factor Authentication Shortcode JavaScript
 * 
 * Handles both app-based (TOTP) and email-based 2FA methods
 *
 * @package GuardDog
 * @since 1.6.0
 */

(function($) {
    'use strict';

    // Main Unified 2FA Shortcode Object
    const GD2FA = {
        // Properties
        ajaxUrl: '',
        nonces: {},
        userId: 0,
        initTime: 0,
        currentRequest: null,
        nonceCheckInterval: null,
        email2faAvailable: false,
        activeContainer: null,

        // Initialize the shortcode
        init: function() {
            // Check if required data is available
            if (typeof guard_dog_2fa_shortcode === 'undefined') {
                console.error('Guard Dog 2FA: guard_dog_2fa_shortcode not found. Check if the script is properly localized.');
                return;
            }
            
            if (!guard_dog_2fa_shortcode.ajaxUrl) {
                console.error('Guard Dog 2FA: AJAX URL not found in localized data.');
                return;
            }
            
            if (!guard_dog_2fa_shortcode.nonces) {
                console.error('Guard Dog 2FA: Nonces not found in localized data.');
                return;
            }
            
            // Check if required nonce keys exist for app-based 2FA
            const requiredAppNonces = ['generate', 'verify', 'regenerateRecovery', 'disable'];
            for (const nonceKey of requiredAppNonces) {
                if (!guard_dog_2fa_shortcode.nonces[nonceKey]) {
                    console.error(`Guard Dog 2FA: Required app-based nonce '${nonceKey}' not found in localized data.`);
                    return;
                }
            }
            
            // Check if email 2FA nonces exist (optional)
            const emailNonces = ['emailEnable', 'emailVerify', 'emailSendCode', 'emailDisable'];
            const hasEmailNonces = emailNonces.every(key => guard_dog_2fa_shortcode.nonces[key]);
            
            if (hasEmailNonces) {
                console.log('Guard Dog 2FA: Email 2FA nonces detected');
            }
            
            this.container = $('[data-guard-dog-2fa-container], .guard-dog-2fa-shortcode-container');
            this.activeContainer = this.container.first();
            this.ajaxUrl = guard_dog_2fa_shortcode.ajaxUrl;
            this.nonces = guard_dog_2fa_shortcode.nonces;
            this.userId = guard_dog_2fa_shortcode.userId;
            this.initTime = Date.now();
            
            // Check if email 2FA is available based on nonces
            this.email2faAvailable = this.nonces.emailEnable !== undefined;
            
            // Setup event listeners
            this.setupEventListeners();
            
            console.log('Guard Dog 2FA: Initialized successfully with data:', {
                ajaxUrl: this.ajaxUrl,
                nonces: Object.keys(this.nonces),
                userId: this.userId,
                email2faAvailable: this.email2faAvailable,
                timestamp: new Date().toISOString()
            });
            
            // Start nonce validity checking
            this.startNonceChecking();

            // Add cleanup on page unload
            $(window).on('beforeunload', () => this.cleanup());
        },

        // Setup event listeners
        setupEventListeners: function() {
            // App-based 2FA buttons
            $(document).on('click', '[data-guard-dog-enable-app-2fa], #guard-dog-enable-app-2fa', this.enableApp2FA.bind(this));
            $(document).on('click', '[data-guard-dog-disable-app-2fa], #guard-dog-disable-app-2fa', this.disableApp2FA.bind(this));
            $(document).on('click', '[data-guard-dog-verify-app-2fa], #guard-dog-verify-app-2fa', this.verifyAndEnableApp2FA.bind(this));
            
            // Email-based 2FA buttons (only when available)
            if (this.email2faAvailable) {
                $(document).on('click', '[data-guard-dog-enable-email-2fa], #guard-dog-enable-email-2fa', this.enableEmail2FA.bind(this));
                $(document).on('click', '[data-guard-dog-disable-email-2fa], #guard-dog-disable-email-2fa', this.disableEmail2FA.bind(this));
                $(document).on('click', '[data-guard-dog-verify-email-2fa], #guard-dog-verify-email-2fa', this.verifyAndEnableEmail2FA.bind(this));
                $(document).on('click', '[data-guard-dog-resend-email-2fa-code], #guard-dog-resend-email-2fa-code', this.resendEmailCode.bind(this));
            }
            
            // Common buttons
            $(document).on('click', '[data-guard-dog-regenerate-recovery-codes], #guard-dog-regenerate-recovery-codes', this.regenerateRecoveryCodes.bind(this));
            $(document).on('click', '[data-guard-dog-copy-recovery-codes], #guard-dog-copy-recovery-codes', this.copyAllRecoveryCodes.bind(this));
            $(document).on('click', '[data-guard-dog-copy-secret-key], #guard-dog-copy-secret-key', this.copySecretKey.bind(this));
            $(document).on('click', '.guard-dog-2fa-code-copy', this.copyIndividualCode.bind(this));
            
            // Verify code input (app-based)
            $(document).on('keypress', '[data-guard-dog-2fa-verify-code], #guard-dog-2fa-verify-code', function(e) {
                if (e.which === 13) { // Enter key
                    e.preventDefault();
                    const $container = $(e.currentTarget).closest('[data-guard-dog-2fa-container], .guard-dog-2fa-shortcode-container');
                    const $button = $container.find('[data-guard-dog-verify-app-2fa]').first();
                    ($button.length ? $button : $('#guard-dog-verify-app-2fa')).click();
                }
            });
            
            // Verify code input (email-based)
            if (this.email2faAvailable) {
                $(document).on('keypress', '[data-guard-dog-email-2fa-verify-code], #guard-dog-email-2fa-verify-code', function(e) {
                    if (e.which === 13) { // Enter key
                        e.preventDefault();
                        const $container = $(e.currentTarget).closest('[data-guard-dog-2fa-container], .guard-dog-2fa-shortcode-container');
                        const $button = $container.find('[data-guard-dog-verify-email-2fa]').first();
                        ($button.length ? $button : $('#guard-dog-verify-email-2fa')).click();
                    }
                });
            }
        },

        getContainer: function(element) {
            const $container = $(element).closest('[data-guard-dog-2fa-container], .guard-dog-2fa-shortcode-container');

            if ($container.length) {
                return $container;
            }

            return this.activeContainer && this.activeContainer.length ? this.activeContainer : this.container.first();
        },

        setActiveContainer: function(element) {
            this.activeContainer = this.getContainer(element);
            return this.activeContainer;
        },

        findInContainer: function($container, dataSelector, legacySelector) {
            const $dataElement = $container.find(dataSelector).first();

            if ($dataElement.length) {
                return $dataElement;
            }

            const $legacyElement = $container.find(legacySelector).first();

            if ($legacyElement.length) {
                return $legacyElement;
            }

            return $container[0] === document ? $(legacySelector).first() : $();
        },

        // Enable App-based 2FA
        enableApp2FA: function(e) {
            e.preventDefault();
            const button = $(e.currentTarget);
            const $container = this.setActiveContainer(button);
            const userId = button.data('user-id');
            const nonce = this.nonces.generate;

            // Debug logging with timing information
            const timeSinceInit = Date.now() - this.initTime;
            console.log('Guard Dog 2FA: Enable App 2FA clicked:', {
                timeSinceInit: timeSinceInit + 'ms',
                userId: userId,
                nonce: nonce,
                nonceLength: nonce ? nonce.length : 0,
                ajaxUrl: this.ajaxUrl,
                container: $container.attr('id') || '',
                timestamp: new Date().toISOString()
            });

            // Check if nonce is still valid (basic check)
            if (!nonce || nonce.length < 10) {
                console.error('Guard Dog 2FA: Nonce appears invalid, attempting to refresh...');
                this.showMessage('error', 'Security token expired. Please refresh the page and try again.');
                return;
            }

            // Proceed with the request
            this.proceedWithEnableApp2FA(button, userId, nonce);
        },

        // Method to proceed with App 2FA enable
        proceedWithEnableApp2FA: function(button, userId, nonce) {
            // Check if page is visible (prevents requests when tab is hidden)
            if (document.hidden) {
                console.log('Guard Dog 2FA: Page is hidden, cannot proceed with request');
                this.showMessage('error', 'Cannot proceed while page is hidden. Please ensure the page is visible and try again.');
                return;
            }
            
            // Store the current request to prevent multiple requests
            if (this.currentRequest) {
                console.log('Guard Dog 2FA: Cancelling previous request...');
                this.currentRequest.abort();
            }

            this.showLoading(button);

            const generateData = {
                action: 'guard_dog_generate_2fa_secret',
                user_id: userId,
                _wpnonce: nonce
            };

            // Debug logging
            console.log('Guard Dog 2FA: Sending generate request:', {
                url: this.ajaxUrl,
                data: generateData,
                requestTime: new Date().toISOString()
            });
            
            // Store the request object
            this.currentRequest = $.ajax({
                url: this.ajaxUrl,
                type: 'POST',
                data: generateData,
                timeout: 60000, // 60 second timeout
                beforeSend: function() {
                    console.log('Guard Dog 2FA: AJAX request starting...');
                },
                success: (response) => {
                    console.log('Guard Dog 2FA: Generate response:', response);
                    this.hideLoading(button);
                    if (response.success) {
                        this.displaySetupSection(response.data);
                        this.showMessage('success', '2FA setup initiated successfully! Please scan the QR code with your authenticator app and enter the 6-digit code below.');
                    } else {
                        this.showMessage('error', response.data.message || 'Could not generate 2FA setup.');
                    }
                },
                error: (xhr, status, error) => {
                    console.error('Guard Dog 2FA: Generate error:', {xhr, status, error});
                    this.hideLoading(button);
                    
                    // Enhanced error handling
                    let errorMessage = 'Network error. Please try again.';
                    if (xhr.status === 403) {
                        errorMessage = 'Security verification failed. This usually means the security tokens have expired.';
                        // Add refresh button for 403 errors
                        this.addRefreshButton();
                    } else if (xhr.status === 0) {
                        errorMessage = 'Request was aborted or timed out. Please check your connection and try again.';
                    } else if (status === 'timeout') {
                        errorMessage = 'Request timed out after 60 seconds. Please try again.';
                    } else if (status === 'abort') {
                        errorMessage = 'Request was aborted. Please try again.';
                    }
                    
                    this.showMessage('error', errorMessage);
                },
                complete: function() {
                    console.log('Guard Dog 2FA: AJAX request completed (success or error)');
                    // Clear the current request reference
                    this.currentRequest = null;
                }.bind(this)
            });
        },

        // Verify and enable App 2FA
        verifyAndEnableApp2FA: function(e) {
            e.preventDefault();
            const button = $(e.currentTarget);
            const $container = this.setActiveContainer(button);
            const code = this.findInContainer($container, '[data-guard-dog-2fa-verify-code]', '#guard-dog-2fa-verify-code').val().trim();
            const userId = this.findInContainer($container, '[data-guard-dog-enable-app-2fa]', '#guard-dog-enable-app-2fa').data('user-id') || this.userId;
            const nonce = this.nonces.verify;

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

            this.showLoading(button);

            const verifyData = {
                action: 'guard_dog_verify_2fa_setup',
                user_id: userId,
                code: code,
                _wpnonce: nonce
            };

            // Debug logging
            console.log('Guard Dog 2FA: Sending verify request:', {
                url: this.ajaxUrl,
                data: verifyData
            });
            
            $.ajax({
                url: this.ajaxUrl,
                type: 'POST',
                data: verifyData,
                timeout: 60000, // 60 second timeout
                success: (response) => {
                    console.log('Guard Dog 2FA: Verify response:', response);
                    this.hideLoading(button);
                    if (response.success) {
                        this.showMessage('success', response.data.message);
                        setTimeout(() => {
                            location.reload();
                        }, 2000);
                    } else {
                        this.showMessage('error', response.data.message || 'Verification failed.');
                    }
                },
                error: (xhr, status, error) => {
                    console.error('Guard Dog 2FA: Verify error:', {xhr, status, error});
                    this.hideLoading(button);
                    this.showMessage('error', 'Network error. Please try again.');
                }
            });
        },

        // Disable App 2FA
        disableApp2FA: function(e) {
            e.preventDefault();
            const button = $(e.currentTarget);
            this.setActiveContainer(button);
            
            if (!confirm('Are you sure you want to disable app-based two-factor authentication? This will remove all security codes and make your account less secure.')) {
                return;
            }

            const userId = button.data('user-id');
            const nonce = this.nonces.disable;

            // Debug logging
            console.log('Guard Dog 2FA: Disable App 2FA request:', {
                userId: userId,
                nonce: nonce,
                button: button.attr('id')
            });

            this.showLoading(button);

            const disableData = {
                action: 'guard_dog_disable_2fa',
                user_id: userId,
                _wpnonce: nonce
            };

            // Debug logging
            console.log('Guard Dog 2FA: Sending disable request:', {
                url: this.ajaxUrl,
                data: disableData
            });

            $.ajax({
                url: this.ajaxUrl,
                type: 'POST',
                data: disableData,
                timeout: 60000, // 60 second timeout
                success: (response) => {
                    console.log('Guard Dog 2FA: Disable response:', response);
                    this.hideLoading(button);
                    if (response.success) {
                        this.showMessage('success', response.data.message);
                        setTimeout(() => {
                            location.reload();
                        }, 2000);
                    } else {
                        this.showMessage('error', response.data.message || 'Could not disable app-based two-factor authentication.');
                    }
                },
                error: (xhr, status, error) => {
                    console.error('Guard Dog 2FA: Disable error:', {xhr, status, error});
                    this.hideLoading(button);
                    this.showMessage('error', 'Network error. Please try again.');
                }
            });
        },

        // Enable Email 2FA
        enableEmail2FA: function(e) {
            e.preventDefault();
            const button = $(e.currentTarget);
            const $container = this.setActiveContainer(button);
            const userId = button.data('user-id');
            const nonce = this.nonces.emailEnable;

            // Debug logging with timing information
            const timeSinceInit = Date.now() - this.initTime;
            console.log('Guard Dog 2FA: Enable Email 2FA clicked:', {
                timeSinceInit: timeSinceInit + 'ms',
                userId: userId,
                nonce: nonce,
                nonceLength: nonce ? nonce.length : 0,
                ajaxUrl: this.ajaxUrl,
                container: $container.attr('id') || '',
                timestamp: new Date().toISOString()
            });

            // Check if nonce is still valid (basic check)
            if (!nonce || nonce.length < 10) {
                console.error('Guard Dog 2FA: Email 2FA nonce appears invalid, attempting to refresh...');
                this.showMessage('error', 'Security token expired. Please refresh the page and try again.');
                return;
            }

            // Proceed with the request
            this.proceedWithEnableEmail2FA(button, userId, nonce);
        },

        // Method to proceed with Email 2FA enable
        proceedWithEnableEmail2FA: function(button, userId, nonce) {
            // Check if page is visible (prevents requests when tab is hidden)
            if (document.hidden) {
                console.log('Guard Dog 2FA: Page is hidden, cannot proceed with request');
                this.showMessage('error', 'Cannot proceed while page is hidden. Please ensure the page is visible and try again.');
                return;
            }
            
            // Store the current request to prevent multiple requests
            if (this.currentRequest) {
                console.log('Guard Dog 2FA: Cancelling previous request...');
                this.currentRequest.abort();
            }

            this.showLoading(button);

            const enableData = {
                action: 'guard_dog_enable_email_2fa',
                user_id: userId,
                _wpnonce: nonce
            };

            // Debug logging
            console.log('Guard Dog 2FA: Sending email enable request:', {
                url: this.ajaxUrl,
                data: enableData,
                requestTime: new Date().toISOString()
            });
            
            // Store the request object
            this.currentRequest = $.ajax({
                url: this.ajaxUrl,
                type: 'POST',
                data: enableData,
                timeout: 60000, // 60 second timeout
                beforeSend: function() {
                    console.log('Guard Dog 2FA: Email AJAX request starting...');
                },
                success: (response) => {
                    console.log('Guard Dog 2FA: Email enable response:', response);
                    this.hideLoading(button);
                    if (response.success) {
                        this.showMessage('success', response.data.message);
                        // Show the email setup section
                        this.showEmailSetupSection();
                    } else {
                        this.showMessage('error', response.data.message || 'Could not enable Email 2FA.');
                    }
                },
                error: (xhr, status, error) => {
                    console.error('Guard Dog 2FA: Email enable error:', {xhr, status, error});
                    this.hideLoading(button);
                    
                    // Enhanced error handling
                    let errorMessage = 'Network error. Please try again.';
                    if (xhr.status === 403) {
                        errorMessage = 'Security verification failed. This usually means the security tokens have expired.';
                        // Add refresh button for 403 errors
                        this.addRefreshButton();
                    } else if (xhr.status === 0) {
                        errorMessage = 'Request was aborted or timed out. Please check your connection and try again.';
                    } else if (status === 'timeout') {
                        errorMessage = 'Request timed out after 60 seconds. Please try again.';
                    } else if (status === 'abort') {
                        errorMessage = 'Request was aborted. Please try again.';
                    }
                    
                    this.showMessage('error', errorMessage);
                },
                complete: function() {
                    console.log('Guard Dog 2FA: Email AJAX request completed (success or error)');
                    // Clear the current request reference
                    this.currentRequest = null;
                }.bind(this)
            });
        },

        // Show email setup section
        showEmailSetupSection: function() {
            const $container = this.activeContainer && this.activeContainer.length ? this.activeContainer : this.container.first();
            this.findInContainer($container, '[data-guard-dog-email-2fa-setup-section]', '#guard-dog-email-2fa-setup-section').show();
            this.findInContainer($container, '[data-guard-dog-email-2fa-verify-code]', '#guard-dog-email-2fa-verify-code').focus();
        },

        // Verify and enable Email 2FA
        verifyAndEnableEmail2FA: function(e) {
            e.preventDefault();
            const button = $(e.currentTarget);
            const $container = this.setActiveContainer(button);
            const code = this.findInContainer($container, '[data-guard-dog-email-2fa-verify-code]', '#guard-dog-email-2fa-verify-code').val().trim();
            const userId = this.userId;
            const nonce = this.nonces.emailVerify;

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

            this.showLoading(button);

            const verifyData = {
                action: 'guard_dog_verify_email_2fa_code',
                user_id: userId,
                code: code,
                _wpnonce: nonce
            };

            // Debug logging
            console.log('Guard Dog 2FA: Sending email verify request:', {
                url: this.ajaxUrl,
                data: verifyData
            });
            
            $.ajax({
                url: this.ajaxUrl,
                type: 'POST',
                data: verifyData,
                timeout: 60000, // 60 second timeout
                success: (response) => {
                    console.log('Guard Dog 2FA: Email verify response:', response);
                    this.hideLoading(button);
                    if (response.success) {
                        this.showMessage('success', response.data.message);
                        setTimeout(() => {
                            location.reload();
                        }, 2000);
                    } else {
                        this.showMessage('error', response.data.message || 'Verification failed.');
                    }
                },
                error: (xhr, status, error) => {
                    console.error('Guard Dog 2FA: Email verify error:', {xhr, status, error});
                    this.hideLoading(button);
                    this.showMessage('error', 'Network error. Please try again.');
                }
            });
        },

        // Resend verification code
        resendEmailCode: function(e) {
            e.preventDefault();
            const button = $(e.currentTarget);
            this.setActiveContainer(button);
            const userId = this.userId;
            const nonce = this.nonces.emailSendCode;

            this.showLoading(button);

            const resendData = {
                action: 'guard_dog_send_email_2fa_code',
                user_id: userId,
                _wpnonce: nonce
            };

            $.ajax({
                url: this.ajaxUrl,
                type: 'POST',
                data: resendData,
                timeout: 60000, // 60 second timeout
                success: (response) => {
                    this.hideLoading(button);
                    if (response.success) {
                        this.showMessage('success', response.data.message);
                    } else {
                        this.showMessage('error', response.data.message || 'Could not resend code.');
                    }
                },
                error: (xhr, status, error) => {
                    this.hideLoading(button);
                    this.showMessage('error', 'Network error. Please try again.');
                }
            });
        },

        // Disable Email 2FA
        disableEmail2FA: function(e) {
            e.preventDefault();
            const button = $(e.currentTarget);
            this.setActiveContainer(button);
            
            if (!confirm('Are you sure you want to disable email two-factor authentication? This will make your account less secure.')) {
                return;
            }

            const userId = button.data('user-id');
            const nonce = this.nonces.emailDisable;

            // Debug logging
            console.log('Guard Dog 2FA: Disable Email 2FA request:', {
                userId: userId,
                nonce: nonce,
                button: button.attr('id')
            });

            this.showLoading(button);

            const disableData = {
                action: 'guard_dog_disable_email_2fa',
                user_id: userId,
                _wpnonce: nonce
            };

            // Debug logging
            console.log('Guard Dog 2FA: Sending email disable request:', {
                url: this.ajaxUrl,
                data: disableData
            });

            $.ajax({
                url: this.ajaxUrl,
                type: 'POST',
                data: disableData,
                timeout: 60000, // 60 second timeout
                success: (response) => {
                    console.log('Guard Dog 2FA: Email disable response:', response);
                    this.hideLoading(button);
                    if (response.success) {
                        this.showMessage('success', response.data.message);
                        setTimeout(() => {
                            location.reload();
                        }, 2000);
                    } else {
                        this.showMessage('error', response.data.message || 'Could not disable email two-factor authentication.');
                    }
                },
                error: (xhr, status, error) => {
                    console.error('Guard Dog 2FA: Email disable error:', {xhr, status, error});
                    this.hideLoading(button);
                    this.showMessage('error', 'Network error. Please try again.');
                }
            });
        },

        // Regenerate recovery codes
        regenerateRecoveryCodes: function(e) {
            e.preventDefault();
            const button = $(e.currentTarget);
            this.setActiveContainer(button);
            
            if (!confirm('Are you sure you want to regenerate recovery codes? This will invalidate all existing codes.')) {
                return;
            }

            const userId = button.data('user-id');
            const nonce = this.nonces.regenerateRecovery;

            this.showLoading(button);

            const regenerateData = {
                action: 'guard_dog_regenerate_recovery_codes',
                user_id: userId,
                _wpnonce: nonce
            };

            $.ajax({
                url: this.ajaxUrl,
                type: 'POST',
                data: regenerateData,
                timeout: 60000, // 60 second timeout
                success: (response) => {
                    this.hideLoading(button);
                    if (response.success) {
                        this.displayRecoveryCodes(response.data.codes);
                        this.showMessage('success', response.data.message);
                    } else {
                        this.showMessage('error', response.data.message || 'Could not regenerate recovery codes.');
                    }
                },
                error: (xhr, status, error) => {
                    this.hideLoading(button);
                    this.showMessage('error', 'Network error. Please try again.');
                }
            });
        },

        // Display setup section
        displaySetupSection: function(data) {
            // Debug logging
            console.log('Guard Dog 2FA: displaySetupSection called with:', data);
            
            // Validate data
            if (!data || typeof data !== 'object') {
                console.error('Guard Dog 2FA: displaySetupSection called with invalid data:', data);
                return;
            }
            
            const $container = this.activeContainer && this.activeContainer.length ? this.activeContainer : this.container.first();
            const setupSection = this.findInContainer($container, '[data-guard-dog-2fa-setup-section]', '#guard-dog-2fa-setup-section');
            if (setupSection.length === 0) {
                console.error('Guard Dog 2FA: Setup section not found');
                return;
            }
            
            setupSection.show();

            // Display QR code or fallback
            if (data.qr_data_uri) {
                this.findInContainer($container, '[data-guard-dog-2fa-qr-code]', '#guard-dog-2fa-qr-code').html('<img src="' + data.qr_data_uri + '" alt="QR Code" class="guard-dog-2fa-qr-image">');
            } else {
                this.findInContainer($container, '[data-guard-dog-2fa-qr-code]', '#guard-dog-2fa-qr-code').html('<p>QR code generation failed. Please use the manual secret key.</p>');
            }

            // Display secret key
            if (data.secret) {
                this.findInContainer($container, '[data-guard-dog-2fa-secret-key]', '#guard-dog-2fa-secret-key').text(data.secret);
            } else {
                console.error('Guard Dog 2FA: Secret key not found in data');
            }
        },

        // Display recovery codes
        displayRecoveryCodes: function(codes) {
            const $container = this.activeContainer && this.activeContainer.length ? this.activeContainer : this.container.first();
            const codesContainer = this.findInContainer($container, '[data-guard-dog-codes-container]', '#guard-dog-codes-container');
            codesContainer.empty();

            codes.forEach(function(code) {
                const codeItem = $('<div class="guard-dog-2fa-code-item">' +
                    '<span>' + code + '</span>' +
                    '<button type="button" class="guard-dog-2fa-code-copy" data-code="' + code + '">Copy</button>' +
                    '</div>');
                codesContainer.append(codeItem);
            });

            // Update copy all functionality
            $container.find('.guard-dog-2fa-code-item span').each(function() {
                const code = $(this).text();
                $(this).next('button').attr('data-code', code);
            });

            this.findInContainer($container, '[data-guard-dog-recovery-codes-display]', '#guard-dog-recovery-codes-display').show();
        },

        // Copy methods
        copyAllRecoveryCodes: function(e) {
            e.preventDefault();
            const $container = this.setActiveContainer(e.currentTarget);
            const codes = [];
            $container.find('.guard-dog-2fa-code-item span').each(function() {
                codes.push($(this).text());
            });
            
            const allCodes = codes.join('\n');
            this.copyToClipboard(allCodes, 'All recovery codes copied to clipboard!');
        },

        copySecretKey: function(e) {
            const $container = this.setActiveContainer(e.currentTarget);
            const secretKey = this.findInContainer($container, '[data-guard-dog-2fa-secret-key]', '#guard-dog-2fa-secret-key').text();
            this.copyToClipboard(secretKey, 'Secret key copied to clipboard!');
        },

        copyIndividualCode: function(e) {
            e.preventDefault();
            this.setActiveContainer(e.currentTarget);
            const button = $(e.currentTarget);
            const code = button.data('code');
            this.copyToClipboard(code, 'Recovery code copied to clipboard!');
        },

        copyToClipboard: function(text, successMessage) {
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(text).then(() => {
                    this.showMessage('success', successMessage);
                }).catch(() => {
                    this.fallbackCopyTextToClipboard(text, successMessage);
                });
            } else {
                this.fallbackCopyTextToClipboard(text, successMessage);
            }
        },

        fallbackCopyTextToClipboard: function(text, successMessage) {
            const textArea = document.createElement('textarea');
            textArea.value = text;
            textArea.style.position = 'fixed';
            textArea.style.left = '-999999px';
            textArea.style.top = '-999999px';
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
            
            try {
                document.execCommand('copy');
                this.showMessage('success', successMessage);
            } catch (err) {
                this.showMessage('error', 'Could not copy to clipboard. Please copy manually.');
            }
            
            document.body.removeChild(textArea);
        },

        // Loading states
        showLoading: function(button) {
            button.prop('disabled', true);
            const originalHtml = button.html();
            button.data('original-html', originalHtml);
            button.html('<span class="loading-spinner">⏳</span> Loading...');
        },

        hideLoading: function(button) {
            button.prop('disabled', false);
            const originalHtml = button.data('original-html');
            if (originalHtml) {
                button.html(originalHtml);
            }
        },

        // Message display
        showMessage: function(type, message) {
            // Debug logging
            console.log('Guard Dog 2FA: showMessage called with:', { type, message });
            
            // Validate parameters
            if (!type || !message) {
                console.error('Guard Dog 2FA: showMessage called with invalid parameters:', { type, message });
                return;
            }
            
            const $container = this.activeContainer && this.activeContainer.length ? this.activeContainer : this.container.first();
            const messageContainer = this.findInContainer($container, '[data-guard-dog-2fa-messages]', '#guard-dog-2fa-messages');
            if (messageContainer.length === 0) {
                console.error('Guard Dog 2FA: Message container not found');
                return;
            }
            
            const messageElement = $('<div class="guard-dog-2fa-notice guard-dog-2fa-' + type + '">' + message + '</div>');
            
            messageContainer.empty().append(messageElement);
            
            // Auto-hide success messages after 5 seconds
            if (type === 'success') {
                setTimeout(() => {
                    messageElement.fadeOut();
                }, 5000);
            }
        },

        // Nonce management
        startNonceChecking: function() {
            // Check nonce validity every 5 minutes
            this.nonceCheckInterval = setInterval(() => {
                this.checkNonceValidity();
            }, 5 * 60 * 1000);
        },

        checkNonceValidity: function() {
            // Check required nonces for app-based 2FA
            const requiredAppNonces = ['generate', 'verify', 'regenerateRecovery', 'disable'];
            let appNoncesValid = true;
            
            requiredAppNonces.forEach(key => {
                if (!this.nonces[key] || this.nonces[key].length < 10) {
                    appNoncesValid = false;
                }
            });
            
            // Check email 2FA nonces if available
            let emailNoncesValid = true;
            if (this.email2faAvailable) {
                const requiredEmailNonces = ['emailEnable', 'emailVerify', 'emailSendCode', 'emailDisable'];
                requiredEmailNonces.forEach(key => {
                    if (!this.nonces[key] || this.nonces[key].length < 10) {
                        emailNoncesValid = false;
                    }
                });
            }
            
            if (!appNoncesValid || !emailNoncesValid) {
                console.log('Guard Dog 2FA: Some nonces appear invalid, refreshing...');
                this.refreshNonces();
            }
        },

        refreshNonces: function() {
            console.log('Guard Dog 2FA: Refreshing nonces...');
            
            // Refresh app-based 2FA nonces
            $.ajax({
                url: this.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'guard_dog_refresh_2fa_nonces',
                    _wpnonce: this.nonces.refresh
                },
                success: (response) => {
                    if (response.success && response.data.nonces) {
                        // Update the app-based nonces
                        Object.assign(this.nonces, response.data.nonces);
                        console.log('Guard Dog 2FA: App-based nonces refreshed successfully');
                        
                        // Show success message if no email 2FA
                        if (!this.email2faAvailable) {
                            this.showMessage('success', 'Security tokens refreshed. Please try again.');
                        }
                    } else {
                        console.error('Guard Dog 2FA: Failed to refresh app-based nonces:', response);
                        this.showMessage('error', 'Could not refresh security tokens. Please refresh the page.');
                    }
                },
                error: (xhr, status, error) => {
                    console.error('Guard Dog 2FA: App-based nonce refresh failed:', {xhr, status, error});
                    this.showMessage('error', 'Could not refresh security tokens. Please refresh the page.');
                }
            });
            
            // Refresh email 2FA nonces if available
            if (this.email2faAvailable) {
                $.ajax({
                    url: this.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'guard_dog_refresh_email_2fa_nonces',
                        _wpnonce: this.nonces.emailDisable || this.nonces.generate
                    },
                    success: (response) => {
                        if (response.success && response.data.nonces) {
                            // Update the email 2FA nonces
                            Object.assign(this.nonces, response.data.nonces);
                            console.log('Guard Dog 2FA: Email 2FA nonces refreshed successfully');
                            this.showMessage('success', 'Security tokens refreshed. Please try again.');
                        } else {
                            console.error('Guard Dog 2FA: Failed to refresh email 2FA nonces:', response);
                            this.showMessage('error', 'Could not refresh security tokens. Please refresh the page.');
                        }
                    },
                    error: (xhr, status, error) => {
                        console.error('Guard Dog 2FA: Email 2FA nonce refresh failed:', {xhr, status, error});
                        this.showMessage('error', 'Could not refresh security tokens. Please refresh the page.');
                    }
                });
            } else {
                // If no email 2FA, just show success message after app-based refresh
                this.showMessage('success', 'Security tokens refreshed. Please try again.');
            }
        },

        // Utility methods
        addRefreshButton: function() {
            const $container = this.activeContainer && this.activeContainer.length ? this.activeContainer : this.container.first();
            const messageContainer = this.findInContainer($container, '[data-guard-dog-2fa-messages]', '#guard-dog-2fa-messages');
            if (messageContainer.find('.guard-dog-2fa-refresh-nonces').length === 0) {
                const refreshButton = $('<button class="guard-dog-2fa-btn guard-dog-2fa-btn-secondary guard-dog-2fa-refresh-nonces guard-dog-2fa-refresh-button">Refresh Security Tokens</button>');
                refreshButton.on('click', () => this.refreshNonces());
                messageContainer.append(refreshButton);
            }
        },

        cleanup: function() {
            if (this.nonceCheckInterval) {
                clearInterval(this.nonceCheckInterval);
                this.nonceCheckInterval = null;
            }
            
            // Abort any pending request
            if (this.currentRequest) {
                this.currentRequest.abort();
                this.currentRequest = null;
            }
        }
    };

    // Initialize when document is ready
    $(document).ready(function() {
        // Only initialize if the 2FA shortcode container exists
        if ($('.guard-dog-2fa-shortcode-container').length > 0) {
            GD2FA.init();
        }
    });

    // Cleanup on page unload
    $(window).on('beforeunload', function() {
        if (GD2FA && typeof GD2FA.cleanup === 'function') {
            GD2FA.cleanup();
        }
    });

})(jQuery);
