'use client';
import { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslations } from 'next-intl';
import type { Locale } from '@/i18n/config';

type Post = {
  id: number;
  slug: string;
  title: string;
  titleEn: string | null;
  coverImage: string;
  coverWidth: number | null;
  coverHeight: number | null;
  tags: string | null;
  publishDate: string | null;
  likeCount: number | null;
  dislikeCount: number | null;
};

type Props = {
  initialPosts: Post[];
  initialTotal: number;
  locale: Locale;
  initialTag?: string;
  initialQ?: string;
  tags: { tag: string; count: number }[];
};

const PAGE_SIZE = 12;

export function MasonryGrid({ initialPosts, initialTotal, locale, initialTag = 'all', initialQ = '', tags }: Props) {
  const t = useTranslations();
  const [posts, setPosts] = useState<Post[]>(initialPosts);
  const [total, setTotal] = useState(initialTotal);
  const [tag, setTag] = useState(initialTag);
  const [q, setQ] = useState(initialQ);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const sentinelRef = useRef<HTMLDivElement>(null);

  // 当筛选条件变化时重置
  const resetAndFetch = useCallback(async (newTag: string, newQ: string) => {
    setLoading(true);
    try {
      const params = new URLSearchParams({ page: '1', limit: String(PAGE_SIZE) });
      if (newTag !== 'all') params.set('tag', newTag);
      if (newQ) params.set('q', newQ);
      const res = await fetch(`/api/blog?${params}`);
      const data = await res.json();
      setPosts(data.posts);
      setTotal(data.total);
      setPage(1);
    } finally {
      setLoading(false);
    }
  }, []);

  const loadMore = useCallback(async () => {
    if (loading) return;
    const next = page + 1;
    setLoading(true);
    try {
      const params = new URLSearchParams({ page: String(next), limit: String(PAGE_SIZE) });
      if (tag !== 'all') params.set('tag', tag);
      if (q) params.set('q', q);
      const res = await fetch(`/api/blog?${params}`);
      const data = await res.json();
      setPosts(prev => [...prev, ...data.posts]);
      setPage(next);
    } finally {
      setLoading(false);
    }
  }, [page, loading, tag, q]);

  // IntersectionObserver 触发加载更多
  useEffect(() => {
    const el = sentinelRef.current;
    if (!el) return;
    const observer = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting && posts.length < total && !loading) {
        loadMore();
      }
    }, { rootMargin: '200px' });
    observer.observe(el);
    return () => observer.disconnect();
  }, [posts.length, total, loading, loadMore]);

  const hasMore = posts.length < total;
  const pickTitle = (p: Post) => locale === 'en' ? (p.titleEn || p.title) : (p.title || p.titleEn || '');

  return (
    <>
      <div className="search-bar">
        <input
          className="search-input"
          type="text"
          value={q}
          onChange={(e) => setQ(e.target.value)}
          onKeyDown={(e) => { if (e.key === 'Enter') resetAndFetch(tag, q); }}
          placeholder={t('search.placeholder')}
        />
        <div className="tag-cloud">
          <button
            className={`tag-chip ${tag === 'all' ? 'active' : ''}`}
            onClick={() => { setTag('all'); resetAndFetch('all', q); }}
          >
            {t('search.all')}
          </button>
          {tags.map(({ tag: tg, count }) => (
            <button
              key={tg}
              className={`tag-chip ${tag === tg ? 'active' : ''}`}
              onClick={() => { setTag(tg); resetAndFetch(tg, q); }}
            >
              {tg}<span className="count">{count}</span>
            </button>
          ))}
        </div>
      </div>

      {posts.length === 0 ? (
        <div className="empty-state">
          <p>{t('search.noResults')}</p>
        </div>
      ) : (
        <div className="masonry-grid">
          {posts.map(p => (
            <a key={p.id} href={`/blog/${p.slug}`} className="masonry-item">
              <img
                src={p.coverImage}
                alt={pickTitle(p)}
                className="masonry-cover"
                width={p.coverWidth || 800}
                height={p.coverHeight || 600}
                loading="lazy"
              />
              <div className="masonry-info">
                <div className="masonry-title">{pickTitle(p)}</div>
                <div className="masonry-meta">
                  <span>{p.publishDate}</span>
                  <span>♥ {p.likeCount ?? 0}</span>
                </div>
                {p.tags && (
                  <div className="masonry-tags">
                    {p.tags.split(',').slice(0, 2).map(tg => (
                      <span key={tg} className="masonry-tag">{tg.trim()}</span>
                    ))}
                  </div>
                )}
              </div>
            </a>
          ))}
        </div>
      )}

      <div ref={sentinelRef} className="load-more-sentinel" />
      {hasMore && (
        <button
          className="load-more-btn"
          onClick={loadMore}
          disabled={loading}
        >
          {loading ? '...' : t('search.results', { count: total })}
        </button>
      )}
    </>
  );
}
