import { sql } from '@/lib/db'
export const dynamic = "force-dynamic"
import { notFound } from 'next/navigation'
import Link from 'next/link'
import Image from 'next/image'

const CATEGORY_META: Record<string, { icon: string; color: string }> = {
  'ai-news':     { icon: '📰', color: 'from-blue-600 to-blue-800' },
  'tutorials':   { icon: '📚', color: 'from-purple-600 to-purple-800' },
  'tips-tricks': { icon: '💡', color: 'from-amber-500 to-orange-600' },
  'upcoming':    { icon: '🚀', color: 'from-emerald-600 to-teal-700' },
}

async function getCategory(slug: string) {
  try {
    const { rows } = await sql`SELECT * FROM categories WHERE slug = ${slug}`
    return rows[0] || null
  } catch {
    return null
  }
}

async function getArticlesByCategory(slug: string) {
  try {
    const { rows } = await sql`
      SELECT
        a.id, a.title_burmese, a.slug, a.excerpt_burmese,
        a.featured_image, a.reading_time, a.view_count, a.published_at,
        c.name_burmese as category_name_burmese, c.slug as category_slug
      FROM articles a
      JOIN categories c ON a.category_id = c.id
      WHERE c.slug = ${slug} AND a.status = 'published'
      ORDER BY a.published_at DESC
      LIMIT 30
    `
    return rows
  } catch {
    return []
  }
}

export default async function CategoryPage({ params }: { params: { slug: string } }) {
  const [category, articles] = await Promise.all([
    getCategory(params.slug),
    getArticlesByCategory(params.slug),
  ])

  if (!category) notFound()

  const meta = CATEGORY_META[params.slug] ?? { icon: '📄', color: 'from-gray-600 to-gray-800' }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Category Header */}
      <div className={`bg-gradient-to-br ${meta.color} text-white`}>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16">
          <div className="text-5xl mb-4">{meta.icon}</div>
          <h1 className="text-4xl font-bold font-burmese mb-3">{category.name_burmese}</h1>
          <p className="text-white/80 font-burmese text-lg">
            ဆောင်းပါး {articles.length} ခု
          </p>
        </div>
      </div>

      {/* Articles Grid */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        {articles.length === 0 ? (
          <div className="text-center py-20 bg-white rounded-2xl shadow-sm">
            <div className="text-6xl mb-4">📭</div>
            <p className="text-xl text-gray-500 font-burmese">ဆောင်းပါးမရှိသေးပါ။ မကြာမီ ပြန်စစ်ကြည့်ပါ။</p>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
            {articles.map((article: any) => (
              <article key={article.id} className="card card-hover">
                {article.featured_image && (
                  <Link href={`/article/${article.slug}`} className="block image-zoom">
                    <div className="relative h-52 w-full">
                      <Image
                        src={article.featured_image}
                        alt={article.title_burmese}
                        fill
                        className="object-cover"
                      />
                    </div>
                  </Link>
                )}
                <div className="p-6">
                  <h2 className="text-lg font-bold text-gray-900 mb-3 font-burmese line-clamp-3 leading-snug">
                    <Link href={`/article/${article.slug}`} className="hover:text-primary transition-colors">
                      {article.title_burmese}
                    </Link>
                  </h2>
                  <p className="text-gray-600 mb-4 font-burmese line-clamp-3 text-sm leading-relaxed">
                    {article.excerpt_burmese}
                  </p>
                  <div className="flex items-center justify-between text-sm text-gray-500 pt-4 border-t border-gray-100">
                    <span className="font-burmese">{article.reading_time} မိနစ်</span>
                    <span>{article.view_count} views</span>
                  </div>
                </div>
              </article>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}

export async function generateMetadata({ params }: { params: { slug: string } }) {
  const category = await getCategory(params.slug)
  if (!category) return { title: 'Category Not Found' }
  return {
    title: `${category.name_burmese} - Burmddit`,
    description: `${category.name_burmese} နှင့် ပတ်သက်သော နောက်ဆုံးရ AI ဆောင်းပါးများ`,
  }
}
