(function($) {
    'use strict';

    $(document).ready(function() {
        // Toggle password visibility
        $('.password-toggle').on('click', function() {
            var targetId = $(this).data('target');
            var passwordField = $('#' + targetId);
            
            if (passwordField.attr('type') === 'password') {
                passwordField.attr('type', 'text');
                $(this).addClass('visible').html('👁️‍🗨️');
            } else {
                passwordField.attr('type', 'password');
                $(this).removeClass('visible').html('👁️');
            }
        });
        
        // Edit Profile Form Submission
        $('#edit-profile-form').on('submit', function(e) {
            e.preventDefault();
            
            var form = $(this);
            var messageContainer = $('.subscription-system-message-container');
            
            // Clear previous messages
            messageContainer.empty();
            
            // Disable submit button
            form.find('button[type="submit"]').prop('disabled', true).text('Updating...');
            
            // Collect form data
            var formData = new FormData(form[0]);
            formData.append('action', 'subscription_system_update_profile');
            formData.append('security', $('#update_profile_nonce').val());
            
            // Send AJAX request
            $.ajax({
                url: subscription_system_ajax.ajax_url,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    // Re-enable submit button
                    form.find('button[type="submit"]').prop('disabled', false).text('Update Profile');
                    
                    if (response.success) {
                        messageContainer.html('<div class="subscription-system-message success">' + response.message + '</div>');
                        
                        // Refresh page after a delay if needed
                        if (response.refresh) {
                            setTimeout(function() {
                                window.location.reload();
                            }, 2000);
                        }
                    } else {
                        messageContainer.html('<div class="subscription-system-message error">' + response.message + '</div>');
                    }
                },
                error: function() {
                    // Re-enable submit button
                    form.find('button[type="submit"]').prop('disabled', false).text('Update Profile');
                    
                    // Display error message
                    messageContainer.html('<div class="subscription-system-message error">An error occurred. Please try again later.</div>');
                }
            });
        });
        
        // Change Password Form Submission
        $('#change-password-form').on('submit', function(e) {
            e.preventDefault();
            
            var form = $(this);
            var messageContainer = $('.subscription-system-message-container');
            
            // Clear previous messages
            messageContainer.empty();
            
            // Validate passwords match
            var newPassword = $('#new_password').val();
            var confirmPassword = $('#confirm_password').val();
            
            if (newPassword !== confirmPassword) {
                messageContainer.html('<div class="subscription-system-message error">New passwords do not match.</div>');
                return;
            }
            
            // Disable submit button
            form.find('button[type="submit"]').prop('disabled', true).text('Updating...');
            
            // Collect form data
            var formData = new FormData(form[0]);
            formData.append('action', 'subscription_system_update_profile');
            formData.append('security', $('#update_profile_nonce').val());
            
            // Send AJAX request
            $.ajax({
                url: subscription_system_ajax.ajax_url,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    // Re-enable submit button
                    form.find('button[type="submit"]').prop('disabled', false).text('Change Password');
                    
                    if (response.success) {
                        messageContainer.html('<div class="subscription-system-message success">' + response.message + '</div>');
                        form[0].reset();
                        
                        // Refresh page after a delay
                        setTimeout(function() {
                            window.location.reload();
                        }, 2000);
                    } else {
                        messageContainer.html('<div class="subscription-system-message error">' + response.message + '</div>');
                    }
                },
                error: function() {
                    // Re-enable submit button
                    form.find('button[type="submit"]').prop('disabled', false).text('Change Password');
                    
                    // Display error message
                    messageContainer.html('<div class="subscription-system-message error">An error occurred. Please try again later.</div>');
                }
            });
        });
        
        // Password strength meter
        $('#new_password').on('keyup', function() {
            var password = $(this).val();
            var strengthBar = $('.strength-bar');
            var strengthText = $('.strength-text');
            
            // Reset
            strengthBar.removeClass('weak medium strong very-strong');
            
            if (password.length === 0) {
                strengthBar.css('width', '0%');
                strengthText.text('Password strength');
                return;
            }
            
            // Check password strength
            var strength = 0;
            
            // If password is 8 characters or more
            if (password.length >= 8) strength += 1;
            
            // If password contains both lower and uppercase characters
            if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) strength += 1;
            
            // If password has numbers and characters
            if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) strength += 1;
            
            // If password has one special character
            if (password.match(/([!,%,&,@,#,$,^,*,?,_,~])/)) strength += 1;
            
            // If password has two special characters
            if (password.match(/(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,%,&,@,#,$,^,*,?,_,~])/)) strength += 1;
            
            // Update strength bar and text
            if (strength < 2) {
                strengthBar.addClass('weak').css('width', '20%');
                strengthText.text('Weak');
            } else if (strength === 2) {
                strengthBar.addClass('medium').css('width', '40%');
                strengthText.text('Medium');
            } else if (strength === 3) {
                strengthBar.addClass('strong').css('width', '60%');
                strengthText.text('Strong');
            } else if (strength === 4) {
                strengthBar.addClass('very-strong').css('width', '80%');
                strengthText.text('Very Strong');
            } else {
                strengthBar.addClass('very-strong').css('width', '100%');
                strengthText.text('Extremely Strong');
            }
        });
        
        // Confirm password validation
        $('#confirm_password').on('keyup', function() {
            var newPassword = $('#new_password').val();
            var confirmPassword = $(this).val();
            
            if (newPassword !== confirmPassword) {
                $(this).addClass('error');
                // You could add a message here if desired
            } else {
                $(this).removeClass('error');
            }
        });
        
        // Profile Image Upload
        $('#profile-image-upload').on('change', function(e) {
            var file = e.target.files[0];
            
            if (!file) {
                return;
            }
            
            // Check file type
            if (!file.type.match('image.*')) {
                alert('Please select an image file.');
                return;
            }
            
            // Check file size (max 2MB)
            if (file.size > 2 * 1024 * 1024) {
                alert('File size should be less than 2MB.');
                return;
            }
            
            // Create progress indicator
            var profileAvatar = $('.profile-avatar');
            if (!profileAvatar.find('.avatar-upload-progress').length) {
                profileAvatar.append('<div class="avatar-upload-progress">0%</div>');
            }
            
            profileAvatar.addClass('uploading');
            
            // Create form data
            var formData = new FormData();
            formData.append('action', 'subscription_system_update_avatar');
            formData.append('security', subscription_system_ajax.avatar_nonce);
            formData.append('profile_image', file);
            
            // Send AJAX request
            $.ajax({
                url: subscription_system_ajax.ajax_url,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                xhr: function() {
                    var xhr = new window.XMLHttpRequest();
                    xhr.upload.addEventListener('progress', function(evt) {
                        if (evt.lengthComputable) {
                            var percentComplete = Math.round((evt.loaded / evt.total) * 100);
                            $('.avatar-upload-progress').text(percentComplete + '%');
                        }
                    }, false);
                    return xhr;
                },
                success: function(response) {
                    profileAvatar.removeClass('uploading');
                    
                    if (response.success) {
                        // Update avatar image
                        profileAvatar.find('img').attr('src', response.data.avatar_url);
                        
                        // Show success message
                        var messageContainer = $('.subscription-system-message-container');
                        messageContainer.html('<div class="subscription-system-message success">' + response.data.message + '</div>');
                        
                        // Hide message after 3 seconds
                        setTimeout(function() {
                            messageContainer.empty();
                        }, 3000);
                    } else {
                        alert(response.data.message || 'Error uploading profile image.');
                    }
                },
                error: function() {
                    profileAvatar.removeClass('uploading');
                    alert('An error occurred. Please try again later.');
                }
            });
        });
    });

})(jQuery); 