'use client'; // 用户主页:资料卡 + 该用户的帖子列表 import { useEffect, useState, useCallback } from 'react'; import { API } from '@/lib/api'; import { useApp } from './AppProvider'; import { Icon } from './Icons'; import { useOpenPrivateChat } from './chat/ChatManager'; function avatar(username, size = 128) { return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') + '&background=6366f1&color=fff&size=' + size; } export default function UserProfile({ username }) { const { currentUser, openPost } = useApp(); const openPrivateChat = useOpenPrivateChat(); const [user, setUser] = useState(null); const [posts, setPosts] = useState([]); const [error, setError] = useState(null); const load = useCallback(async () => { setError(null); try { const users = await API.getUsersByUsername(username); const u = users && users.length > 0 ? users[0] : null; if (!u) { setError('用户不存在'); return; } setUser(u); const userPosts = await API.getPosts('latest', u.id); setPosts(userPosts || []); } catch (err) { setError(err.message || '加载失败'); } }, [username]); useEffect(() => { load(); }, [load]); if (error) { return (
加载失败:{error}
); } if (!user) { return
加载中...
; } return (

用户主页

{user.username}

{user.bio || '这个人很懒,什么都没写'}

{currentUser && currentUser.id !== user.id && ( )}
📅 加入于 {user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'} 📝 发了 {posts.length} 个帖子 {user.role === 'admin' && 🛡️ 管理员}

📝 发布的帖子

{posts.length === 0 ? (
还没有发帖
) : ( posts.map((p) => { const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : ''; return (
openPost(p.id)}>
{p.title || '无标题'}
{(p.content || '').substring(0, 100)}{(p.content || '').length > 100 ? '...' : ''}
{time}
); }) )}
); }