'use client';

import { useState } from 'react';
import type { PlazaPost } from '@/types/plaza';
import { PostGrid } from '@/components/feed/PostGrid';
import { fetchUserPosts } from '@/lib/api';

type UserPostGridProps = {
  slug: string;
  initialPosts: PlazaPost[];
  initialCursor: string | null;
  initialHasMore: boolean;
};

export function UserPostGrid({
  slug,
  initialPosts,
  initialCursor,
  initialHasMore,
}: UserPostGridProps) {
  const [posts, setPosts] = useState(initialPosts);
  const [cursor, setCursor] = useState(initialCursor);
  const [hasMore, setHasMore] = useState(initialHasMore);
  const [loading, setLoading] = useState(false);

  const loadMore = async () => {
    if (!cursor || loading) return;
    setLoading(true);
    try {
      const data = await fetchUserPosts(slug, { cursor });
      setPosts((current) => [...current, ...data.posts]);
      setCursor(data.next_cursor);
      setHasMore(data.has_more);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-4">
      <h2 className="text-lg font-semibold text-[#17221d]">作品</h2>
      <PostGrid posts={posts} />
      {hasMore ? (
        <button
          type="button"
          disabled={loading}
          onClick={loadMore}
          className="w-full rounded-full border border-[#d6d0c3] py-2.5 text-sm font-semibold text-[#2f6f57]"
        >
          {loading ? '加载中…' : '加载更多'}
        </button>
      ) : null}
    </div>
  );
}
