// Feed Page - 恢复完整 UI 样式版本
// 保留错误边界 + 静态兜底数据，确保不白屏
// 样式还原：全站动态时间线 + 博客风格说说卡片 + 楼中楼评论

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

// ========== 全局兜底 ==========
if (typeof API === 'undefined') {
  window.API = {
    get: () => Promise.resolve({ success: false, data: null, message: '服务未就绪' }),
    post: () => Promise.resolve({ success: false, data: null, message: '服务未就绪' }),
    uploadFile: () => Promise.resolve({ success: false, data: null, message: '服务未就绪' }),
  };
}

// ========== 错误边界 ==========
class FeedErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, errorInfo: '' };
  }
  static getDerivedStateFromError(error) {
    return { hasError: true, errorInfo: error?.message || '' };
  }
  componentDidCatch(error, errorInfo) {
    console.error('[FeedPage] 渲染错误:', error, errorInfo);
  }
  render() {
    if (this.state.hasError) {
      return (
        <div style={{ minHeight: '100vh', background: 'var(--bg-page)' }}>
          <div style={{
            padding: '16px', background: 'var(--bg-card)',
            borderBottom: '1px solid var(--border)',
            fontSize: '16px', fontWeight: 600, color: 'var(--text-primary)',
          }}>心情动态</div>
          <div style={{ padding: '40px 20px', textAlign: 'center' }}>
            <div style={{ fontSize: '40px', marginBottom: 16 }}>⚠️</div>
            <div style={{ fontSize: '16px', color: '#333', marginBottom: 8, fontWeight: 600 }}>页面加载异常</div>
            <div style={{ fontSize: '13px', color: '#999', marginBottom: 20 }}>
              {this.state.errorInfo || '内容暂时无法显示'}
            </div>
            <button
              onClick={() => this.setState({ hasError: false, errorInfo: '' })}
              style={{
                padding: '10px 24px',
                background: 'var(--primary)',
                color: '#fff',
                border: 'none',
                borderRadius: 20,
                fontSize: '14px',
              }}
            >重新加载</button>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

// ========== 静态测试数据 ==========
const STATIC_TIMELINE = [
  { id: 1, nickname: '小城故事', action: '发布了说说', preview: '今天的晚霞真好看…', time: '2分钟前', color: '#165DFF' },
  { id: 2, nickname: '追梦人', action: '评论了', preview: '说得太好了！', time: '5分钟前', color: '#10B981' },
  { id: 3, nickname: '清风徐来', action: '点赞了', preview: '坚持跑步第100天…', time: '12分钟前', color: '#F59E0B' },
  { id: 4, nickname: '云淡风轻', action: '发布了文章', preview: '关于生活的思考…', time: '30分钟前', color: '#9333EA' },
  { id: 5, nickname: '山水之间', action: '收藏了', preview: '超实用的攻略…', time: '1小时前', color: '#0EA5E9' },
];

const STATIC_FEEDS = [
  {
    id: 1,
    nickname: '小城故事',
    avatar_color: '#165DFF',
    content: '今天的晚霞真好看，分享给大家～\n\n生活中的小确幸，往往就在抬头的那一刻。放慢脚步，你会发现身边到处都是美好。',
    created_at: '2026-09-19 18:30',
    visibility: 'public',
    images: [],
    videos: [],
    tags: ['生活随笔', '晚霞'],
    likes_count: 23,
    comments_count: 5,
    is_liked: false,
    is_collected: false,
    comments: [
      {
        id: 101,
        nickname: '追梦人',
        avatar_color: '#10B981',
        content: '真的好美！是在哪里拍的呀？',
        created_at: '2026-09-19 18:45',
        replies: [
          {
            id: 1001,
            nickname: '小城故事',
            reply_to: '追梦人',
            avatar_color: '#165DFF',
            content: '就在家楼下的江边，刚好赶上日落时分~',
            created_at: '2026-09-19 18:50',
          },
        ],
      },
      {
        id: 102,
        nickname: '清风徐来',
        avatar_color: '#F59E0B',
        content: '同感！每天下班路上抬头看看天，一天的疲惫都消了。',
        created_at: '2026-09-19 19:02',
        replies: [],
      },
    ],
  },
  {
    id: 2,
    nickname: '追梦人',
    avatar_color: '#10B981',
    content: '周末去了趟老巷口的书店，翻到一本久违的诗集。\n\n时光慢下来的感觉真好，书页间都是旧时光的味道。',
    created_at: '2026-09-18 20:15',
    visibility: 'public',
    images: [
      { url: '', width: 400, height: 300, color: '#A855F7' },
      { url: '', width: 400, height: 300, color: '#EC4899' },
      { url: '', width: 400, height: 300, color: '#14B8A6' },
    ],
    videos: [],
    tags: ['周末', '书店', '阅读'],
    likes_count: 42,
    comments_count: 12,
    is_liked: true,
    is_collected: false,
    comments: [
      {
        id: 201,
        nickname: '云淡风轻',
        avatar_color: '#9333EA',
        content: '这家书店叫什么名字呀？下次也想去看看',
        created_at: '2026-09-18 21:00',
        replies: [],
      },
    ],
  },
  {
    id: 3,
    nickname: '清风徐来',
    avatar_color: '#F59E0B',
    content: '坚持跑步第100天打卡！💪\n\n从一开始的两公里都喘，到现在轻松五公里。\n\n只要开始，就永远不晚。你也可以的！',
    created_at: '2026-09-17 07:00',
    visibility: 'public',
    images: [
      { url: '', width: 600, height: 400, color: '#22C55E' },
    ],
    videos: [],
    tags: ['运动', '跑步打卡', '自律'],
    likes_count: 67,
    comments_count: 18,
    is_liked: false,
    is_collected: true,
    comments: [
      {
        id: 301,
        nickname: '山水之间',
        avatar_color: '#0EA5E9',
        content: '太励志了！我也要开始跑步',
        created_at: '2026-09-17 08:15',
        replies: [
          {
            id: 3001,
            nickname: '清风徐来',
            reply_to: '山水之间',
            avatar_color: '#F59E0B',
            content: '加油！从快走开始，慢慢加量，一定可以的~',
            created_at: '2026-09-17 08:30',
          },
          {
            id: 3002,
            nickname: '追梦人',
            reply_to: '清风徐来',
            avatar_color: '#10B981',
            content: '说的对，循序渐进最重要！',
            created_at: '2026-09-17 09:00',
          },
        ],
      },
    ],
  },
];

// ========== 头像组件 ==========
function Avatar({ name = '用', size = 40, color = '#165DFF', style = {} }) {
  const fontSize = Math.round(size * 0.38);
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: `linear-gradient(135deg, ${color}, ${lightenColor(color, 20)})`,
      color: '#fff', fontSize, fontWeight: 600,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      flexShrink: 0, userSelect: 'none',
      ...style,
    }}>
      {(name || '用').charAt(0)}
    </div>
  );
}

