/**
 * Guard Dog 2FA Setup Script for User Profile
 */
jQuery(document).ready(function($) {

    const setupSection = $('#guard-dog-2fa-setup-section');
    const enableButton = $('#guard-dog-enable-2fa-button');
    const qrCodeDiv = $('#guard-dog-2fa-qr-code');
    const secretKeySpan = $('#guard-dog-2fa-secret-key');
    const verifyCodeInput = $('#guard-dog-2fa-verify-code');
    const verifyButton = $('#guard-dog-verify-2fa-button');
    const feedbackDiv = $('#guard-dog-2fa-setup-feedback');

    // Ensure setup section is hidden by default
    setupSection.hide();

    // Handle "Enable 2FA" button click
    enableButton.on('click', function() {
        const button = $(this);
        const userId = button.data('user-id');
        const nonce = button.data('nonce');

        // Basic check
        if (!userId || !nonce) {
            feedbackDiv.text('Error: Missing user data.').addClass('notice notice-error').show();
            return;
        }

        // Disable button, show loading (optional)
        button.prop('disabled', true).text('Generating...');
        feedbackDiv.removeClass('notice notice-error notice-success').hide();
        qrCodeDiv.empty(); // Clear previous QR if any
        secretKeySpan.empty();

        $.ajax({
            url: guard_dog_profile_2fa.ajax_url, // WordPress AJAX URL (passed via wp_localize_script)
            type: 'POST',
            data: {
                action: 'guard_dog_generate_2fa_secret',
                nonce: nonce,
                user_id: userId
            },
            success: function(response) {
                if (response.success) {
                    // Populate the fields
                    secretKeySpan.text(response.data.secret);
                    // Generate QR code image - using Google Charts API URL provided by library
                    // Note: Requires internet connection for the user viewing the profile.
                    // Consider using a JS QR library for offline generation later.
                    qrCodeDiv.html('<img src="' + response.data.qr_data_uri + '" alt="QR Code" />');

                    // Show the setup section, hide the enable button
                    setupSection.slideDown();
                    enableButton.hide(); // Hide after success
                    feedbackDiv.empty().hide();

                } else {
                    // Show error message
                    feedbackDiv.text('Error: ' + (response.data.message || 'Could not generate secret.')).addClass('notice notice-error').show();
                    button.prop('disabled', false).text('Enable 2FA'); // Re-enable button on failure
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error("Guard Dog AJAX Error:", textStatus, errorThrown);
                feedbackDiv.text('AJAX Error: ' + textStatus).addClass('notice notice-error').show();
                button.prop('disabled', false).text('Enable 2FA'); // Re-enable button on failure
            }
        });
    });

    // Handle "Verify & Enable" button click
    verifyButton.on('click', function() {
        const button = $(this);
        const code = verifyCodeInput.val().trim();
        const userId = enableButton.data('user-id'); // Get user ID from the (now hidden) enable button
        // Get nonce from the hidden field created by wp_nonce_field()
        const nonce = $('#guard_dog_verify_2fa_nonce').val(); // Nonce field created by PHP

        if (!userId || !nonce) {
            feedbackDiv.text('Error: Missing user/security data.').removeClass('notice-success').addClass('notice notice-error').show();
            return;
        }
        if (!code || code.length !== 6 || !/^[0-9]+$/.test(code)) {
            feedbackDiv.text('Error: Please enter a valid 6-digit code.').removeClass('notice-success').addClass('notice notice-error').show();
            return;
        }

        button.prop('disabled', true).text('Verifying...');
        feedbackDiv.removeClass('notice notice-error notice-success').hide();

        $.ajax({
            url: guard_dog_profile_2fa.ajax_url,
            type: 'POST',
            data: {
                action: 'guard_dog_verify_2fa_setup',
                nonce: nonce,
                user_id: userId,
                code: code
            },
            success: function(response) {
                if (response.success) {
                    feedbackDiv.text(response.data.message).removeClass('notice-error').addClass('notice notice-success').show();
                    setupSection.slideUp();
                    setTimeout(function() {
                        window.location.reload();
                    }, 3000); // Reload after 3 seconds

                } else {
                    feedbackDiv.text('Error: ' + (response.data.message || 'Verification failed.')).removeClass('notice-success').addClass('notice notice-error').show();
                    button.prop('disabled', false).text('Verify & Enable');
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error("Guard Dog AJAX Error:", textStatus, errorThrown);
                feedbackDiv.text('AJAX Error: ' + textStatus).removeClass('notice-success').addClass('notice notice-error').show();
                button.prop('disabled', false).text('Verify & Enable');
            }
        });
    });

    // Handle "Disable 2FA" button click
    $('#guard-dog-disable-2fa-profile').on('click', function() {
        const button = $(this);
        const userId = button.data('user-id');
        const nonce = button.data('nonce');

        if (!userId || !nonce) {
            alert('Error: Missing user data.');
            return;
        }

        if (!confirm('Are you sure you want to disable two-factor authentication? This will remove all security codes and make your account less secure.')) {
            return;
        }

        button.prop('disabled', true).text('Disabling...');

        // Debug logging
        console.log('Guard Dog Profile 2FA: Disable request:', {
            userId: userId,
            nonce: nonce,
            ajaxUrl: guard_dog_profile_2fa.ajax_url
        });

        $.ajax({
            url: guard_dog_profile_2fa.ajax_url,
            type: 'POST',
            data: {
                action: 'guard_dog_disable_2fa',
                user_id: userId,
                _wpnonce: nonce
            },
            success: function(response) {
                console.log('Guard Dog Profile 2FA: Disable response:', response);
                button.prop('disabled', false).text('Disable App 2FA');
                
                if (response.success) {
                    alert(response.data.message || 'Two-Factor Authentication has been disabled.');
                    window.location.reload();
                } else {
                    alert('Error: ' + (response.data.message || 'Could not disable two-factor authentication.'));
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error("Guard Dog Profile 2FA: Disable error:", {jqXHR, textStatus, errorThrown});
                button.prop('disabled', false).text('Disable App 2FA');
                alert('Network error. Please try again.');
            }
        });
    });

    // Handle "Generate New Recovery Codes" button click
    $('#guard-dog-regenerate-recovery-codes-profile').on('click', function() {
        const button = $(this);
        const userId = button.data('user-id');
        const nonce = button.data('nonce');

        if (!userId || !nonce) {
            alert('Error: Missing user data.');
            return;
        }

        if (!confirm('Are you sure you want to regenerate recovery codes? This will invalidate all existing codes.')) {
            return;
        }

        button.prop('disabled', true).text('Generating...');

        $.ajax({
            url: guard_dog_profile_2fa.ajax_url,
            type: 'POST',
            data: {
                action: 'guard_dog_regenerate_recovery_codes',
                user_id: userId,
                nonce: nonce
            },
            success: function(response) {
                button.prop('disabled', false).text('Generate New Recovery Codes');
                
                if (response.success) {
                    // Display the recovery codes
                    displayRecoveryCodes(response.data.codes);
                    $('#guard-dog-recovery-codes-display-profile').show();
                    
                    // Show success message
                    if (response.data.message) {
                        alert(response.data.message);
                    }
                } else {
                    alert('Error: ' + (response.data.message || 'Could not regenerate recovery codes.'));
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error("Guard Dog AJAX Error:", textStatus, errorThrown);
                button.prop('disabled', false).text('Generate New Recovery Codes');
                alert('Network error. Please try again.');
            }
        });
    });

    // Handle "Copy All Codes" button click
    $('#guard-dog-copy-recovery-codes-profile').on('click', function() {
        const codes = [];
        $('#guard-dog-recovery-codes-list-profile .guard-dog-recovery-code').each(function() {
            codes.push($(this).text());
        });
        
        const allCodes = codes.join('\n');
        copyToClipboard(allCodes);
        alert('All recovery codes copied to clipboard!');
    });

    // Handle "Print Codes" button click
    $('#guard-dog-print-recovery-codes-profile').on('click', function() {
        const codes = [];
        $('#guard-dog-recovery-codes-list-profile .guard-dog-recovery-code').each(function() {
            codes.push($(this).text());
        });
        
        const allCodes = codes.join('\n');
        printRecoveryCodes(allCodes);
    });

    // Helper function to display recovery codes
    function displayRecoveryCodes(codes) {
        const container = $('#guard-dog-recovery-codes-list-profile');
        container.empty();

        codes.forEach(function(code) {
            const codeElement = $('<div class="guard-dog-recovery-code">' + code + '</div>');
            container.append(codeElement);
        });
    }

    // Helper function to copy text to clipboard
    function copyToClipboard(text) {
        if (navigator.clipboard && window.isSecureContext) {
            // Use modern clipboard API
            navigator.clipboard.writeText(text);
        } else {
            // Fallback for older browsers
            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');
            } catch (err) {
                console.error('Failed to copy text: ', err);
            }
            document.body.removeChild(textArea);
        }
    }

    // Helper function to print recovery codes
    function printRecoveryCodes(codes) {
        const printWindow = window.open('', '_blank');
        const cssUrl = guard_dog_profile_2fa.assetsUrl + 'css/guard-dog-recovery-codes-print.css';
        const printContent = `
            <!DOCTYPE html>
            <html>
            <head>
                <title>Guard Dog Recovery Codes</title>
                <link rel="stylesheet" href="${cssUrl}" type="text/css" media="all">
            </head>
            <body>
                <div class="header">
                    <h1>Guard Dog Recovery Codes</h1>
                    <p>Generated on: ${new Date().toLocaleString()}</p>
                </div>
                
                <div class="warning">
                    <strong>Important:</strong> Store these codes securely. Each code can only be used once.
                </div>
                
                <div class="codes">
                    ${codes.split('\n').map(code => `<div class="code">${code}</div>`).join('')}
                </div>
                
                <div class="no-print guard-dog-print-controls">
                    <button onclick="window.print()">Print</button>
                    <button onclick="window.close()">Close</button>
                </div>
            </body>
            </html>
        `;
        
        printWindow.document.write(printContent);
        printWindow.document.close();
    }

});