// 文章列表页
const { useState, useEffect, useCallback } = React;

function ArticlesPage() {
  const { navigate, goBack, showToast, api, requireLogin } = useApp();
  const [categories, setCategories] = useState([]);
  const [activeCat, setActiveCat] = useState(0); // 0 = 全部
  const [articles, setArticles] = useState([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [keyword, setKeyword] = useState('');
  const [showSearch, setShowSearch] = useState(false);

  const loadCategories = useCallback(async () => {
    try {
      const res = await api.get('/article-categories');
      if (res.success) {
        setCategories(res.data || []);
      }
    } catch(e) {}
  }, [api]);

  const loadArticles = useCallback(async (reset = false) => {
    if (loading) return;
    const nextPage = reset ? 1 : page;
    if (reset) {
      setPage(1);
      setHasMore(true);
    }
    if (!hasMore && !reset) return;

    setLoading(true);
    try {
      const params = { page: nextPage, size: 10 };
      if (activeCat > 0) params.category_id = activeCat;
      if (keyword.trim()) params.keyword = keyword.trim();
      const res = await api.get('/articles', params);
      if (res.success) {
        const list = res.data.list || [];
        setArticles(prev => reset ? list : [...prev, ...list]);
        setHasMore(list.length >= 10 && list.length < res.data.total);
        setPage(nextPage + 1);
      }
    } catch(e) {
      showToast('加载失败');
    } finally {
      setLoading(false);
    }
  }, [api, activeCat, keyword, page, hasMore, loading, showToast]);

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

  useEffect(() => {
    loadArticles(true);
  }, [activeCat]);

  // 搜索防抖
  useEffect(() => {
    const t = setTimeout(() => {
      loadArticles(true);
    }, 400);
    return () => clearTimeout(t);
  }, [keyword]);

  const handleScroll = (e) => {
    const el = e.target;
    if (el.scrollHeight - el.scrollTop - el.clientHeight < 100) {
      if (!loading && hasMore) loadArticles(false);
    }
  };

  const openArticle = (id) => {
    navigate('article-detail', { id });
  };

  const formatTime = (t) => {
    if (!t) return '';
    const d = new Date(t.replace(' ', 'T'));
    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 t.substring(5, 16);
  };

  return (
    <div className="page-container" onScroll={handleScroll}>
      <AppHeader
        title="文章"
        subtitle="发现优质内容"
        showBack
        onBack={goBack}
        rightContent={
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div
              className="icon-btn"
              onClick={() => setShowSearch(!showSearch)}
              style={{ fontSize: 16, cursor: 'pointer' }}
            >
              {showSearch ? '✕' : '🔍'}
            </div>
            <div
              onClick={() => {
                if (!requireLogin(() => {}, 'login')) return;
                if (window.openArticlePublish) {
                  window.openArticlePublish();
                } else {
                  showToast('功能加载中...');
                }
              }}
              style={{
                display: 'inline-flex',
                alignItems: 'center',
                gap: 2,
                padding: '5px 12px',
                background: 'var(--primary)',
                color: '#fff',
                borderRadius: 14,
                fontSize: 12,
                fontWeight: 600,
                cursor: 'pointer',
              }}
            >
              ＋
            </div>
          </div>
        }
        showActions={false}
      />

      {showSearch && (
        <div className="search-bar">
          <input
            type="text"
            placeholder="搜索文章..."
            value={keyword}
            onChange={(e) => setKeyword(e.target.value)}
            autoFocus
          />
        </div>
      )}

      {/* 分类标签 */}
      <div className="cat-tabs">
        <div
          className={`cat-tab ${activeCat === 0 ? 'active' : ''}`}
          onClick={() => setActiveCat(0)}
        >
          全部
        </div>
        {categories.map(c => (
          <div
            key={c.id}
            className={`cat-tab ${activeCat === c.id ? 'active' : ''}`}
            onClick={() => setActiveCat(c.id)}
          >
            {c.name}
          </div>
        ))}
      </div>

      {/* 文章列表 */}
      <div className="article-list">
        {articles.length === 0 && !loading && (
          <div className="empty-state">
            <div style={{ fontSize: '48px', marginBottom: 12 }}>📝</div>
            <div className="empty-text">暂无文章</div>
          </div>
        )}

        {articles.map(article => (
          <div
            key={article.id}
            className="article-card"
            onClick={() => openArticle(article.id)}
          >
            {article.cover_image && (
              <div className="article-cover">
                <img src={article.cover_image} alt="" />
              </div>
            )}
            <div className="article-info">
              <h3 className="article-title">{article.title}</h3>
              <p className="article-summary">{article.summary || '暂无摘要'}</p>
              <div className="article-meta">
                <div className="article-author">
                  {article.avatar && <img src={article.avatar} alt="" />}
                  <span>{article.nickname}</span>
                </div>
                {article.category_name && (
                  <span className="article-cat-tag">{article.category_name}</span>
                )}
                <div className="article-stats">
                  <span>👁 {article.views_count || 0}</span>
                  <span>💬 {article.comments_count || 0}</span>
                  {article.price > 0 && <span className="paid-tag">¥{article.price}</span>}
                </div>
                <span className="article-time">{formatTime(article.created_at)}</span>
              </div>
            </div>
          </div>
        ))}

        {loading && (
          <div className="loading-more">加载中...</div>
        )}
        {!hasMore && articles.length > 0 && (
          <div className="no-more">— 没有更多了 —</div>
        )}
      </div>

      <style>{`
        .cat-tabs {
          display: flex;
          gap: 8px;
          padding: 8px 16px;
          overflow-x: auto;
          background: #fff;
          border-bottom: 1px solid #f0f0f0;
          position: sticky;
          top: 0;
          z-index: 10;
        }
        .cat-tabs::-webkit-scrollbar { display: none; }
        .cat-tab {
          flex-shrink: 0;
          padding: 6px 14px;
          border-radius: 20px;
          font-size: 13px;
          color: #666;
          background: #f5f5f5;
          cursor: pointer;
          transition: all .2s;
        }
        .cat-tab.active {
          background: var(--primary-color, #2E7CF6);
          color: #fff;
        }

        .search-bar {
          padding: 8px 16px;
          background: #fff;
          border-bottom: 1px solid #f0f0f0;
        }
        .search-bar input {
          width: 100%;
          padding: 8px 14px;
          border: none;
          border-radius: 20px;
          background: #f5f5f5;
          font-size: 14px;
          outline: none;
        }

        .article-list {
          padding: 12px;
        }
        .article-card {
          background: #fff;
          border-radius: 12px;
          margin-bottom: 12px;
          overflow: hidden;
          cursor: pointer;
          box-shadow: 0 1px 4px rgba(0,0,0,0.04);
          transition: transform .2s;
        }
        .article-card:active {
          transform: scale(0.98);
        }
        .article-cover {
          width: 100%;
          height: 160px;
          overflow: hidden;
          background: #f0f0f0;
        }
        .article-cover img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        .article-info {
          padding: 12px 14px;
        }
        .article-title {
          font-size: 16px;
          font-weight: 600;
          color: #1a1a1a;
          line-height: 1.4;
          margin: 0 0 6px 0;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
        .article-summary {
          font-size: 13px;
          color: #888;
          line-height: 1.5;
          margin: 0 0 10px 0;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
        .article-meta {
          display: flex;
          align-items: center;
          gap: 8px;
          flex-wrap: wrap;
          font-size: 12px;
          color: #999;
        }
        .article-author {
          display: flex;
          align-items: center;
          gap: 6px;
          font-size: 12px;
          color: #666;
        }
        .article-author img {
          width: 20px;
          height: 20px;
          border-radius: 50%;
        }
        .article-cat-tag {
          padding: 1px 6px;
          border-radius: 4px;
          background: #e8f2ff;
          color: #2E7CF6;
          font-size: 11px;
        }
        .article-stats {
          display: flex;
          gap: 10px;
          margin-left: auto;
        }
        .article-time {
          color: #bbb;
        }
        .paid-tag {
          color: #ff6b00 !important;
          font-weight: 600;
        }

        .empty-state {
          text-align: center;
          padding: 60px 20px;
          color: #999;
        }
        .empty-text {
          font-size: 14px;
        }
        .loading-more, .no-more {
          text-align: center;
          padding: 16px;
          color: #bbb;
          font-size: 13px;
        }
      `}</style>
    </div>
  );
}

Object.assign(window, { ArticlesPage });