function lightenColor(hex, percent) {
  try {
    const n = parseInt(hex.replace('#', ''), 16);
    let r = (n >> 16) + percent;
    let g = ((n >> 8) & 0xff) + percent;
    let b = (n & 0xff) + percent;
    r = Math.min(255, Math.max(0, r));
    g = Math.min(255, Math.max(0, g));
    b = Math.min(255, Math.max(0, b));
    return '#' + ((r << 16) | (g << 8) | b).toString(16).padStart(6, '0');
  } catch (e) {
    return hex;
  }
}

// ========== 全站动态时间线 ==========
function TimelineSection({ items, onRefresh }) {
  return (
    <div style={{
      background: 'var(--bg-card)',
      borderBottom: '1px solid var(--border)',
    }}>
      <div style={{
        padding: '12px 16px 0',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
      }}>
        <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-primary)' }}>
          🔥 全站动态
        </span>
        <span
          onClick={onRefresh}
          style={{ fontSize: 11, color: 'var(--text-tertiary)', cursor: 'pointer' }}
        >
          🔄 刷新
        </span>
      </div>
      <div style={{
        maxHeight: 240,
        overflowY: 'auto',
        padding: '4px 16px 10px',
      }}>
        {items.map((item, idx) => (
          <div
            key={item.id || idx}
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: 10,
              padding: '8px 0',
              borderBottom: idx === items.length - 1 ? 'none' : '1px solid #f2f3f5',
              fontSize: 12,
              lineHeight: 1.4,
            }}
          >
            <Avatar name={item.nickname} size={28} color={item.color} />
            <div style={{ flex: 1, minWidth: 0, overflow: 'hidden' }}>
              <span style={{ fontWeight: 600, color: 'var(--text-primary)' }}>
                {item.nickname}
              </span>
              <span style={{ margin: '0 3px', color: 'var(--text-secondary)' }}>
                {item.action}
              </span>
              <span style={{ color: 'var(--text-tertiary)' }}>
                {item.preview}
              </span>
            </div>
            <div style={{
              fontSize: 10,
              color: 'var(--text-tertiary)',
              whiteSpace: 'nowrap',
              flexShrink: 0,
            }}>
              {item.time}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ========== 楼中楼评论组件 ==========
function CommentSection({ comments = [], feedId, onReply }) {
  const [replyTo, setReplyTo] = useState(null);
  const [replyText, setReplyText] = useState('');

  return (
    <div style={{
      background: 'var(--bg-page)',
      borderTop: '1px solid var(--border)',
      padding: '12px 16px',
    }}>
      {comments.map((comment, cIdx) => (
        <CommentItem
          key={comment.id || cIdx}
          comment={comment}
          onReply={(replyTarget) => {
            setReplyTo(replyTarget);
            if (onReply) onReply(replyTarget);
          }}
        />
      ))}
      {comments.length === 0 && (
        <div style={{
          textAlign: 'center',
          padding: '8px 0',
          fontSize: 12,
          color: 'var(--text-tertiary)',
        }}>
          还没有评论，快来抢沙发～
        </div>
      )}

      {/* 评论输入框 */}
      <div style={{
        display: 'flex',
        alignItems: 'center',
        gap: 8,
        marginTop: 12,
        paddingTop: 10,
        borderTop: '1px solid var(--border)',
      }}>
        <input
          type="text"
          placeholder={replyTo ? `回复 ${replyTo.nickname}：` : "说点什么…"}
          value={replyText}
          onChange={(e) => setReplyText(e.target.value)}
          style={{
            flex: 1,
            height: 36,
            padding: '0 14px',
            borderRadius: 18,
            border: 'none',
            background: '#fff',
            fontSize: 13,
            outline: 'none',
          }}
        />
        <button
          style={{
            height: 36,
            padding: '0 16px',
            borderRadius: 18,
            border: 'none',
            background: 'var(--primary)',
            color: '#fff',
            fontSize: 13,
            fontWeight: 500,
            cursor: 'pointer',
          }}
          onClick={() => {
            if (!replyText.trim()) return;
            setReplyText('');
            setReplyTo(null);
          }}
        >发送</button>
      </div>
    </div>
  );
}

function CommentItem({ comment, onReply }) {
  const [showAllReplies, setShowAllReplies] = useState(false);
  const replies = comment.replies || [];
  const visibleReplies = showAllReplies ? replies : replies.slice(0, 2);
  const hasMore = replies.length > 2;

  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{ display: 'flex', gap: 8 }}>
        <Avatar name={comment.nickname} size={28} color={comment.avatar_color || '#10B981'} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-secondary)' }}>
            {comment.nickname}
          </div>
          <div style={{
            fontSize: 13,
            color: 'var(--text-primary)',
            lineHeight: 1.5,
            marginTop: 3,
            wordBreak: 'break-word',
          }}>
            {comment.content}
          </div>
          <div style={{
            display: 'flex',
            gap: 16,
            marginTop: 4,
            fontSize: 11,
            color: 'var(--text-tertiary)',
          }}>
            <span>{formatTime(comment.created_at)}</span>
            <span
              style={{ color: 'var(--primary)', cursor: 'pointer' }}
              onClick={() => onReply && onReply({ id: comment.id, nickname: comment.nickname })}
            >回复</span>
          </div>
        </div>
      </div>

      {/* 楼中楼回复 */}
      {replies.length > 0 && (
        <div style={{
          marginTop: 8,
          marginLeft: 36,
          background: 'rgba(245, 246, 248, 0.8)',
          borderRadius: 8,
          padding: '10px 12px',
        }}>
          {visibleReplies.map((reply, rIdx) => (
            <div key={reply.id || rIdx} style={{
              display: 'flex',
              gap: 6,
              marginBottom: rIdx === visibleReplies.length - 1 ? 0 : 8,
            }}>
              <Avatar name={reply.nickname} size={22} color={reply.avatar_color || '#F59E0B'} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{
                  fontSize: 12,
                  lineHeight: 1.5,
                  color: 'var(--text-primary)',
                  wordBreak: 'break-word',
                }}>
                  <span style={{ fontWeight: 600, color: 'var(--text-secondary)' }}>
                    {reply.nickname}
                  </span>
                  {reply.reply_to && (
                    <>
                      <span style={{ color: 'var(--text-tertiary)', margin: '0 2px' }}>回复</span>
                      <span style={{ color: 'var(--primary)', fontWeight: 500 }}>
                        @{reply.reply_to}
                      </span>
                    </>
                  )}
                  <span style={{ marginLeft: 2 }}>{reply.content}</span>
                </div>
                <div style={{
                  fontSize: 10,
                  color: 'var(--text-tertiary)',
                  marginTop: 2,
                }}>
                  {formatTime(reply.created_at)}
                </div>
              </div>
            </div>
          ))}
          {hasMore && (
            <div
              style={{
                fontSize: 12,
                color: 'var(--primary)',
                fontWeight: 500,
                marginTop: 6,
                cursor: 'pointer',
              }}
              onClick={() => setShowAllReplies(!showAllReplies)}
            >
              {showAllReplies ? '收起回复' : `查看全部 ${replies.length} 条回复`}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function formatTime(dateStr) {
  if (!dateStr) return '';
  try {
    const d = new Date(dateStr.replace(' ', 'T'));
    if (isNaN(d.getTime())) return dateStr;
    const now = new Date();
    const diff = (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 < 86400 * 7) return Math.floor(diff / 86400) + '天前';
    return dateStr.slice(5, 16).replace('-', '月').replace(' ', '日 ');
  } catch (e) {
    return dateStr || '';
  }
}

// ========== 说说卡片组件 ==========
function FeedCard({ item, onLike, onCollect, onComment, onShare, requireLogin, showToast }) {
  const [expanded, setExpanded] = useState(false);
  const [showComments, setShowComments] = useState(false);
  const content = item.content || '';
  const isLong = content.length > 120 || content.split('\n').length > 3;

  const handleLike = () => {
    if (!requireLogin(() => handleLike())) return;
    onLike && onLike(item);
  };

  const handleCollect = () => {
    if (!requireLogin(() => handleCollect())) return;
    onCollect && onCollect(item);
  };

  const handleComment = () => {
    if (!requireLogin(() => handleComment())) return;
    setShowComments(!showComments);
    onComment && onComment(item);
  };

  const handleShare = () => {
    if (!requireLogin(() => handleShare())) return;
    showToast && showToast('分享功能开发中');
    onShare && onShare(item);
  };

  const images = item.images || [];
  const videos = item.videos || [];
  const tags = item.tags || [];

  return (
    <div style={{
      background: 'var(--bg-card)',
      borderRadius: 12,
      marginBottom: 12,
      boxShadow: '0 2px 8px rgba(0,0,0,0.04)',
      overflow: 'hidden',
    }}>
      {/* 卡片头部 */}
      <div style={{
        padding: '14px 16px 10px',
        display: 'flex',
        alignItems: 'center',
        gap: 12,
      }}>
        <div style={{ cursor: 'pointer' }} onClick={() => navigate('space', { user_id: item.user_id })}>
          <Avatar name={item.nickname} size={40} color={item.avatar_color || '#165DFF'} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontSize: 14,
            fontWeight: 600,
            color: 'var(--text-primary)',
            display: 'flex',
            alignItems: 'center',
            gap: 8,
          }}>
            <span
              onClick={() => navigate('space', { user_id: item.user_id })}
              style={{ cursor: 'pointer' }}
            >
              {item.nickname || '匿名用户'}
            </span>
            {item.visibility === 'public' && (
              <span style={{
                fontSize: 11,
                padding: '3px 8px',
                borderRadius: 10,
                background: 'var(--primary-light)',
                color: 'var(--primary)',
                fontWeight: 500,
              }}>公开</span>
            )}
          </div>
          <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 }}>
            {formatTime(item.created_at)}
          </div>
        </div>
      </div>

      {/* 正文内容 */}
      <div style={{ padding: '6px 16px 12px' }}>
        <div style={{
          fontSize: 14.5,
          lineHeight: 1.65,
          color: 'var(--text-primary)',
          whiteSpace: 'pre-wrap',
          wordBreak: 'break-word',
          display: '-webkit-box',
          WebkitLineClamp: expanded ? 'unset' : 3,
          WebkitBoxOrient: 'vertical',
          overflow: expanded ? 'visible' : 'hidden',
          textOverflow: 'ellipsis',
        }}>
          {content}
        </div>
        {isLong && (
          <div
            style={{
              fontSize: 13,
              fontWeight: 500,
              color: 'var(--primary)',
              marginTop: 4,
              cursor: 'pointer',
            }}
            onClick={() => setExpanded(!expanded)}
          >
            {expanded ? '收起' : '展开全文'}
          </div>
        )}
      </div>

      {/* 图片附件 */}
      {images.length > 0 && (
        <div style={{
          padding: '0 16px 12px',
          display: 'flex',
          flexWrap: 'wrap',
          gap: 8,
        }}>
          {images.map((img, idx) => {
            const isSingle = images.length === 1;
            const style = isSingle
              ? { maxWidth: 260, maxHeight: 220, width: 'auto', height: 'auto', flex: 'none' }
              : { width: 120, height: 120, flexShrink: 0 };
            return (
              <div
                key={idx}
                style={{
                  ...style,
                  borderRadius: 8,
                  overflow: 'hidden',
                  background: img.color || '#e5e6eb',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: '#fff',
                  fontSize: isSingle ? 16 : 12,
                  fontWeight: 500,
                }}
              >
                📷
              </div>
            );
          })}
        </div>
      )}

      {/* 视频附件 */}
      {videos.length > 0 && (
        <div style={{
          padding: '0 16px 12px',
          display: 'flex',
          flexWrap: 'wrap',
          gap: 8,
        }}>
          {videos.map((video, idx) => {
            const isSingle = videos.length === 1;
            const style = isSingle
              ? { width: 300, height: 180 }
              : { width: 200, height: 120 };
            return (
              <div
                key={idx}
                style={{
                  ...style,
                  borderRadius: 8,
                  overflow: 'hidden',
                  background: '#000',
                  position: 'relative',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: '#fff',
                  fontSize: 24,
                }}
              >
                ▶️
              </div>
            );
          })}
        </div>
      )}

      {/* 标签 */}
      {tags.length > 0 && (
        <div style={{
          padding: '0 16px 12px',
          display: 'flex',
          flexWrap: 'wrap',
          gap: 6,
        }}>
          {tags.map((tag, idx) => (
            <span
              key={idx}
              style={{
                fontSize: 12,
                fontWeight: 500,
                color: 'var(--primary)',
                padding: '3px 10px',
                borderRadius: 12,
                background: 'var(--primary-light)',
              }}
            >
              #{tag}
            </span>
          ))}
        </div>
      )}

      {/* 底部操作栏 */}
      <div style={{
        borderTop: '1px solid var(--border)',
        padding: '8px 4px',
        display: 'flex',
      }}>
        <div
          style={{
            flex: 1,
            textAlign: 'center',
            padding: '6px 0',
            fontSize: 13,
            color: item.is_liked ? 'var(--danger)' : 'var(--text-secondary)',
            cursor: 'pointer',
          }}
          onClick={handleLike}
        >
          {item.is_liked ? '❤️' : '🤍'} {item.likes_count || 0}
        </div>
        <div
          style={{
            flex: 1,
            textAlign: 'center',
            padding: '6px 0',
            fontSize: 13,
            color: showComments ? 'var(--primary)' : 'var(--text-secondary)',
            cursor: 'pointer',
          }}
          onClick={handleComment}
        >
          💬 {item.comments_count || 0}
        </div>
        <div
          style={{
            flex: 1,
            textAlign: 'center',
            padding: '6px 0',
            fontSize: 13,
            color: item.is_collected ? '#FFB800' : 'var(--text-secondary)',
            cursor: 'pointer',
          }}
          onClick={handleCollect}
        >
          {item.is_collected ? '⭐' : '☆'} 收藏
        </div>
        <div
          style={{
            flex: 1,
            textAlign: 'center',
            padding: '6px 0',
            fontSize: 13,
            color: 'var(--text-secondary)',
            cursor: 'pointer',
          }}
          onClick={handleShare}
        >
          🔄 分享
        </div>
      </div>

      {/* 评论区 */}
      {showComments && (
        <CommentSection comments={item.comments || []} feedId={item.id} />
      )}
    </div>
  );
}

