import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import BlogSidebar from '../components/BlogSidebar.jsx';
import { listPosts, searchPosts, getTags } from '../api/blog.js';
import { getPublicSettings } from '../api/settings.js';

/** 摘要：优先取 excerpt，否则从内容中剥离 markdown 符号截取（照搬 blog.js） */
function excerptOf(p) {
  if (p.excerpt) return p.excerpt;
  return (p.content || '').replace(/[#*`\[\]()>|~_]/g, '').slice(0, 200);
}

/** 博客列表页（迁移自 blog.html + blog.js loadPosts）：瀑布流卡片，点击进详情；
 *  顶部搜索框（/api/blog/search）+ 标签云（/api/blog/tags，点击进 /tag/:name）+ 归档入口 */
export default function Blog() {
  const [settings, setSettings] = useState({});
  const [posts, setPosts] = useState(null); // null=加载中
  const [error, setError] = useState('');

  // 搜索状态
  const [query, setQuery] = useState('');
  const [results, setResults] = useState(null); // null=未搜索
  const [searching, setSearching] = useState(false);

  // 标签云
  const [tags, setTags] = useState([]);

  useEffect(() => {
    getPublicSettings().then(setSettings).catch(() => {});
    listPosts()
      .then((ps) => setPosts(ps || []))
      .catch((e) => setError(e.message || '加载失败'));
    getTags()
      .then((ts) => setTags(ts || []))
      .catch(() => setTags([]));
  }, []);

  const doSearch = async (e) => {
    e && e.preventDefault();
    const q = query.trim();
    if (!q) { setResults(null); return; }
    setSearching(true);
    try {
      const rs = await searchPosts(q);
      setResults(rs || []);
    } catch (err) {
      setResults([]);
      setError(err.message || '搜索失败');
    }
    setSearching(false);
  };

  const clearSearch = () => {
    setQuery('');
    setResults(null);
    setError('');
  };

  // 搜索结果以列表呈现（区别于瀑布流卡片）
  const renderResults = () => (
    <div className="search-results">
      <div className="search-results-head">
        <span>搜索结果（{results.length}）</span>
        <button className="btn btn-text btn-sm" onClick={clearSearch}>
          <span className="material-icons" style={{ fontSize: 16 }}>close</span> 清空
        </button>
      </div>
      {results.length === 0 ? (
        <div className="empty-state"><div className="empty-icon">🔍</div><p>没有找到相关内容</p></div>
      ) : (
        <div className="search-results-list">
          {results.map((p) => (
            <Link key={p.id} to={`/blog/${p.id}`} className="search-result-item">
              <div className="sri-title">{p.title}</div>
              {p.excerpt && <div className="sri-excerpt">{p.excerpt}</div>}
              <div className="sri-meta">
                <span>{p.author_name || '管理员'}</span>
                <span className="sep">·</span>
                <span>{p.created_at}</span>
                {p.tags && <span className="sri-tags">{p.tags}</span>}
              </div>
            </Link>
          ))}
        </div>
      )}
    </div>
  );

  return (
    <div className="homepage-layout blog-layout">
      <h1 className="sr-only">博客</h1>
      <BlogSidebar settings={settings} />
      <div className="homepage-content">
        {/* 工具条：搜索框 + 归档 */}
        <form className="blog-toolbar" onSubmit={doSearch}>
          <div className="search-box">
            <span className="material-icons">search</span>
            <input
              type="text"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="搜索文章标题 / 内容..."
              aria-label="搜索文章"
            />
            {query && (
              <button type="button" className="search-clear" onClick={() => setQuery('')} aria-label="清空输入">
                <span className="material-icons">close</span>
              </button>
            )}
          </div>
          <button type="submit" className="btn btn-tonal btn-sm" disabled={searching}>
            {searching ? '搜索中...' : '搜索'}
          </button>
          <Link to="/archive.html" className="btn btn-text btn-sm">
            <span className="material-icons" style={{ fontSize: 16 }}>archive</span> 归档
          </Link>
        </form>

        {/* 标签云 */}
        {tags.length > 0 && (
          <div className="tag-cloud card">
            <div className="tag-cloud-title">
              <span className="material-icons">local_offer</span> 标签
            </div>
            <div className="tag-cloud-body">
              {tags.map((t) => (
                <Link key={t.name} to={`/tag/${encodeURIComponent(t.name)}`} className="tag-chip" style={{ fontSize: tagSize(t.count) }}>
                  {t.name}
                  <span className="tag-count">{t.count}</span>
                </Link>
              ))}
            </div>
          </div>
        )}

        {/* 搜索结果 / 瀑布流 */}
        {results !== null ? (
          renderResults()
        ) : (
          <>
            {!posts && !error && (
              <div className="loading"><div className="spinner"></div></div>
            )}
            {error && (
              <div className="empty-state"><div className="empty-icon">⚠️</div><p>{error}</p></div>
            )}
            {posts && posts.length === 0 && (
              <div className="empty-state"><div className="empty-icon">📖</div><p>暂无文章</p></div>
            )}
            {posts && posts.length > 0 && (
              <div className="blog-waterfall">
                {posts.map((p) => (
                  <Link key={p.id} to={`/blog/${p.id}`} className="card blog-card" style={{ textDecoration: 'none' }}>
                    <div className="blog-featured"></div>
                    <div className="blog-title">{p.title}</div>
                    <div className="blog-excerpt">{excerptOf(p)}</div>
                    <div className="blog-meta">{p.author_name || '管理员'} · {p.created_at}</div>
                  </Link>
                ))}
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}

/** 标签字号随文章数渐变（经典标签云效果）：1 篇 ~12px，8 篇及以上 ~18px */
function tagSize(count) {
  const c = Number(count) || 1;
  const size = 12 + Math.min(c, 8) * 0.75;
  return size.toFixed(1) + 'px';
}
