import { prisma } from '@peyzajart/db'
import { Link } from '@/i18n/navigation'
import type { Metadata } from 'next'

export async function generateMetadata({ params: { locale } }: { params: { locale: string } }): Promise<Metadata> {
  return { title: locale === 'en' ? 'Blog' : 'Blog' }
}

export const dynamic = 'force-dynamic'

export default async function BlogPage({ params: { locale } }: { params: { locale: string } }) {
  const en = locale === 'en'
  const base = en ? '/en' : ''

  const posts = await prisma.blog.findMany({
    where: { isPublished: true },
    orderBy: { createdAt: 'desc' },
    select: { id: true, slug: true, titleTr: true, titleEn: true, excerpt: true, coverImage: true, createdAt: true },
  })

  return (
    <div className="pt-20 min-h-screen bg-cream">
      <div className="max-w-7xl mx-auto px-6 md:px-10 py-16">
        <div className="mb-12">
          <p className="font-body text-xs tracking-widest uppercase text-orange mb-3">
            {en ? 'Articles' : 'Yazılar'}
          </p>
          <h1 className="font-display text-5xl font-light text-brown">Blog</h1>
        </div>

        {posts.length === 0 ? (
          <p className="font-body text-center text-brown/40 py-20">
            {en ? 'No articles yet.' : 'Henüz yazı yok.'}
          </p>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
            {posts.map(post => {
              const title = en ? (post.titleEn ?? post.titleTr) : post.titleTr
              const date = new Date(post.createdAt).toLocaleDateString(en ? 'en-US' : 'tr-TR', {
                year: 'numeric', month: 'long', day: 'numeric',
              })
              return (
                <Link key={post.id} href={`${base}/blog/${post.slug}`} className="group">
                  <div className="aspect-video bg-sand mb-4 overflow-hidden rounded-xl">
                    {post.coverImage
                      ? <img src={post.coverImage} alt={title} className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" />
                      : <div className="w-full h-full flex items-center justify-center font-display text-5xl text-brown/10">{title[0]}</div>}
                  </div>
                  <p className="font-body text-xs text-orange/70 mb-2">{date}</p>
                  <h2 className="font-display text-xl font-light text-brown group-hover:text-orange transition-colors mb-2">{title}</h2>
                  {post.excerpt && (
                    <p className="font-body text-sm text-brown/50 leading-relaxed line-clamp-2">{post.excerpt}</p>
                  )}
                </Link>
              )
            })}
          </div>
        )}
      </div>
    </div>
  )
}
