import { useQuery } from '@tanstack/react-query'
import { Link } from '@tanstack/react-router'
import * as api from '@/lib/api'

export function ArticleTicker() {
  const { data } = useQuery({
    queryKey: ['ticker-articles'],
    queryFn: () => api.fetchArticles({ status: 'published', limit: 10 }),
  })

  const articles = data?.data.slice(0, 10) || []

  if (articles.length === 0) return null

  return (
    <div className="overflow-hidden bg-muted/50 border-y">
      <div className="container mx-auto max-w-6xl px-4">
        <div className="py-2 flex items-center gap-4">
          <span className="text-sm font-semibold text-primary whitespace-nowrap">
            Latest:
          </span>
          <div className="overflow-hidden flex-1 relative">
            <div className="flex animate-marquee whitespace-nowrap">
              {articles.map((article, index) => (
                 <Link
                  key={`${article.id}-${index}`}
                   to={`/articles/${article.id}`}
                  className="text-sm text-muted-foreground hover:text-foreground hover:underline inline-block px-4"
                >
                  {article.title || 'No title'}
                </Link>
              ))}
              {/* Duplicate for seamless scrolling */}
              {articles.map((article, index) => (
                 <Link
                  key={`dup-${article.id}-${index}`}
                   to={`/articles/${article.id}`}
                  className="text-sm text-muted-foreground hover:text-foreground hover:underline inline-block px-4"
                >
                  {article.title || 'No title'}
                </Link>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}