---
/**
 * RelatedPosts - Related articles section component
 * Displays 3-4 related posts from the same category
 */

interface Category {
  id: string
  title: string
  slug: string
  backgroundColor?: string
  textColor?: string
}

interface PostImage {
  url: string
  alt?: string
}

interface Post {
  id: string
  title: string
  slug: string
  heroImage?: PostImage | null
  excerpt?: string | null
  categories?: Category[] | null
  publishedAt?: string | null
}

interface Props {
  posts: Post[]
  title?: string
}

const { posts, title = '相關文章' } = Astro.props

// Only display if there are related posts
// Component will render empty fragment if no posts
---

{
  posts && posts.length > 0 && (
    <section class="py-16 md:py-12 px-6 bg-[var(--color-gray-50)]" aria-labelledby="related-posts-heading">
      <div class="max-w-[1200px] mx-auto">
        <h2 id="related-posts-heading" class="font-['Noto_Sans_TC'] text-[1.75rem] md:text-2xl font-bold text-[var(--color-enchunblue)] text-center mb-10 md:mb-8">
          {title}
        </h2>

        <div class="grid grid-cols-1 md:grid-cols-[repeat(auto-fit,minmax(280px,1fr))] gap-6 md:gap-4">
          {
            posts.slice(0, 4).map((post) => (
              <a href={`/blog/${post.slug}`} class="flex flex-col bg-white rounded-xl overflow-hidden shadow-sm hover:shadow-lg transition-all duration-300 no-underline text-inherit hover:-translate-y-1 group">
                <!-- Post Image -->
                <div class="aspect-video overflow-hidden bg-[var(--color-gray-200)]">
                  <img
                    src={post.heroImage?.url || '/placeholder-blog.jpg'}
                    alt={post.heroImage?.alt || post.title}
                    loading="lazy"
                    class="w-full h-full object-cover transition-transform duration-400 group-hover:scale-105"
                    width="400"
                    height="225"
                  />
                </div>

                <!-- Post Content -->
                <div class="p-5 flex flex-col gap-3">
                  <!-- Category Badge -->
                  {
                    post.categories && post.categories[0] && (
                      <span
                        class="inline-block px-3 py-1 rounded-2xl text-xs font-semibold self-start"
                        style={`background-color: ${post.categories[0].backgroundColor || 'var(--color-enchunblue)'}; color: ${post.categories[0].textColor || '#fff'}`}
                      >
                        {post.categories[0].title}
                      </span>
                  )}

                  <!-- Post Title -->
                  <h3 class="font-['Noto_Sans_TC'] text-[1.0625rem] font-semibold text-[var(--color-dark-blue)] leading-snug line-clamp-2">
                    {post.title}
                  </h3>
                </div>
              </a>
            ))
          }
        </div>
      </div>
    </section>
  )
}
