import { useState } from 'react'
import { ArticleCard } from './ArticleCard'
import type { Article } from '@/types/nostr'

interface UserArticlesProps {
  articles: Article[]
  loading: boolean
  error: string | null
  onLoadContent: (articleId: string, authorPubkey: string) => Promise<Article | null>
  showEmptyMessage?: boolean
}

export function UserArticles({
  articles,
  loading,
  error,
  onLoadContent,
  showEmptyMessage = true,
}: UserArticlesProps) {
  const [unlockedArticles, setUnlockedArticles] = useState<Set<string>>(new Set())

  const handleUnlock = async (article: Article) => {
    const fullArticle = await onLoadContent(article.id, article.pubkey)
    if (fullArticle && fullArticle.paid) {
      setUnlockedArticles((prev) => new Set([...prev, article.id]))
    }
  }

  if (loading) {
    return (
      <div className="text-center py-12">
        <p className="text-gray-500">Loading articles...</p>
      </div>
    )
  }

  if (error) {
    return (
      <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-4">
        <p className="text-red-800">{error}</p>
      </div>
    )
  }

  if (articles.length === 0 && showEmptyMessage) {
    return (
      <div className="text-center py-12">
        <p className="text-gray-500">No articles published yet.</p>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {articles.map((article) => (
        <ArticleCard
          key={article.id}
          article={{
            ...article,
            paid: unlockedArticles.has(article.id) || article.paid,
          }}
          onUnlock={handleUnlock}
        />
      ))}
    </div>
  )
}
