document.addEventListener('DOMContentLoaded', function() {
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    if (!currentUser) {
        window.location.href = 'login.html';
    }

    document.getElementById('profile-username').value = currentUser.username;
    document.getElementById('profile-email').value = currentUser.email;

    if (currentUser.picture) {
        const profilePicturePreview = document.getElementById('profile-picture-preview');
        profilePicturePreview.src = currentUser.picture;
        profilePicturePreview.style.display = 'block';
    }

    document.getElementById('profile-form').addEventListener('submit', function(event) {
        event.preventDefault();

        const newUsername = document.getElementById('profile-username').value;
        const newEmail = document.getElementById('profile-email').value;
        const profilePicture = document.getElementById('profile-picture').files[0];

        if (profilePicture) {
            const reader = new FileReader();
            reader.onload = function(e) {
                currentUser.picture = e.target.result;
                saveUserData(newUsername, newEmail, currentUser.picture);
            };
            reader.readAsDataURL(profilePicture);
        } else {
            saveUserData(newUsername, newEmail, currentUser.picture);
        }
    });

    document.getElementById('logout').addEventListener('click', function() {
        localStorage.removeItem('currentUser');
        window.location.href = 'index.html';
    });

    function saveUserData(username, email, picture) {
        let users = JSON.parse(localStorage.getItem('users'));
        const currentUser = JSON.parse(localStorage.getItem('currentUser')); // Получаем текущего пользователя
        const userIndex = users.findIndex(u => u.username === currentUser.username);
    
        if (userIndex !== -1) {
            users[userIndex].username = username;
            users[userIndex].email = email;
    
            localStorage.setItem('users', JSON.stringify(users));
    
            currentUser.username = username;
            currentUser.email = email;
    
            localStorage.setItem('currentUser', JSON.stringify(currentUser));
    
            alert('Данные сохранены успешно!');
        }
    }
});
