// ========== 个人空间（参考QQ空间风格）==========

const { useState, useEffect, useCallback, useRef } = React;

// 错误边界
class SpaceErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  static getDerivedStateFromError() { return { hasError: true }; }
  componentDidCatch(error) { console.error('Space error:', error); }
  render() {
    if (this.state.hasError) {
      return (
        <div style={{ padding: 60, textAlign: 'center', color: 'var(--text-secondary)' }}>
          <div style={{ fontSize: 40, marginBottom: 12 }}>⚠️</div>
          <div style={{ marginBottom: 8 }}>空间加载异常</div>
          <div style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>请尝试刷新页面</div>
        </div>
      );
    }
    return this.props.children;
  }
}

// 时间格式化
function timeAgo(dateStr) {
  if (!dateStr) return '';
  const d = new Date(dateStr);
  const now = new Date();
  const diff = Math.floor((now - d) / 1000);
  if (diff < 60) return '刚刚';
  if (diff < 3600) return Math.floor(diff / 60) + '分钟前';
  if (diff < 86400) return Math.floor(diff / 3600) + '小时前';
  if (diff < 2592000) return Math.floor(diff / 86400) + '天前';
  return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
}

// 首字母头像
function getInitial(name) {
  if (!name) return '?';
  return name.charAt(0);
}

// 随机封面颜色（没有自定义封面时用渐变）
const COVER_GRADIENTS = [
  'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
  'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
  'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
  'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
  'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
  'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)',
  'linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%)',
  'linear-gradient(135deg, #5ee7df 0%, #b490ca 100%)',
];

function getCoverForUser(userId) {
  const idx = (userId || 1) % COVER_GRADIENTS.length;
  return COVER_GRADIENTS[idx];
}

