/**
 * VMPFence Login Security - 2FA Management
 * 
 * Handles UI interactions for Two-Factor Authentication setup and management
 * 
 * @package VMPFence
 * @since 2.1.0
 */

(function($) {
    'use strict';

    // State management
    let setupData = {
        qrCode: null,
        secret: null,
        backupCodes: [],
        isSetupComplete: false
    };

    /**
     * Initialize 2FA management
     */
    function init() {
        // Toast notification system auto-initializes from toast-notifications.js
        // Removed manual init to prevent duplicate initialization and double toasts
        
        // Check if in forced setup mode
        const urlParams = new URLSearchParams(window.location.search);
        const isForceSetup = urlParams.get('force_setup') === '1';
        
        if (isForceSetup) {
            initForcedSetupMode();
        }
        
        // Tab switching
        initTabs();
        
        // Button handlers
        $('#vmpfence-disable-2fa').on('click', handleDisableClick);
        $('#vmpfence-regenerate-codes').on('click', handleRegenerateClick);
        $('#vmpfence-cancel-setup').on('click', handleCancelSetup);
        $('#vmpfence-activate-2fa').on('click', handleActivate2FA);
        
        // Code actions
        $('#vmpfence-copy-secret').on('click', handleCopySecret);
        $('#vmpfence-print-codes').on('click', handlePrintCodes);
        $('#vmpfence-download-codes, #vmpfence-setup-download-codes').on('click', handleDownloadCodes);
        
        // Code input auto-focus and validation
        $('#vmpfence-verify-code').on('input', function() {
            this.value = this.value.replace(/\D/g, '').substr(0, 6);
        });
        
        // Auto-load 2FA setup if container exists and has auto-load attribute
        // This only happens for premium users when 2FA is disabled
        if ($('#vmpfence-2fa-setup-container').length && $('#vmpfence-2fa-setup-container').data('auto-load')) {
            startSetup();
        }
    }

    /**
     * Initialize tab switching functionality
     */
    function initTabs() {
        $('.vmpfence-tabs-nav button').on('click', function(e) {
            e.preventDefault();
            
            const targetTab = $(this).data('tab');
            const urlParams = new URLSearchParams(window.location.search);
            const isForceSetup = urlParams.get('force_setup') === '1';
            
            // Block navigation to Settings tab during forced setup
            if (isForceSetup && targetTab === 'settings') {
                showForcedSetupModal();
                return;
            }
            
            // Update tab buttons
            $('.vmpfence-tabs-nav button').removeClass('active');
            $(this).addClass('active');
            
            // Update tab content
            $('.vmpfence-tab-content').removeClass('active');
            $('#' + targetTab).addClass('active');
            
            // Update URL without page reload
            const url = new URL(window.location);
            url.searchParams.set('tab', targetTab);
            window.history.pushState({}, '', url);
        });
    }

    /**
     * Start 2FA setup process
     */
    function startSetup() {
        showLoading('Generating QR code...');

        $.ajax({
            url: $('#vmpfence-ajax-url').val(),
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'vmpfence_setup_2fa',
                nonce: $('#vmpfence-nonce').val()
            },
            success: function(response) {
                hideLoading();
                
                if (response.success && response.data) {
                    // API returns qr_code_url, not qr_code
                    setupData.qrCode = response.data.qr_code_url || response.data.qr_code;
                    setupData.secret = response.data.secret;
                    setupData.backupCodes = response.data.backup_codes || [];
                    
                    // Show single-page setup container
                    $('#vmpfence-2fa-setup-container').show();
                    
                    // Display QR code (safely escape URL to prevent XSS)
                    if (setupData.qrCode) {
                        $('#vmpfence-qr-code').empty().append(
                            $('<img>').attr({'src': setupData.qrCode, 'alt': 'QR Code'})
                        );
                    }
                    
                    // Display secret key
                    if (setupData.secret) {
                        $('#vmpfence-secret-display').text(setupData.secret);
                    }
                    
                    // Display backup codes immediately
                    if (setupData.backupCodes && setupData.backupCodes.length > 0) {
                        displayBackupCodes(setupData.backupCodes, '#vmpfence-backup-codes-list');
                    }
                    
                    // Focus on verification input
                    $('#vmpfence-verify-code').focus();
                } else {
                    showError('Failed to start setup: ' + (response.data && response.data.message ? response.data.message : 'Unknown error'));
                }
            },
            error: function(xhr) {
                hideLoading();
                let message = 'Failed to connect to API server';
                if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                    message = xhr.responseJSON.data.message;
                }
                showError(message);
            }
        });
    }

    /**
     * Handle Cancel Setup button
     */
    function handleCancelSetup(e) {
        e.preventDefault();
        
        VMPFenceNotifications.showConfirmModal({
            title: 'Cancel 2FA Setup',
            message: 'Are you sure you want to cancel 2FA setup?<br><br>The page will reload and any progress will be lost.',
            confirmText: 'Yes, Cancel Setup',
            cancelText: 'No, Continue',
            type: 'warning'
        }).then(function(confirmed) {
            if (!confirmed) return;
            // Just reload the page to reset everything
            location.reload();
        });
    }

    /**
     * Handle Activate 2FA button
     */
    function handleActivate2FA(e) {
        e.preventDefault();
        
        const code = $('#vmpfence-verify-code').val().trim();
        
        if (!code || code.length !== 6) {
            showError('Please enter a 6-digit code');
            return;
        }
        
        showLoading('Verifying code...');
        
        // Step 1: Verify the code
        $.ajax({
            url: $('#vmpfence-ajax-url').val(),
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'vmpfence_verify_2fa_setup',
                nonce: $('#vmpfence-nonce').val(),
                code: code
            },
            success: function(response) {
                // API returns 'success' not 'valid'
                if (response.success && response.data.success) {
                    hideLoading();
                    
                    // Mark setup as complete to allow navigation
                    setupData.isSetupComplete = true;
                    
                    // Show success message
                    let successHtml = '<div class="vmpfence-notice vmpfence-notice-success" style="margin: 20px 0; padding: 20px; background: #edfaef; border-left: 4px solid #00a32a; border-radius: 12px;">';
                    successHtml += '<h3 style="margin-top: 0; color: #00a32a;">✓ Two-Factor Authentication Activated!</h3>';
                    successHtml += '<p style="color: #1d2327;">Your account is now protected with 2FA. Make sure you have saved your backup codes.</p>';
                    successHtml += '<p style="margin-bottom: 0;"><strong>Page will reload in 3 seconds...</strong></p>';
                    successHtml += '</div>';
                    
                    // Hide setup, disabled status, and show success
                    $('#vmpfence-2fa-setup-container').hide();
                    $('.vmpfence-2fa-disabled').hide();
                    $('.vmpfence-card-body').prepend(successHtml);
                    
                    // Scroll to top
                    $('html, body').animate({ scrollTop: 0 }, 300);
                    
                    // Reload page
                    setTimeout(function() {
                        location.reload();
                    }, 3000);
                } else {
                    hideLoading();
                    showError('Invalid code. Please check your authenticator app and try again.');
                }
            },
            error: function(xhr) {
                hideLoading();
                let message = 'Verification failed';
                if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                    message = xhr.responseJSON.data.message;
                }
                showError(message);
            }
        });
    }



    /**
     * Handle Disable 2FA button
     */
    function handleDisableClick(e) {
        e.preventDefault();
        
        VMPFenceNotifications.showConfirmModal({
            title: 'Disable Two-Factor Authentication',
            message: 'Are you sure you want to disable Two-Factor Authentication?<br><br><strong>Warning:</strong> This will make your account less secure.',
            confirmText: 'Yes, Disable 2FA',
            cancelText: 'Cancel',
            type: 'warning'
        }).then(function(confirmed) {
            if (!confirmed) return;
            
            showLoading('Disabling 2FA...');
            
            $.ajax({
            url: $('#vmpfence-ajax-url').val(),
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'vmpfence_disable_2fa',
                nonce: $('#vmpfence-nonce').val()
            },
            success: function(response) {
                hideLoading();
                
                if (response.success) {
                    location.reload();
                } else {
                    showError('Failed to disable 2FA: ' + (response.data && response.data.message ? response.data.message : 'Unknown error'));
                }
            },
            error: function(xhr) {
                hideLoading();
                showError('Failed to disable 2FA. Please try again.');
            }
            });
        });
    }

    /**
     * Handle Regenerate Backup Codes button
     */
    function handleRegenerateClick(e) {
        e.preventDefault();
        
        VMPFenceNotifications.showConfirmModal({
            title: 'Regenerate Backup Codes',
            message: 'Are you sure you want to regenerate backup codes?<br><br><strong>Warning:</strong> Your old codes will no longer work.',
            confirmText: 'Yes, Regenerate',
            cancelText: 'Cancel',
            type: 'warning'
        }).then(function(confirmed) {
            if (!confirmed) return;
            
            showLoading('Generating new backup codes...');
            
            $.ajax({
            url: $('#vmpfence-ajax-url').val(),
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'vmpfence_regenerate_backup_codes',
                nonce: $('#vmpfence-nonce').val()
            },
            success: function(response) {
                hideLoading();
                
                if (response.success && response.data.backup_codes) {
                    displayBackupCodes(response.data.backup_codes, '#vmpfence-codes-list');
                    $('#vmpfence-backup-codes-container').slideDown();
                    showSuccess('New backup codes generated successfully!');
                } else {
                    showError('Failed to generate backup codes: ' + (response.data && response.data.message ? response.data.message : 'Unknown error'));
                }
            },
            error: function(xhr) {
                hideLoading();
                showError('Failed to generate backup codes. Please try again.');
            }
            });
        });
    }

    /**
     * Handle Copy Secret button
     */
    function handleCopySecret(e) {
        e.preventDefault();
        
        const secret = $('#vmpfence-secret-display').text();
        
        // Modern clipboard API
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(secret).then(function() {
                showSuccess('Secret key copied to clipboard!');
            }, function() {
                fallbackCopyToClipboard(secret);
            });
        } else {
            fallbackCopyToClipboard(secret);
        }
    }

    /**
     * Fallback copy to clipboard for older browsers
     */
    function fallbackCopyToClipboard(text) {
        const textarea = document.createElement('textarea');
        textarea.value = text;
        textarea.style.position = 'fixed';
        textarea.style.opacity = '0';
        document.body.appendChild(textarea);
        textarea.select();
        
        try {
            document.execCommand('copy');
            showSuccess('Secret key copied to clipboard!');
        } catch (err) {
            showError('Failed to copy. Please select and copy manually.');
        }
        
        document.body.removeChild(textarea);
    }

    /**
     * Handle Print Codes button
     */
    function handlePrintCodes(e) {
        e.preventDefault();
        
        const codes = setupData.backupCodes.length ? setupData.backupCodes : getDisplayedCodes();
        
        if (!codes.length) {
            showError('No backup codes available to print');
            return;
        }
        
        const printWindow = window.open('', '', 'height=600,width=800');
        printWindow.document.write('<html><head><title>VMPFence 2FA Backup Codes</title>');
        printWindow.document.write('<style>body{font-family:Arial,sans-serif;padding:40px;}h1{color:#333;}ul{list-style:none;padding:0;}li{margin:10px 0;font-size:18px;font-family:monospace;}</style>');
        printWindow.document.write('</head><body>');
        printWindow.document.write('<h1>VMPFence Two-Factor Authentication Backup Codes</h1>');
        printWindow.document.write('<p>Save these codes in a secure location. Each code can only be used once.</p>');
        printWindow.document.write('<ul>');
        
        codes.forEach(function(code) {
            printWindow.document.write('<li>' + code + '</li>');
        });
        
        printWindow.document.write('</ul>');
        printWindow.document.write('<p><small>Generated: ' + new Date().toLocaleString() + '</small></p>');
        printWindow.document.write('</body></html>');
        printWindow.document.close();
        printWindow.print();
    }

    /**
     * Handle Download Codes button
     */
    function handleDownloadCodes(e) {
        e.preventDefault();
        
        const codes = setupData.backupCodes.length ? setupData.backupCodes : getDisplayedCodes();
        
        if (!codes.length) {
            showError('No backup codes available to download');
            return;
        }
        
        const content = 'VMPFence Two-Factor Authentication Backup Codes\n\n' +
                       'Save these codes in a secure location. Each code can only be used once.\n\n' +
                       codes.join('\n') + '\n\n' +
                       'Generated: ' + new Date().toLocaleString();
        
        const blob = new Blob([content], { type: 'text/plain' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'vmpfence-backup-codes.txt';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
        
        showSuccess('Backup codes downloaded!');
    }

    /**
     * Display backup codes in the specified container
     */
    function displayBackupCodes(codes, containerSelector) {
        const $container = $(containerSelector);
        $container.empty();
        
        if (!codes || !codes.length) {
            $container.html('<p>No backup codes available</p>');
            return;
        }
        
        codes.forEach(function(code) {
            // Safely escape code to prevent XSS
            const $codeItem = $('<div>').addClass('vmpfence-code-item');
            const $codeElement = $('<code>').text(code);
            $codeItem.append($codeElement);
            $container.append($codeItem);
        });
        
        setupData.backupCodes = codes;
    }

    /**
     * Get currently displayed backup codes
     */
    function getDisplayedCodes() {
        const codes = [];
        $('.vmpfence-codes-grid code').each(function() {
            codes.push($(this).text().trim());
        });
        return codes;
    }

    /**
     * Reset setup state
     */
    function resetSetupData() {
        setupData = {
            qrCode: null,
            secret: null,
            backupCodes: []
        };
        $('#vmpfence-verify-code').val('');
        $('#vmpfence-qr-code').empty();
        $('#vmpfence-secret-display').text('');
        $('#vmpfence-backup-codes-list').empty();
    }

    /**
     * Show loading overlay
     */
    function showLoading(message) {
        $('#vmpfence-loading-message').text(message || 'Processing...');
        $('#vmpfence-loading-overlay').fadeIn(200);
    }

    /**
     * Hide loading overlay
     */
    function hideLoading() {
        $('#vmpfence-loading-overlay').fadeOut(200);
    }

    /**
     * Show error message
     */
    function showError(message) {
        VMPFenceNotifications.showError(message, 6000);
    }

    /**
     * Show success message
     */
    function showSuccess(message) {
        VMPFenceNotifications.showSuccess(message, 4000);
    }

    /**
     * Initialize forced setup mode protections
     */
    function initForcedSetupMode() {
        // Prevent page navigation
        $(window).on('beforeunload', function(e) {
            const urlParams = new URLSearchParams(window.location.search);
            const isForceSetup = urlParams.get('force_setup') === '1';
            
            if (isForceSetup && !setupData.isSetupComplete) {
                const message = 'You must complete Two-Factor Authentication setup before accessing other areas.';
                e.returnValue = message;
                return message;
            }
        });
        
        // Add visual indicator to Settings tab
        $('.nav-tab[data-tab="settings"]').css({
            'opacity': '0.5',
            'cursor': 'not-allowed'
        }).attr('title', 'Complete 2FA setup to access settings');
        
        // Auto-show 2FA tab
        $('.nav-tab[data-tab="two-factor"]').addClass('nav-tab-active');
        $('#two-factor').show();
        $('#settings').hide();
    }

    /**
     * Show modal explaining forced setup requirement
     */
    function showForcedSetupModal() {
        if ($('#vmpfence-forced-setup-modal').length) {
            $('#vmpfence-forced-setup-modal').show();
            return;
        }
        
        const modal = $('<div>', {
            id: 'vmpfence-forced-setup-modal',
            css: {
                'position': 'fixed',
                'top': '0',
                'left': '0',
                'width': '100%',
                'height': '100%',
                'background': 'rgba(0, 0, 0, 0.7)',
                'z-index': '999999',
                'display': 'flex',
                'align-items': 'center',
                'justify-content': 'center'
            }
        });
        
        const modalContent = $('<div>', {
            css: {
                'background': '#fff',
                'padding': '30px',
                'border-radius': '8px',
                'max-width': '500px',
                'box-shadow': '0 4px 20px rgba(0,0,0,0.3)'
            }
        });
        
        modalContent.html(`
            <h2 style="margin-top: 0; color: #d63638;">
                <span class="dashicons dashicons-lock" style="font-size: 28px; vertical-align: middle;"></span>
                Two-Factor Authentication Required
            </h2>
            <p style="font-size: 15px; line-height: 1.6;">
                Your account requires Two-Factor Authentication to be enabled. 
                You must complete the 2FA setup before you can access other settings or admin areas.
            </p>
            <p style="font-size: 14px; color: #666; margin-bottom: 20px;">
                This is a security requirement based on your user role.
            </p>
            <button class="button button-primary button-large" id="vmpfence-modal-ok" style="width: 100%;">
                I Understand - Continue Setup
            </button>
        `);
        
        modal.append(modalContent);
        $('body').append(modal);
        
        // Close modal on button click
        $('#vmpfence-modal-ok').on('click', function() {
            modal.fadeOut(200, function() {
                $(this).remove();
            });
        });
        
        // Close on outside click
        modal.on('click', function(e) {
            if (e.target === this) {
                modal.fadeOut(200, function() {
                    $(this).remove();
                });
            }
        });
    }

    /**
     * Initialize forced setup mode protections
     */
    function initForcedSetupMode() {
        // Prevent page navigation
        $(window).on('beforeunload', function(e) {
            const urlParams = new URLSearchParams(window.location.search);
            const isForceSetup = urlParams.get('force_setup') === '1';
            
            if (isForceSetup && !setupData.isSetupComplete) {
                const message = 'You must complete Two-Factor Authentication setup before accessing other areas.';
                e.returnValue = message;
                return message;
            }
        });
        
        // Add visual indicator to Settings tab button
        const settingsTab = $('.vmpfence-tabs-nav button[data-tab="settings"]');
        if (settingsTab.length > 0) {
            settingsTab.css({
                'opacity': '0.5',
                'cursor': 'not-allowed'
            }).attr('title', 'Complete 2FA setup to access settings');
        }
        
        // Auto-show 2FA tab
        $('.vmpfence-tabs-nav button[data-tab="two-factor-authentication"]').addClass('active');
        $('#vmpfence-2fa-tab').addClass('active');
        $('#vmpfence-settings-tab').removeClass('active');
    }

    /**
     * Show modal explaining forced setup requirement
     */
    function showForcedSetupModal() {
        if ($('#vmpfence-forced-setup-modal').length) {
            $('#vmpfence-forced-setup-modal').show();
            return;
        }
        
        const modal = $('<div>', {
            id: 'vmpfence-forced-setup-modal',
            css: {
                'position': 'fixed',
                'top': '0',
                'left': '0',
                'width': '100%',
                'height': '100%',
                'background': 'rgba(0, 0, 0, 0.7)',
                'z-index': '999999',
                'display': 'flex',
                'align-items': 'center',
                'justify-content': 'center'
            }
        });
        
        const modalContent = $('<div>', {
            css: {
                'background': '#fff',
                'padding': '30px',
                'border-radius': '8px',
                'max-width': '500px',
                'box-shadow': '0 4px 20px rgba(0,0,0,0.3)'
            }
        });
        
        modalContent.html(`
            <h2 style="margin-top: 0; color: #d63638;">
                <span class="dashicons dashicons-lock" style="font-size: 28px; vertical-align: middle;"></span>
                Two-Factor Authentication Required
            </h2>
            <p style="font-size: 15px; line-height: 1.6;">
                Your account requires Two-Factor Authentication to be enabled. 
                You must complete the 2FA setup before you can access other settings or admin areas.
            </p>
            <p style="font-size: 14px; color: #666; margin-bottom: 20px;">
                This is a security requirement based on your user role.
            </p>
            <button class="button button-primary button-large" id="vmpfence-modal-ok" style="width: 100%;">
                I Understand - Continue Setup
            </button>
        `);
        
        modal.append(modalContent);
        $('body').append(modal);
        
        // Close modal on button click
        $('#vmpfence-modal-ok').on('click', function() {
            modal.fadeOut(200, function() {
                $(this).remove();
            });
        });
        
        // Close on outside click
        modal.on('click', function(e) {
            if (e.target === this) {
                modal.fadeOut(200, function() {
                    $(this).remove();
                });
            }
        });
    }

    // Initialize on document ready
    $(document).ready(init);

})(jQuery);
