/**
 * Settings Page Interactive Behaviors
 * Handles password toggles, strength meter, interest tags, and accessibility
 */

(function($) {
    'use strict';

    /**
     * Password Toggle Visibility
     */
    function initPasswordToggle() {
        $('.btn-toggle-password').on('click', function(e) {
            e.preventDefault();
            const $btn = $(this);
            const $input = $btn.closest('.input-group-modern').find('.form-control-modern');
            const $icon = $btn.find('i');
            
            if ($input.attr('type') === 'password') {
                $input.attr('type', 'text');
                $icon.removeClass('icon_lock_alt').addClass('icon_lock-open_alt');
                $btn.attr('aria-label', 'Hide password');
            } else {
                $input.attr('type', 'password');
                $icon.removeClass('icon_lock-open_alt').addClass('icon_lock_alt');
                $btn.attr('aria-label', 'Show password');
            }
        });
    }

    /**
     * Password Strength Meter
     */
    function initPasswordStrength() {
        const $newPasswordInput = $('#new-password');
        
        if ($newPasswordInput.length) {
            $newPasswordInput.on('input', function() {
                const password = $(this).val();
                const strength = calculatePasswordStrength(password);
                updateStrengthMeter(strength);
            });
        }
    }

    /**
     * Calculate password strength (0-100)
     */
    function calculatePasswordStrength(password) {
        if (!password) return 0;
        
        let strength = 0;
        
        // Length check
        if (password.length >= 8) strength += 25;
        if (password.length >= 12) strength += 15;
        
        // Character variety checks
        if (/[a-z]/.test(password)) strength += 15; // lowercase
        if (/[A-Z]/.test(password)) strength += 15; // uppercase
        if (/[0-9]/.test(password)) strength += 15; // numbers
        if (/[^a-zA-Z0-9]/.test(password)) strength += 15; // special chars
        
        return Math.min(strength, 100);
    }

    /**
     * Update the strength meter UI
     */
    function updateStrengthMeter(strength) {
        const $strengthBar = $('.strength-bar');
        const $strengthText = $('.strength-text');
        
        if (!$strengthBar.length) return;
        
        $strengthBar.css('width', strength + '%');
        
        let text = 'Weak';
        let color = '#ff4757';
        
        if (strength >= 75) {
            text = 'Strong';
            color = '#4caf50';
        } else if (strength >= 50) {
            text = 'Medium';
            color = '#ffa726';
        }
        
        $strengthText.text(text).css('color', color);
    }

    /**
     * Interest Tags Selection
     */
    function initInterestTags() {
        $('.interest-tag').on('click', function(e) {
            e.preventDefault();
            $(this).toggleClass('active');
            
            // Update hidden input or aria-pressed for accessibility
            const isActive = $(this).hasClass('active');
            $(this).attr('aria-pressed', isActive);
        });
        
        // Keyboard navigation for interest tags
        $('.interest-tag').on('keypress', function(e) {
            if (e.which === 13 || e.which === 32) { // Enter or Space
                e.preventDefault();
                $(this).click();
            }
        });
    }

    /**
     * Toggle Switch Accessibility
     */
    function initToggleSwitches() {
        $('.toggle-input').on('change', function() {
            const isChecked = $(this).is(':checked');
            const $label = $(this).next('.toggle-label');
            
            // Update ARIA attributes
            $(this).attr('aria-checked', isChecked);
            
            // Optional: Trigger custom events for specific settings
            const settingId = $(this).attr('id');
            if (settingId) {
                $(document).trigger('setting-changed', {
                    setting: settingId,
                    enabled: isChecked
                });
            }
        });
    }

    /**
     * Form Validation Enhancement
     */
    function initFormValidation() {
        $('.settings-form').on('submit', function(e) {
            const $form = $(this);
            let isValid = true;
            
            // Clear previous errors
            $form.find('.is-invalid').removeClass('is-invalid');
            $form.find('.error-message').remove();
            
            // Validate required fields
            $form.find('[required]').each(function() {
                if (!$(this).val()) {
                    isValid = false;
                    $(this).addClass('is-invalid');
                    $(this).after('<div class="error-message text-danger mt-1" style="font-size: 0.85rem;">This field is required</div>');
                }
            });
            
            // Validate email
            const $email = $form.find('input[type="email"]');
            if ($email.length && $email.val()) {
                const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailPattern.test($email.val())) {
                    isValid = false;
                    $email.addClass('is-invalid');
                    $email.after('<div class="error-message text-danger mt-1" style="font-size: 0.85rem;">Please enter a valid email address</div>');
                }
            }
            
            // Validate password confirmation
            const $newPassword = $('#new-password');
            const $confirmPassword = $('#confirm-password');
            
            if ($newPassword.length && $confirmPassword.length) {
                if ($newPassword.val() !== $confirmPassword.val()) {
                    isValid = false;
                    $confirmPassword.addClass('is-invalid');
                    $confirmPassword.after('<div class="error-message text-danger mt-1" style="font-size: 0.85rem;">Passwords do not match</div>');
                }
            }
            
            if (!isValid) {
                e.preventDefault();
                
                // Focus on first invalid field
                const $firstInvalid = $form.find('.is-invalid').first();
                if ($firstInvalid.length) {
                    $firstInvalid.focus();
                    
                    // Scroll to error
                    $('html, body').animate({
                        scrollTop: $firstInvalid.offset().top - 100
                    }, 300);
                }
            }
        });
    }

    /**
     * Focus States for Accessibility
     */
    function initFocusManagement() {
        // Enhanced focus visibility for keyboard navigation
        $('a, button, input, select, textarea, [tabindex]').on('focus', function() {
            $(this).addClass('keyboard-focus');
        }).on('blur', function() {
            $(this).removeClass('keyboard-focus');
        });
    }

    /**
     * Success/Error Messages
     */
    function showMessage(type, message) {
        const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
        const icon = type === 'success' ? 'icon_check' : 'icon_error-circle';
        
        const $alert = $(`
            <div class="alert ${alertClass} alert-dismissible fade show" role="alert" style="position: fixed; top: 20px; right: 20px; z-index: 9999; min-width: 300px;">
                <i class="${icon}" aria-hidden="true"></i>
                <strong>${message}</strong>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        `);
        
        $('body').append($alert);
        
        // Auto-dismiss after 5 seconds
        setTimeout(function() {
            $alert.alert('close');
        }, 5000);
    }

    /**
     * Initialize all settings page functionality
     */
    function initSettings() {
        initPasswordToggle();
        initPasswordStrength();
        initInterestTags();
        initToggleSwitches();
        initFormValidation();
        initFocusManagement();
        
        // Handle form submissions (demo - prevent actual submission)
        $('.settings-form').on('submit', function(e) {
            e.preventDefault();
            showMessage('success', 'Settings saved successfully!');
        });
        
        console.log('Settings page initialized');
    }

    // Initialize when document is ready
    $(document).ready(function() {
        if ($('.dashboard-area').length || $('.settings-card').length) {
            initSettings();
        }
    });

})(jQuery);