// ========== 主页面组件 ==========
function FeedPage({ showPublish: externalShowPublish, onClosePublish }) {
  let navigate = () => {};
  let showToast = (msg) => console.log('[toast]', msg);
  let requireLogin = (cb) => { showToast('请先登录'); return false; };

  try {
    const app = useApp ? useApp() : {};
    navigate = app.navigate || (() => {});
    showToast = app.showToast || ((msg) => console.log('[toast]', msg));
    requireLogin = app.requireLogin || ((cb) => { showToast('请先登录'); return false; });
  } catch (e) {
    console.error('[FeedPage] useApp error:', e);
  }

  const safeRequireLogin = (callback) => {
    try {
      if (typeof requireLogin === 'function') {
        return requireLogin(callback);
      }
      showToast('请先登录');
      return false;
    } catch (e) {
      console.error('safeRequireLogin error:', e);
      showToast('请先登录');
      return false;
    }
  };

  const [timeline, setTimeline] = useState(STATIC_TIMELINE);
  const [feeds, setFeeds] = useState(STATIC_FEEDS);
  const [loading, setLoading] = useState(true);
  const [showSearch, setShowSearch] = useState(false);

  // 加载数据，失败保留静态兜底
  const loadFeeds = useCallback(async () => {
    try {
      setLoading(true);
      const res = await API.get('/feeds');
      if (res && res.success && Array.isArray(res.data) && res.data.length > 0) {
        setFeeds(res.data);
      }
    } catch (e) {
      console.error('loadFeeds error:', e);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    loadFeeds();
  }, [loadFeeds]);

  const handleLike = (item) => {
    try {
      API.post(`/feeds/${item.id}/like`).catch(() => {});
      setFeeds(feeds.map(f => {
        if (f.id === item.id) {
          const liked = !f.is_liked;
          return {
            ...f,
            is_liked: liked,
            likes_count: liked ? (f.likes_count || 0) + 1 : Math.max(0, (f.likes_count || 0) - 1),
          };
        }
        return f;
      }));
    } catch (e) {
      console.error('handleLike error:', e);
    }
  };

  const handleCollect = (item) => {
    try {
      API.post(`/feeds/${item.id}/collect`).catch(() => {});
      setFeeds(feeds.map(f => {
        if (f.id === item.id) {
          const collected = !f.is_collected;
          return { ...f, is_collected: collected };
        }
        return f;
      }));
      showToast(item.is_collected ? '已取消收藏' : '已收藏');
    } catch (e) {
      console.error('handleCollect error:', e);
    }
  };

  const refreshTimeline = () => {
    showToast('已刷新');
  };

  return (
    <FeedErrorBoundary>
      <div style={{ minHeight: '100vh', background: 'var(--bg-page)' }}>
        <AppHeader title="心情动态" subtitle="说说广场" showActions={true} />

        {/* 搜索栏 */}
        {showSearch && (
          <div style={{
            padding: '8px 16px 12px',
            background: 'var(--bg-card)',
            borderBottom: '1px solid var(--border)',
            position: 'sticky', top: 49, zIndex: 15,
          }}>
              <input
                type="text"
                placeholder="搜索说说、用户、标签…"
                style={{
                  width: '100%',
                  height: 36,
                  padding: '0 14px',
                  borderRadius: 18,
                  border: 'none',
                  background: '#f5f5f5',
                  fontSize: 13,
                  outline: 'none',
                  boxSizing: 'border-box',
                }}
              />
            </div>
          )}

        {/* 全站动态时间线 */}
        <TimelineSection items={timeline} onRefresh={refreshTimeline} />

        {/* 说说列表 */}
        <div style={{ padding: '12px 12px 20px' }}>
          {loading ? (
            <div style={{
              padding: '40px 0',
              textAlign: 'center',
              color: 'var(--text-tertiary)',
              fontSize: 13,
            }}>
              加载中...
            </div>
          ) : (
            (feeds || []).length === 0 ? (
              <div style={{
                background: 'var(--bg-card)',
                borderRadius: 12,
                padding: '40px 20px',
                textAlign: 'center',
                color: 'var(--text-tertiary)',
              }}>
                <div style={{ fontSize: 32, marginBottom: 12 }}>📝</div>
                还没有动态，快来发布第一条吧～
              </div>
            ) : (
              (feeds || []).map((feed, idx) => (
                <FeedCard
                  key={feed.id || idx}
                  item={feed}
                  onLike={handleLike}
                  onCollect={handleCollect}
                  requireLogin={safeRequireLogin}
                  showToast={showToast}
                />
              ))
            )
          )}
        </div>
      </div>
    </FeedErrorBoundary>
  );
}

Object.assign(window, { FeedPage });
