import Link from 'next/link';
import Image from 'next/image';
import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';

export const metadata = {
  title: 'บทความ',
  description: 'บทความความรู้เกี่ยวกับวัสดุท่อ อุปกรณ์ระบบท่อ และเทคนิคการติดตั้ง',
};

function getBlogPosts() {
  const blogDir = path.join(process.cwd(), 'src/content/blog');
  const files = fs.readdirSync(blogDir).filter(f => f.endsWith('.md'));
  
  return files.map(filename => {
    const filePath = path.join(blogDir, filename);
    const fileContent = fs.readFileSync(filePath, 'utf-8');
    const { data } = matter(fileContent);
    
    // Support both 'category' and 'categories' field names
    const category = data.category || (Array.isArray(data.categories) ? data.categories[0] : 'ทั่วไป');
    // Support both 'image' and 'featuredImage' field names
    const image = data.image || data.featuredImage || '/images/2021/03/ppr-pipe_000C.jpg';
    
    return {
      slug: filename.replace('.md', ''),
      title: data.title || 'ไม่มีชื่อ',
      excerpt: data.excerpt || '',
      date: data.date || new Date().toISOString(),
      author: data.author || 'ดีลพลัสเทค',
      category,
      image,
    };
  }).sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
}

export default function BlogPage() {
  const posts = getBlogPosts();

  return (
    <div className="pt-32 pb-16">
      <div className="container mx-auto px-4">
        {/* Hero */}
        <div className="text-center mb-12">
          <h1 className="text-4xl md:text-5xl font-bold text-secondary-900 mb-4">
            บทความ<span className="text-primary-600">ความรู้</span>
          </h1>
          <p className="text-xl text-secondary-600 max-w-2xl mx-auto">
            บทความความรู้เกี่ยวกับวัสดุท่อ อุปกรณ์ระบบท่อ และเทคนิคการติดตั้ง
          </p>
        </div>

        {/* Blog Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
          {posts.map((post) => (
            <Link
              key={post.slug}
              href={`/blog/${post.slug}`}
              className="card group"
            >
              <div className="relative aspect-video bg-secondary-100">
                <Image
                  src={post.image}
                  alt={post.title}
                  fill
                  className="object-cover group-hover:scale-105 transition-transform duration-300"
                />
                <div className="absolute top-4 left-4">
                  <span className="industrial-badge">{post.category}</span>
                </div>
              </div>
              <div className="p-6">
                <time className="text-sm text-secondary-500">
                  {new Date(post.date).toLocaleDateString('th-TH', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric',
                  })}
                </time>
                <h3 className="text-xl font-bold text-secondary-900 mt-2 group-hover:text-primary-600 transition-colors">
                  {post.title}
                </h3>
                <p className="text-secondary-600 text-sm mt-2 line-clamp-2">
                  {post.excerpt}
                </p>
                <span className="text-primary-600 font-semibold flex items-center gap-2 mt-4">
                  อ่านเพิ่มเติม
                  <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                  </svg>
                </span>
              </div>
            </Link>
          ))}
        </div>

        {posts.length === 0 && (
          <div className="text-center py-12">
            <p className="text-secondary-600">ยังไม่มีบทความในขณะนี้</p>
          </div>
        )}
      </div>
    </div>
  );
}
