/**
 * Guard Dog Login Security Page JavaScript
 * 
 * Handles tab switching, form interactions, and security features.
 *
 * @package GuardDog
 * @since 1.1.0
 */

(function($) {
    'use strict';

    $(document).ready(function() {
        console.log('Guard Dog Login Security page JavaScript loaded');

        // Tab switching functionality
        $('.guard-dog-tab-link').on('click', function(e) {
            e.preventDefault();
            
            const targetTab = $(this).data('tab');
            const storageKey = $(this).data('storage-key') || 'guard_dog_active_tab';
            console.log('Switching to tab:', targetTab, 'with storage key:', storageKey);
            
            // Update active tab
            $('.guard-dog-tab-link').removeClass('active');
            $(this).addClass('active');
            
            // Show target panel
            $('.guard-dog-tab-panel').removeClass('active');
            const $targetPanel = $('#' + targetTab);
            console.log('Target panel found:', $targetPanel.length);
            $targetPanel.addClass('active');
            
            // Store active tab in sessionStorage for persistence
            sessionStorage.setItem(storageKey, targetTab);
        });

        // Initialize active tab - check for stored tab first, then URL hash, then default to first
        $('.guard-dog-tab-link').each(function() {
            const storageKey = $(this).data('storage-key') || 'guard_dog_active_tab';
            let activeTab = sessionStorage.getItem(storageKey);
            
            if (!activeTab && window.location.hash) {
                activeTab = window.location.hash.substring(1);
            }
            
            if (activeTab && $('#' + activeTab).length > 0) {
                // Activate the stored tab
                $('.guard-dog-tab-link').removeClass('active');
                $('.guard-dog-tab-panel').removeClass('active');
                
                $('.guard-dog-tab-link[data-tab="' + activeTab + '"]').addClass('active');
                $('#' + activeTab).addClass('active');
                
                console.log('Restored active tab:', activeTab, 'for storage key:', storageKey);
                return false; // Break the loop since we found and activated a tab
            }
        });
        
        // If no active tab was found, initialize first tab
        if ($('.guard-dog-tab-link.active').length === 0) {
            console.log('No active tab found, initializing first tab');
            $('.guard-dog-tab-link:first').addClass('active');
            $('.guard-dog-tab-panel:first').addClass('active');
        }

        console.log('Found tab links:', $('.guard-dog-tab-link').length);
        console.log('Found tab panels:', $('.guard-dog-tab-panel').length);

        // Custom URL form validation
        $('.guard-dog-settings-form').on('submit', function(e) {
            const $urlInput = $(this).find('input[name="guard_dog_login_slug"]');
            const urlValue = $urlInput.val().trim();
            
            if (urlValue && !/^[a-zA-Z0-9-_]+$/.test(urlValue)) {
                e.preventDefault();
                alert('Custom URL can only contain letters, numbers, hyphens, and underscores.');
                $urlInput.focus();
                return false;
            }
        });

        // Login attempts form validation
        $('.guard-dog-settings-form').on('submit', function(e) {
            const maxRetries = parseInt($(this).find('input[name="guard_dog_lla_max_retries"]').val());
            const lockoutDuration = parseInt($(this).find('input[name="guard_dog_lla_lockout_duration"]').val());
            
            if (maxRetries < 1 || maxRetries > 20) {
                e.preventDefault();
                alert('Maximum retries must be between 1 and 20.');
                return false;
            }
            
            if (lockoutDuration < 1 || lockoutDuration > 1440) {
                e.preventDefault();
                alert('Lockout duration must be between 1 and 1440 minutes.');
                return false;
            }
        });

        // Two-factor authentication form handling
        $('.guard-dog-settings-form').on('submit', function(e) {
            const enabled = $(this).find('input[name="guard_dog_two_factor_enabled"]').is(':checked');
            const enforced = $(this).find('input[name="guard_dog_two_factor_enforced"]').is(':checked');
            const wasEnforced = $(this).find('input[name="guard_dog_two_factor_enforced"]').data('was-checked');
            
            // Debug logging
            if (typeof console !== 'undefined' && console.log) {
                console.log('2FA Form submission:');
                console.log('- Enabled:', enabled);
                console.log('- Enforced:', enforced);
                console.log('- Was enforced before:', wasEnforced);
                console.log('- Should show confirmation:', enforced && !wasEnforced);
                console.log('- Form action:', $(this).attr('action'));
                console.log('- Form method:', $(this).attr('method'));
            }
            
            // Only show confirmation for enforcement, not just enable
            if (enforced && !wasEnforced) {
                if (!confirm('Enforcing 2FA will require all users to set up 2FA within the grace period. Users who do not comply will be locked out. Are you sure you want to proceed?')) {
                    e.preventDefault();
                    return false;
                }
            }
            
            // Store current state for next comparison
            $(this).find('input[name="guard_dog_two_factor_enforced"]').data('was-checked', enforced);
            
            // Debug: Log that form is submitting
            if (typeof console !== 'undefined' && console.log) {
                console.log('2FA Form submitting...');
            }
        });

        // Unlock IP Button functionality
        $('.guard-dog-unlock-ip').on('click', function(e) {
            e.preventDefault();
            const $button = $(this);
            const ipAddress = $button.data('ip');
            
            if (confirm('Are you sure you want to unlock IP address ' + ipAddress + '?')) {
                $button.prop('disabled', true).text('Unlocking...');
                
                // Simulate AJAX call (in real implementation, this would make an AJAX request)
                setTimeout(function() {
                    $button.closest('.lockout-item').fadeOut();
                    $button.prop('disabled', false).text('Unlock');
                }, 1000);
            }
        });

        // Profile page hash handling for 2FA section
        if (window.location.hash === '#guard-dog-2fa' && $('#guard-dog-2fa').length === 0) {
            // We're not on the profile page yet but have the hash, let links work normally
        }
        
        // Add click handler to profile links to set hash for highlighting
        $('.guard-dog-2fa-actions a[href*="profile.php"]').on('click', function() {
            const href = $(this).attr('href');
            if (href.indexOf('#guard-dog-2fa') === -1) {
                $(this).attr('href', href + '#guard-dog-2fa');
            }
        });

        // Toggle functionality for collapsible sections
        $('.guard-dog-toggle-section').on('click', function(e) {
            e.preventDefault();
            const $section = $(this).closest('.guard-dog-form-section');
            const $content = $section.find('.guard-dog-toggle-content');
            
            $content.slideToggle();
            $(this).toggleClass('collapsed');
        });

        // Real-time URL preview for custom login URL
        $('input[name="guard_dog_login_slug"]').on('input', function() {
            const urlValue = $(this).val().trim();
            const $preview = $('.guard-dog-url-preview');
            
            if (urlValue) {
                const previewUrl = window.location.origin + '/' + urlValue;
                $preview.text(previewUrl).show();
            } else {
                $preview.hide();
            }
        });

        // Initialize URL preview on page load
        $('input[name="guard_dog_login_slug"]').trigger('input');

        // Form field dependencies for Login Attempts
        $('input[name="guard_dog_lla_enabled"]').on('change', function() {
            const enabled = $(this).is(':checked');
            const $dependentFields = $(this).closest('table').find('.guard-dog-dependent-field');
            
            if (enabled) {
                $dependentFields.removeClass('disabled');
            } else {
                $dependentFields.addClass('disabled');
            }
        });

        // Form field dependencies for 2FA
        $('input[name="guard_dog_two_factor_enabled"]').on('change', function() {
            const enabled = $(this).is(':checked');
            const $dependentFields = $(this).closest('table').find('.guard-dog-dependent-field');
            
            if (enabled) {
                $dependentFields.removeClass('disabled');
            } else {
                $dependentFields.addClass('disabled');
            }
        });

        // Initialize form field dependencies
        $('input[name="guard_dog_lla_enabled"]').trigger('change');
        $('input[name="guard_dog_two_factor_enabled"]').trigger('change');

        // Security status indicators
        function updateSecurityStatus() {
            const customUrlEnabled = $('input[name="guard_dog_login_slug"]').val().trim() !== '';
            const attemptsEnabled = $('input[name="guard_dog_lla_enabled"]').is(':checked');
            const tfaEnabled = $('input[name="guard_dog_two_factor_enabled"]').is(':checked');
            
            let securityLevel = 0;
            if (customUrlEnabled) securityLevel++;
            if (attemptsEnabled) securityLevel++;
            if (tfaEnabled) securityLevel++;
            
            const $statusIndicator = $('.guard-dog-security-level');
            $statusIndicator.removeClass('low medium high').addClass(
                securityLevel === 0 ? 'low' : 
                securityLevel === 1 ? 'medium' : 'high'
            );
        }

        // Update security status on form changes
        $('.guard-dog-login-security-page input, .guard-dog-login-security-page select').on('change', updateSecurityStatus);
        
        // Initialize security status
        updateSecurityStatus();

    });

})(jQuery);