async function loadProfile(pushHistory = true) {
    const view = showView('profileView');

    if (!view) return;

    if (pushHistory) {
        const url = new URL(window.location.href);
        url.searchParams.set('page', 'home');
        url.searchParams.set('profile', '1');
        url.searchParams.delete('task');
        url.searchParams.delete('project');
        url.searchParams.delete('tasks');
        url.searchParams.delete('version');
        url.searchParams.delete('admin');
        window.history.pushState({}, '', url);
    }

    const userId = getCurrentUserId();
    const result = await apiGet('/api/user.php', {
        api: 'UserInfo',
        user_id: userId,
        _: Date.now()
    });

    if (!result.success) {
        view.innerHTML = '<div class="alert alert-danger">Could not load profile.</div>';
        return;
    }

    renderProfile(result.user);
}

function renderProfile(user) {
    currentProfileUser = user;

    setText('profileStatus', '');
    document.getElementById('profileName').value = user.name ?? '';
    document.getElementById('profileEmail').value = user.email ?? '';
    document.getElementById('profilePassword').value = '';
    document.getElementById('profilePasswordConfirm').value = '';
    document.getElementById('profileTheme').value = user.settings?.theme ?? 'dark';
    document.getElementById('profileRemovePicture').checked = false;
    document.getElementById('profilePictureInput').value = '';
    renderProfileAvatar(user.picture);
}

function renderProfileAvatar(picture) {
    const preview = document.getElementById('profileAvatarPreview');

    if (!preview) return;

    if (picture) {
        preview.innerHTML = `<img src="${picture}" alt="">`;
        return;
    }

    preview.innerHTML = `
        <span class="profile-avatar-fallback">
            <i class="fa-solid fa-user"></i>
        </span>
    `;
}