// ========== 个人空间主页 ==========
function SpacePage() {
  const { api, navigate, goBack, showToast, requireLogin, pageParams, currentUser } = useApp();
  const userId = pageParams?.space?.user_id ? parseInt(pageParams.space.user_id) : (currentUser?.id || 1);
  const isSelf = currentUser && currentUser.id === userId;

  const [user, setUser] = useState(null);
  const [activeTab, setActiveTab] = useState('feed'); // feed/album/message/visitor
  const [feeds, setFeeds] = useState([]);
  const [photos, setPhotos] = useState([]);
  const [messages, setMessages] = useState([]);
  const [visitors, setVisitors] = useState([]);
  const [loading, setLoading] = useState(true);
  const [followed, setFollowed] = useState(false);
  const [showMessageInput, setShowMessageInput] = useState(false);
  const [messageText, setMessageText] = useState('');
  const [showEditProfile, setShowEditProfile] = useState(false);
  const [editNickname, setEditNickname] = useState('');
  const [editBio, setEditBio] = useState('');
  const [editGender, setEditGender] = useState('');
  const [editBirthday, setEditBirthday] = useState('');
  const [editProvince, setEditProvince] = useState('');
  const [editCity, setEditCity] = useState('');
  const [editOccupation, setEditOccupation] = useState('');
  const [editEducation, setEditEducation] = useState('');
  const [replyTo, setReplyTo] = useState(null);
  const [replyText, setReplyText] = useState('');
  const msgInputRef = useRef(null);

  const loadUser = useCallback(() => {
    if (!api || !api.get) return;
    api.get(`/users/${userId}`).then(res => {
      if (res.success && res.data) {
        setUser(res.data);
        setFollowed(res.data.is_followed);
      }
    }).catch(() => {});
  }, [userId, api]);

  const loadFeeds = useCallback(() => {
    if (!api || !api.get) return;
    api.get(`/users/${userId}/feeds`).then(res => {
      if (res.success && res.data) setFeeds(res.data);
    }).catch(() => {});
  }, [userId, api]);

  const loadPhotos = useCallback(() => {
    if (!api || !api.get) return;
    api.get(`/users/${userId}/photos`).then(res => {
      if (res.success && res.data) setPhotos(res.data);
    }).catch(() => {});
  }, [userId, api]);

  const loadMessages = useCallback(() => {
    if (!api || !api.get) return;
    api.get(`/users/${userId}/messages`).then(res => {
      if (res.success && res.data) setMessages(res.data);
    }).catch(() => {});
  }, [userId, api]);

  const loadVisitors = useCallback(() => {
    if (!api || !api.get) return;
    api.get(`/users/${userId}/visitors`).then(res => {
      if (res.success && res.data) setVisitors(res.data);
    }).catch(() => {});
  }, [userId, api]);

  const recordVisit = useCallback(() => {
    if (!api || !api.post) return;
    api.post(`/users/${userId}/visit`).catch(() => {});
  }, [userId, api]);

  useEffect(() => {
    setLoading(true);
    Promise.all([loadUser(), loadFeeds(), loadPhotos(), loadMessages(), loadVisitors()]).finally(() => {
      setLoading(false);
    });
    recordVisit();
  }, [userId, loadUser, loadFeeds, loadPhotos, loadMessages, loadVisitors, recordVisit]);

  const handleFollow = () => {
    if (!requireLogin(() => handleFollow(), 'login')) return;
    api.post(`/users/${userId}/follow`).then(res => {
      if (res.success && res.data) {
        setFollowed(res.data.followed);
        showToast(res.data.followed ? '关注成功' : '已取消关注');
      } else {
        showToast(res.message || '操作失败');
      }
    }).catch(() => showToast('操作失败'));
  };

  const handleChat = () => {
    if (!requireLogin(() => handleChat(), 'login')) return;
    // 跳转到久聊，打开与该用户的会话
    navigate('im-chat', { user_id: userId });
  };

  const handleSendMessage = () => {
    if (!requireLogin(() => handleSendMessage(), 'login')) return;
    if (!messageText.trim()) { showToast('请输入留言内容'); return; }
    api.post(`/users/${userId}/messages`, { content: messageText }).then(res => {
      if (res.success) {
        showToast('留言成功');
        setMessageText('');
        setShowMessageInput(false);
        loadMessages();
      } else {
        showToast(res.message || '留言失败');
      }
    }).catch(() => showToast('留言失败'));
  };

  const handleDeleteMessage = (msgId) => {
    if (!confirm('确定删除这条留言？')) return;
    api.post(`/users/${userId}/messages/${msgId}/delete`).then(res => {
      if (res.success) { showToast('已删除'); loadMessages(); }
      else showToast(res.message || '删除失败');
    });
  };

  const handleReply = (msgId) => {
    if (!replyText.trim()) { showToast('请输入回复内容'); return; }
    api.post(`/users/${userId}/messages/${msgId}/reply`, { content: replyText }).then(res => {
      if (res.success) {
        showToast('回复成功');
        setReplyTo(null);
        setReplyText('');
        loadMessages();
      } else {
        showToast(res.message || '回复失败');
      }
    });
  };

  const handleSaveProfile = () => {
    api.post('/user/profile', {
      nickname: editNickname, bio: editBio,
      gender: editGender, birthday: editBirthday,
      province: editProvince, city: editCity,
      occupation: editOccupation, education: editEducation,
    }).then(res => {
      if (res.success) {
        showToast('资料已更新');
        setShowEditProfile(false);
        loadUser();
      } else {
        showToast(res.message || '保存失败');
      }
    });
  };

  const openEditProfile = () => {
    setEditNickname(user?.nickname || '');
    setEditBio(user?.bio || '');
    setEditGender(user?.gender || '');
    setEditBirthday(user?.birthday || '');
    setEditProvince(user?.province || '');
    setEditCity(user?.city || '');
    setEditOccupation(user?.occupation || '');
    setEditEducation(user?.education || '');
    setShowEditProfile(true);
  };

  const tabs = [
    { key: 'feed', label: '动态', icon: '📝' },
    { key: 'album', label: '相册', icon: '🖼️' },
    { key: 'message', label: '留言板', icon: '💬' },
    { key: 'visitor', label: '访客', icon: '👀' },
  ];

  if (loading || !user) {
    return (
      <PageWrapper>
        <AppHeader title="个人空间" showBack={true} />
        <div style={{ textAlign: 'center', padding: 60, color: 'var(--text-tertiary)' }}>加载中...</div>
      </PageWrapper>
    );
  }

  const coverStyle = user.space_cover
    ? { backgroundImage: `url(${user.space_cover})`, backgroundSize: 'cover', backgroundPosition: 'center' }
    : { background: getCoverForUser(userId) };

  return (
    <SpaceErrorBoundary>
      <PageWrapper>
        {/* 顶部封面 + 用户信息 */}
        <div style={{ position: 'relative' }}>
          {/* 封面图 */}
          <div style={{
            height: 200,
            width: '100%',
            position: 'relative',
            ...coverStyle,
          }}>
            {/* 返回按钮浮在封面上 */}
            <div
              onClick={goBack}
              style={{
                position: 'absolute',
                top: 12, left: 12,
                width: 32, height: 32,
                borderRadius: '50%',
                background: 'rgba(0,0,0,0.3)',
                color: '#fff',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                fontSize: 18,
                cursor: 'pointer',
                zIndex: 10,
              }}
            >
              ‹
            </div>

            {/* 装扮入口（自己的空间） */}
            {isSelf && (
              <div
                onClick={() => showToast('装扮空间功能开发中')}
                style={{
                  position: 'absolute',
                  top: 12, right: 12,
                  padding: '6px 12px',
                  borderRadius: 14,
                  background: 'rgba(0,0,0,0.3)',
                  color: '#fff',
                  fontSize: 12,
                  cursor: 'pointer',
                  zIndex: 10,
                }}
              >
                ✨ 装扮空间
              </div>
            )}
          </div>

          {/* 用户信息卡片 */}
          <div style={{
            margin: '-40px 16px 0',
            background: 'var(--bg-card)',
            borderRadius: 12,
            padding: '16px 16px 12px',
            position: 'relative',
            zIndex: 5,
            boxShadow: '0 4px 12px rgba(0,0,0,0.08)',
          }}>
            <div style={{ display: 'flex', gap: 12, marginBottom: 12 }}>
              {/* 头像 */}
              <div style={{
                width: 64, height: 64,
                borderRadius: '50%',
                border: '3px solid var(--bg-card)',
                marginTop: -32,
                background: 'linear-gradient(135deg, var(--primary), #764ba2)',
                color: '#fff',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                fontSize: 24,
                fontWeight: 600,
                flexShrink: 0,
              }}>
                {getInitial(user.nickname)}
              </div>

              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
                  <span style={{ fontSize: 17, fontWeight: 700, color: 'var(--text-primary)' }}>
                    {user.nickname}
                  </span>
                  {user.member_level !== 'normal' && (
                    <span style={{
                      fontSize: 10,
                      padding: '1px 6px',
                      borderRadius: 6,
                      background: user.member_level === 'gold' ? 'linear-gradient(135deg, #FFD700, #FFA500)' : '#C0C0C0',
                      color: '#fff',
                      fontWeight: 500,
                    }}>
                      {user.member_level === 'gold' ? '金卡' : user.member_level === 'silver' ? '银卡' : '会员'}
                    </span>
                  )}
                </div>
                <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginBottom: 4 }}>
                  空间号：<span style={{ color: 'var(--primary)', fontWeight: 500 }}>{user.space_id || ('A' + (10000 + userId))}</span>
                </div>
                <div style={{ fontSize: 12, color: 'var(--text-secondary)', lineHeight: 1.4, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
                  {user.bio || '这个人很懒，什么都没留下~'}
                </div>

                {/* 资料标签行 */}
                <div style={{
                  display: 'flex', flexWrap: 'wrap', gap: 6,
                  marginTop: 8,
                }}>
                  {user.gender ? (
                    <span style={{
                      fontSize: 11, padding: '2px 8px', borderRadius: 4,
                      background: user.gender === 'male' ? 'rgba(22, 93, 255, 0.1)' : 'rgba(236, 72, 153, 0.1)',
                      color: user.gender === 'male' ? '#165DFF' : '#EC4899',
                    }}>
                      {user.gender === 'male' ? '♂ 男' : '♀ 女'}
                    </span>
                  ) : (
                    <span style={{ fontSize: 11, padding: '2px 8px', borderRadius: 4, background: 'var(--bg-page)', color: 'var(--text-tertiary)' }}>性别未填</span>
                  )}
                  {user.age ? (
                    <span style={{ fontSize: 11, padding: '2px 8px', borderRadius: 4, background: 'var(--bg-page)', color: 'var(--text-secondary)' }}>
                      {user.age} 岁
                    </span>
                  ) : null}
                  {user.province || user.city ? (
                    <span style={{ fontSize: 11, padding: '2px 8px', borderRadius: 4, background: 'var(--bg-page)', color: 'var(--text-secondary)' }}>
                      📍 {user.province || ''}{user.city ? `·${user.city}` : ''}
                    </span>
                  ) : null}
                  {user.occupation ? (
                    <span style={{ fontSize: 11, padding: '2px 8px', borderRadius: 4, background: 'var(--bg-page)', color: 'var(--text-secondary)' }}>
                      💼 {user.occupation}
                    </span>
                  ) : null}
                  {user.education ? (
                    <span style={{ fontSize: 11, padding: '2px 8px', borderRadius: 4, background: 'var(--bg-page)', color: 'var(--text-secondary)' }}>
                      🎓 {user.education}
                    </span>
                  ) : null}
                </div>
              </div>
            </div>

            {/* 统计栏 */}
            <div style={{
              display: 'flex',
              padding: '10px 0',
              borderTop: '1px solid var(--border)',
              borderBottom: '1px solid var(--border)',
              marginBottom: 12,
            }}>
              <div style={{ flex: 1, textAlign: 'center' }}>
                <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--text-primary)' }}>{user.feed_count || 0}</div>
                <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 }}>动态</div>
              </div>
              <div style={{ flex: 1, textAlign: 'center', borderLeft: '1px solid var(--border)' }}>
                <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--text-primary)' }}>{user.following_count || 0}</div>
                <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 }}>关注</div>
              </div>
              <div style={{ flex: 1, textAlign: 'center', borderLeft: '1px solid var(--border)' }}>
                <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--text-primary)' }}>{user.follower_count || 0}</div>
                <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 }}>粉丝</div>
              </div>
              <div style={{ flex: 1, textAlign: 'center', borderLeft: '1px solid var(--border)' }}>
                <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--text-primary)' }}>{user.visit_count || 0}</div>
                <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 }}>访客</div>
              </div>
            </div>

            {/* 操作按钮 */}
            {isSelf ? (
              <div style={{ display: 'flex', gap: 8 }}>
                <div
                  onClick={openEditProfile}
                  style={{
                    flex: 1,
                    height: 34,
                    borderRadius: 17,
                    border: '1px solid var(--border)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontSize: 13,
                    color: 'var(--text-secondary)',
                    cursor: 'pointer',
                  }}
                >
                  ✏️ 编辑资料
                </div>
                <div
                  onClick={() => showToast('装扮空间功能开发中')}
                  style={{
                    flex: 1,
                    height: 34,
                    borderRadius: 17,
                    border: '1px solid var(--border)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontSize: 13,
                    color: 'var(--text-secondary)',
                    cursor: 'pointer',
                  }}
                >
                  🎨 上传封面
                </div>
              </div>
            ) : (
              <div style={{ display: 'flex', gap: 8 }}>
                <div
                  onClick={handleFollow}
                  style={{
                    flex: 1,
                    height: 34,
                    borderRadius: 17,
                    background: followed
                      ? 'var(--bg-page)'
                      : 'linear-gradient(135deg, var(--primary), #4080FF)',
                    border: followed ? '1px solid var(--border)' : 'none',
                    color: followed ? 'var(--text-secondary)' : '#fff',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontSize: 13,
                    fontWeight: followed ? 400 : 600,
                    cursor: 'pointer',
                  }}
                >
                  {followed ? '✓ 已关注' : '+ 加好友'}
                </div>
                <div
                  onClick={handleChat}
                  style={{
                    flex: 1,
                    height: 34,
                    borderRadius: 17,
                    border: '1px solid var(--border)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontSize: 13,
                    color: 'var(--text-secondary)',
                    cursor: 'pointer',
                  }}
                >
                  💬 发消息
                </div>
                <div
                  onClick={() => setShowMessageInput(true)}
                  style={{
                    flex: 1,
                    height: 34,
                    borderRadius: 17,
                    border: '1px solid var(--border)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontSize: 13,
                    color: 'var(--text-secondary)',
                    cursor: 'pointer',
                  }}
                >
                  ✉️ 留言
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Tab 切换 */}
        <div style={{
          display: 'flex',
          background: 'var(--bg-card)',
          marginTop: 12,
          borderTop: '1px solid var(--border)',
          borderBottom: '1px solid var(--border)',
          position: 'sticky',
          top: 0,
          zIndex: 20,
        }}>
          {tabs.map(tab => (
            <div
              key={tab.key}
              onClick={() => setActiveTab(tab.key)}
              style={{
                flex: 1,
                padding: '11px 0',
                textAlign: 'center',
                fontSize: 13,
                fontWeight: activeTab === tab.key ? 600 : 400,
                color: activeTab === tab.key ? 'var(--primary)' : 'var(--text-secondary)',
                cursor: 'pointer',
                position: 'relative',
              }}
            >
              <span style={{ marginRight: 2, fontSize: 14 }}>{tab.icon}</span>
              {tab.label}
              {activeTab === tab.key && (
                <div style={{
                  position: 'absolute', bottom: 0, left: '50%', transform: 'translateX(-50%)',
                  width: 24, height: 2, borderRadius: 1, background: 'var(--primary)',
                }} />
              )}
            </div>
          ))}
        </div>

        {/* 内容区 */}
        <div style={{ paddingBottom: 40 }}>
          {/* 动态 Tab */}
          {activeTab === 'feed' && (
            <div style={{ padding: 12 }}>
              {feeds.length === 0 ? (
                <div style={{ textAlign: 'center', padding: 60, color: 'var(--text-tertiary)' }}>
                  <div style={{ fontSize: 40, marginBottom: 12 }}>📭</div>
                  <div style={{ marginBottom: 4 }}>暂无动态</div>
                  <div style={{ fontSize: 11 }}>TA还没有发布任何内容</div>
                </div>
              ) : (
                feeds.map(item => (
                  <div
                    key={item.feed_type + item.id}
                    style={{
                      background: 'var(--bg-card)',
                      borderRadius: 10,
                      padding: 14,
                      marginBottom: 10,
                    }}
                  >
                    {item.feed_type === 'feed' ? (
                      // 说说
                      <>
                        <div style={{ fontSize: 14, color: 'var(--text-primary)', lineHeight: 1.6, marginBottom: item.images?.length ? 10 : 0, whiteSpace: 'pre-wrap' }}>
                          {item.content}
                        </div>
                        {item.images && item.images.length > 0 && (
                          <div style={{
                            display: 'grid',
                            gridTemplateColumns: item.images.length === 1 ? '1fr' : item.images.length === 2 ? '1fr 1fr' : '1fr 1fr 1fr',
                            gap: 4,
                            marginBottom: 10,
                          }}>
                            {item.images.map((img, i) => (
                              <div key={i} style={{
                                aspectRatio: '1/1',
                                borderRadius: 6,
                                background: 'linear-gradient(135deg, #e8ecf1, #d5dae0)',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                fontSize: 24,
                              }}>🖼️</div>
                            ))}
                          </div>
                        )}
                      </>
                    ) : (
                      // 文章
                      <div style={{ cursor: 'pointer' }} onClick={() => navigate('article-detail', { id: item.id })}>
                        <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--text-primary)', marginBottom: 6, lineHeight: 1.4 }}>
                          📄 {item.title}
                        </div>
                        <div style={{
                          fontSize: 12, color: 'var(--text-secondary)', lineHeight: 1.5,
                          display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
                        }}>
                          {item.content?.replace(/<[^>]*>/g, '') || ''}
                        </div>
                      </div>
                    )}
                    <div style={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'center',
                      paddingTop: 8,
                      borderTop: '1px solid var(--border)',
                      marginTop: 4,
                      fontSize: 11,
                      color: 'var(--text-tertiary)',
                    }}>
                      <span>{timeAgo(item.created_at)}</span>
                      <div style={{ display: 'flex', gap: 16 }}>
                        <span>👍 {item.likes_count || 0}</span>
                        <span>💬 {item.comments_count || 0}</span>
                      </div>
                    </div>
                  </div>
                ))
              )}
            </div>
          )}

          {/* 相册 Tab */}
          {activeTab === 'album' && (
            <div style={{ padding: 12 }}>
              {photos.length === 0 ? (
                <div style={{ textAlign: 'center', padding: 60, color: 'var(--text-tertiary)' }}>
                  <div style={{ fontSize: 40, marginBottom: 12 }}>🖼️</div>
                  <div style={{ marginBottom: 4 }}>暂无照片</div>
                  <div style={{ fontSize: 11 }}>TA还没有上传照片</div>
                </div>
              ) : (
                <div style={{
                  display: 'grid',
                  gridTemplateColumns: '1fr 1fr 1fr',
                  gap: 3,
                }}>
                  {photos.map((photo, i) => (
                    <div key={i} style={{
                      aspectRatio: '1/1',
                      borderRadius: 4,
                      background: 'linear-gradient(135deg, #e8ecf1, #d5dae0)',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      fontSize: 28,
                      cursor: 'pointer',
                    }}>🖼️</div>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* 留言板 Tab */}
          {activeTab === 'message' && (
            <div style={{ padding: 12 }}>
              {/* 留言输入框 */}
              {!isSelf && (
                <div style={{
                  background: 'var(--bg-card)',
                  borderRadius: 10,
                  padding: 12,
                  marginBottom: 12,
                }}>
                  <textarea
                    ref={msgInputRef}
                    placeholder="说点什么吧~"
                    value={messageText}
                    onChange={e => setMessageText(e.target.value)}
                    style={{
                      width: '100%',
                      minHeight: 60,
                      border: '1px solid var(--border)',
                      borderRadius: 8,
                      padding: 10,
                      fontSize: 13,
                      resize: 'none',
                      background: 'var(--bg-page)',
                      color: 'var(--text-primary)',
                      outline: 'none',
                      boxSizing: 'border-box',
                    }}
                  />
                  <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 8 }}>
                    <div
                      onClick={handleSendMessage}
                      style={{
                        padding: '6px 18px',
                        borderRadius: 14,
                        background: 'linear-gradient(135deg, var(--primary), #4080FF)',
                        color: '#fff',
                        fontSize: 12,
                        fontWeight: 500,
                        cursor: 'pointer',
                      }}
                    >
                      发表留言
                    </div>
                  </div>
                </div>
              )}

              {isSelf && (
                <div style={{ fontSize: 12, color: 'var(--text-tertiary)', marginBottom: 10, paddingLeft: 4 }}>
                  共 {messages.length} 条留言
                </div>
              )}

              {messages.length === 0 ? (
                <div style={{ textAlign: 'center', padding: 60, color: 'var(--text-tertiary)' }}>
                  <div style={{ fontSize: 40, marginBottom: 12 }}>💌</div>
                  <div style={{ marginBottom: 4 }}>暂无留言</div>
                  <div style={{ fontSize: 11 }}>快来抢沙发吧~</div>
                </div>
              ) : (
                messages.map(msg => (
                  <div
                    key={msg.id}
                    style={{
                      background: 'var(--bg-card)',
                      borderRadius: 10,
                      padding: 12,
                      marginBottom: 10,
                    }}
                  >
                    <div style={{ display: 'flex', gap: 10 }}>
                      {/* 头像 */}
                      <div
                        onClick={() => msg.from_user_id && navigate('space', { user_id: msg.from_user_id })}
                        style={{
                          width: 36, height: 36,
                          borderRadius: '50%',
                          background: 'linear-gradient(135deg, var(--primary), #764ba2)',
                          color: '#fff',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          fontSize: 14,
                          fontWeight: 600,
                          flexShrink: 0,
                          cursor: msg.from_user_id ? 'pointer' : 'default',
                        }}
                      >
                        {getInitial(msg.from_nickname)}
                      </div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4 }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                            <span
                              onClick={() => msg.from_user_id && navigate('space', { user_id: msg.from_user_id })}
                              style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-primary)', cursor: msg.from_user_id ? 'pointer' : 'default' }}
                            >
                              {msg.from_nickname}
                            </span>
                            {msg.from_space_id && (
                              <span style={{ fontSize: 10, color: 'var(--text-tertiary)' }}>{msg.from_space_id}</span>
                            )}
                          </div>
                          <span style={{ fontSize: 10, color: 'var(--text-tertiary)' }}>{timeAgo(msg.created_at)}</span>
                        </div>
                        <div style={{ fontSize: 13, color: 'var(--text-secondary)', lineHeight: 1.5, whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
                          {msg.content}
                        </div>

                        {/* 主人回复 */}
                        {msg.reply && (
                          <div style={{
                            marginTop: 8,
                            padding: '8px 10px',
                            background: 'var(--bg-page)',
                            borderRadius: 8,
                            borderLeft: '2px solid var(--primary)',
                          }}>
                            <div style={{ fontSize: 11, color: 'var(--primary)', marginBottom: 2, fontWeight: 500 }}>
                              主人回复：
                            </div>
                            <div style={{ fontSize: 12, color: 'var(--text-secondary)', lineHeight: 1.4 }}>
                              {msg.reply}
                            </div>
                          </div>
                        )}

                        {/* 操作栏 */}
                        <div style={{ marginTop: 8, display: 'flex', justifyContent: 'flex-end', gap: 12 }}>
                          {isSelf && !msg.reply && (
                            <span
                              onClick={() => { setReplyTo(msg.id); setReplyText(''); }}
                              style={{ fontSize: 11, color: 'var(--primary)', cursor: 'pointer' }}
                            >回复</span>
                          )}
                          {(isSelf || (currentUser && currentUser.id === msg.from_user_id)) && (
                            <span
                              onClick={() => handleDeleteMessage(msg.id)}
                              style={{ fontSize: 11, color: 'var(--text-tertiary)', cursor: 'pointer' }}
                            >删除</span>
                          )}
                        </div>

                        {/* 回复输入框 */}
                        {replyTo === msg.id && (
                          <div style={{ marginTop: 8, display: 'flex', gap: 8 }}>
                            <input
                              type="text"
                              placeholder="写下你的回复..."
                              value={replyText}
                              onChange={e => setReplyText(e.target.value)}
                              onKeyDown={e => e.key === 'Enter' && handleReply(msg.id)}
                              style={{
                                flex: 1,
                                height: 30,
                                border: '1px solid var(--border)',
                                borderRadius: 15,
                                padding: '0 12px',
                                fontSize: 12,
                                background: 'var(--bg-page)',
                                color: 'var(--text-primary)',
                                outline: 'none',
                              }}
                            />
                            <div
                              onClick={() => handleReply(msg.id)}
                              style={{
                                padding: '0 14px',
                                height: 30,
                                borderRadius: 15,
                                background: 'var(--primary)',
                                color: '#fff',
                                fontSize: 12,
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                cursor: 'pointer',
                              }}
                            >回复</div>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                ))
              )}
            </div>
          )}

          {/* 访客 Tab */}
          {activeTab === 'visitor' && (
            <div style={{ padding: 12 }}>
              {!isSelf ? (
                <div style={{ textAlign: 'center', padding: 60, color: 'var(--text-tertiary)' }}>
                  <div style={{ fontSize: 40, marginBottom: 12 }}>🔒</div>
                  <div style={{ marginBottom: 4 }}>访客记录仅空间主人可见</div>
                </div>
              ) : visitors.length === 0 ? (
                <div style={{ textAlign: 'center', padding: 60, color: 'var(--text-tertiary)' }}>
                  <div style={{ fontSize: 40, marginBottom: 12 }}>👀</div>
                  <div style={{ marginBottom: 4 }}>暂无访客</div>
                  <div style={{ fontSize: 11 }}>多发布动态吸引更多人来看你吧~</div>
                </div>
              ) : (
                <div style={{
                  background: 'var(--bg-card)',
                  borderRadius: 10,
                  overflow: 'hidden',
                }}>
                  {visitors.map((v, i) => (
                    <div
                      key={i}
                      onClick={() => v.visitor_id && v.visitor_id > 0 && navigate('space', { user_id: v.visitor_id })}
                      style={{
                        display: 'flex',
                        alignItems: 'center',
                        gap: 10,
                        padding: '12px 14px',
                        borderBottom: i < visitors.length - 1 ? '1px solid var(--border)' : 'none',
                        cursor: v.visitor_id > 0 ? 'pointer' : 'default',
                      }}
                    >
                      <div style={{
                        width: 36, height: 36,
                        borderRadius: '50%',
                        background: v.visitor_id > 0 ? 'linear-gradient(135deg, var(--primary), #764ba2)' : '#ccc',
                        color: '#fff',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        fontSize: 14,
                        fontWeight: 600,
                        flexShrink: 0,
                      }}>
                        {getInitial(v.nickname)}
                      </div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 13, color: 'var(--text-primary)', fontWeight: 500 }}>
                          {v.nickname}
                        </div>
                        <div style={{ fontSize: 10, color: 'var(--text-tertiary)', marginTop: 2 }}>
                          {timeAgo(v.visited_at)} 访问了你的空间
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}
        </div>

        {/* 留言输入弹窗（从操作按钮触发） */}
        {showMessageInput && (
          <div
            style={{
              position: 'fixed', inset: 0, zIndex: 500,
              background: 'rgba(0,0,0,0.5)',
              display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
            }}
            onClick={() => setShowMessageInput(false)}
          >
            <div
              onClick={e => e.stopPropagation()}
              style={{
                width: '100%', maxWidth: 480,
                background: '#fff',
                borderRadius: '16px 16px 0 0',
                padding: '20px 16px',
              }}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
                <span style={{ fontSize: 15, fontWeight: 600 }}>给 {user.nickname} 留言</span>
                <span
                  onClick={() => setShowMessageInput(false)}
                  style={{ fontSize: 20, color: 'var(--text-tertiary)', cursor: 'pointer' }}
                >×</span>
              </div>
              <textarea
                placeholder="说点什么吧~"
                value={messageText}
                onChange={e => setMessageText(e.target.value)}
                style={{
                  width: '100%',
                  height: 100,
                  border: '1px solid var(--border)',
                  borderRadius: 8,
                  padding: 10,
                  fontSize: 13,
                  resize: 'none',
                  background: 'var(--bg-page)',
                  color: 'var(--text-primary)',
                  outline: 'none',
                  boxSizing: 'border-box',
                }}
              />
              <div
                onClick={handleSendMessage}
                style={{
                  marginTop: 12,
                  width: '100%',
                  height: 42,
                  borderRadius: 21,
                  background: 'linear-gradient(135deg, var(--primary), #4080FF)',
                  color: '#fff',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: 14,
                  fontWeight: 600,
                  cursor: 'pointer',
                }}
              >
                发表留言
              </div>
            </div>
          </div>
        )}

        {/* 编辑资料弹窗 */}
        {showEditProfile && (
          <div
            style={{
              position: 'fixed', inset: 0, zIndex: 500,
              background: 'rgba(0,0,0,0.5)',
              display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
              padding: '20px 16px',
              overflowY: 'auto',
            }}
            onClick={() => setShowEditProfile(false)}
          >
            <div
              onClick={e => e.stopPropagation()}
              style={{
                width: '100%', maxWidth: 340,
                background: '#fff',
                borderRadius: 16,
                padding: 20,
                margin: 'auto 0',
              }}
            >
              <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 14, textAlign: 'center' }}>编辑资料</div>

              <div style={{ marginBottom: 10 }}>
                <div style={{ fontSize: 12, color: '#6B7280', marginBottom: 4 }}>昵称</div>
                <input
                  type="text"
                  value={editNickname}
                  onChange={e => setEditNickname(e.target.value)}
                  style={{
                    width: '100%', height: 38,
                    border: '1px solid #E5E7EB',
                    borderRadius: 8,
                    padding: '0 12px',
                    fontSize: 13,
                    background: '#fff',
                    color: '#374151',
                    outline: 'none',
                    boxSizing: 'border-box',
                  }}
                />
              </div>

              <div style={{ marginBottom: 10 }}>
                <div style={{ fontSize: 12, color: '#6B7280', marginBottom: 4 }}>性别</div>
                <div style={{ display: 'flex', gap: 8 }}>
                  {['male', 'female'].map(g => (
                    <div
                      key={g}
                      onClick={() => setEditGender(g)}
                      style={{
                        flex: 1, height: 36, borderRadius: 8,
                        border: editGender === g ? '1px solid #165DFF' : '1px solid #E5E7EB',
                        background: editGender === g ? 'rgba(22, 93, 255, 0.08)' : '#fff',
                        color: editGender === g ? '#165DFF' : '#6B7280',
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        fontSize: 13, cursor: 'pointer',
                        fontWeight: editGender === g ? 600 : 400,
                      }}
                    >{g === 'male' ? '男' : '女'}</div>
                  ))}
                </div>
              </div>

              <div style={{ marginBottom: 10 }}>
                <div style={{ fontSize: 12, color: '#6B7280', marginBottom: 4 }}>出生日期</div>
                <input
                  type="date"
                  value={editBirthday}
                  onChange={e => setEditBirthday(e.target.value)}
                  style={{
                    width: '100%', height: 38,
                    border: '1px solid #E5E7EB',
                    borderRadius: 8,
                    padding: '0 12px',
                    fontSize: 13,
                    background: '#fff',
                    color: '#374151',
                    outline: 'none',
                    boxSizing: 'border-box',
                  }}
                />
              </div>

              <div style={{ marginBottom: 10 }}>
                <div style={{ fontSize: 12, color: '#6B7280', marginBottom: 4 }}>所在地区</div>
                <div style={{ display: 'flex', gap: 8 }}>
                  <select
                    value={editProvince}
                    onChange={e => { setEditProvince(e.target.value); setEditCity(''); }}
                    style={{
                      flex: 1, height: 38,
                      border: '1px solid #E5E7EB',
                      borderRadius: 8,
                      padding: '0 8px',
                      fontSize: 13,
                      background: '#fff',
                      color: editProvince ? '#374151' : '#9CA3AF',
                      outline: 'none',
                      boxSizing: 'border-box',
                    }}
                  >
                    <option value="">省份</option>
                    {Object.keys(window.PROVINCE_CITY_MAP_UI || {}).map(p => (
                      <option key={p} value={p}>{p}</option>
                    ))}
                  </select>
                  <select
                    value={editCity}
                    onChange={e => setEditCity(e.target.value)}
                    disabled={!editProvince}
                    style={{
                      flex: 1, height: 38,
                      border: '1px solid #E5E7EB',
                      borderRadius: 8,
                      padding: '0 8px',
                      fontSize: 13,
                      background: '#fff',
                      color: editCity ? '#374151' : '#9CA3AF',
                      outline: 'none',
                      boxSizing: 'border-box',
                    }}
                  >
                    <option value="">城市</option>
                    {((window.PROVINCE_CITY_MAP_UI || {})[editProvince] || []).map(c => (
                      <option key={c} value={c}>{c}</option>
                    ))}
                  </select>
                </div>
              </div>

              <div style={{ marginBottom: 10 }}>
                <div style={{ fontSize: 12, color: '#6B7280', marginBottom: 4 }}>职业</div>
                <select
                  value={editOccupation}
                  onChange={e => setEditOccupation(e.target.value)}
                  style={{
                    width: '100%', height: 38,
                    border: '1px solid #E5E7EB',
                    borderRadius: 8,
                    padding: '0 12px',
                    fontSize: 13,
                    background: '#fff',
                    color: editOccupation ? '#374151' : '#9CA3AF',
                    outline: 'none',
                    boxSizing: 'border-box',
                  }}
                >
                  <option value="">请选择职业</option>
                  {(window.OCCUPATION_LIST_UI || []).map(o => (
                    <option key={o} value={o}>{o}</option>
                  ))}
                </select>
              </div>

              <div style={{ marginBottom: 10 }}>
                <div style={{ fontSize: 12, color: '#6B7280', marginBottom: 4 }}>学历</div>
                <select
                  value={editEducation}
                  onChange={e => setEditEducation(e.target.value)}
                  style={{
                    width: '100%', height: 38,
                    border: '1px solid #E5E7EB',
                    borderRadius: 8,
                    padding: '0 12px',
                    fontSize: 13,
                    background: '#fff',
                    color: editEducation ? '#374151' : '#9CA3AF',
                    outline: 'none',
                    boxSizing: 'border-box',
                  }}
                >
                  <option value="">请选择学历</option>
                  {(window.EDUCATION_LIST_UI || []).map(o => (
                    <option key={o} value={o}>{o}</option>
                  ))}
                </select>
              </div>

              <div style={{ marginBottom: 14 }}>
                <div style={{ fontSize: 12, color: '#6B7280', marginBottom: 4 }}>个性签名</div>
                <textarea
                  value={editBio}
                  onChange={e => setEditBio(e.target.value)}
                  style={{
                    width: '100%',
                    height: 60,
                    border: '1px solid #E5E7EB',
                    borderRadius: 8,
                    padding: 10,
                    fontSize: 13,
                    resize: 'none',
                    background: '#fff',
                    color: '#374151',
                    outline: 'none',
                    boxSizing: 'border-box',
                  }}
                />
              </div>

              <div style={{ display: 'flex', gap: 10 }}>
                <div
                  onClick={() => setShowEditProfile(false)}
                  style={{
                    flex: 1, height: 38, borderRadius: 19,
                    border: '1px solid #E5E7EB',
                    color: '#6B7280',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 13, cursor: 'pointer',
                  }}
                >取消</div>
                <div
                  onClick={handleSaveProfile}
                  style={{
                    flex: 1, height: 38, borderRadius: 19,
                    background: 'linear-gradient(135deg, var(--primary), #4080FF)',
                    color: '#fff',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 13, fontWeight: 600, cursor: 'pointer',
                  }}
                >保存</div>
              </div>
            </div>
          </div>
        )}
      </PageWrapper>
    </SpaceErrorBoundary>
  );
}

// 暴露到全局
Object.assign(window, {
  SpacePage,
});
