---
import { type BlogPost } from '@/types';
import { type Lang } from '@/types/i18n';
import { getBlogBaseUrl, filterPostsByCategory, filterPostsByTag, sortPostsByDate } from '@/utils/blog-utils';

interface Props {
  posts?: BlogPost[];
  lang: Lang;
  baseUrl?: string;
  category?: string;
  tag?: string;
}

// Get component props
const { lang, baseUrl, category, tag, posts: providedPosts } = Astro.props;

// If posts are not provided, read from file system
let posts: BlogPost[] = [];

if (providedPosts) {
  // Use provided posts
  posts = providedPosts;
} else {
  // Read blog posts based on current language
  const postsGlob = {
    en: await import.meta.glob('../../pages/blog/posts/*.md', { eager: true }),
    zh: await import.meta.glob('../../pages/zh/blog/posts/*.md', { eager: true })
  };
  
  // Get posts for current language
  const allPosts = lang === 'zh' ? Object.values(postsGlob.zh) : Object.values(postsGlob.en);
  
  // Process blog post data
  posts = allPosts.map((post: any) => {
    const slug = post.url?.split('/').filter(Boolean).pop() || '';
    
    // Default image if not specified in frontmatter
    const defaultImage = "https://images.unsplash.com/photo-1516321318423-f06f85e504b3?w=400&h=250&fit=crop&crop=center";
    
    return {
      title: post.frontmatter.title,
      description: post.frontmatter.description || '',
      image: post.frontmatter.image || defaultImage,
      slug: slug,
      tags: post.frontmatter.tags || [],
      tagId: post.frontmatter.tagId || [],
      category: Array.isArray(post.frontmatter.category) ? post.frontmatter.category : post.frontmatter.category ? [post.frontmatter.category] : [],
      categoryId: Array.isArray(post.frontmatter.categoryId) ? post.frontmatter.categoryId : post.frontmatter.categoryId ? [post.frontmatter.categoryId] : [],
      date: post.frontmatter.date || post.frontmatter.pubDate || '',
      readTime: post.frontmatter.readTime || post.frontmatter.readingTime || '5 min read',
    };
  });
  
  // Sort posts by date
  posts = sortPostsByDate(posts);
}

// Filter posts by category if specified
if (category) {
  posts = filterPostsByCategory(posts, category);
}

// Filter posts by tag if specified
if (tag) {
  posts = filterPostsByTag(posts, tag);
}

// 调整基础URL
const postBaseUrl = lang === 'zh' ? '/zh/blog/posts/' : '/blog/posts/';

// 获取本地化的"阅读更多"文本
const readMoreText = lang === 'zh' ? '阅读更多' : 'Read More';
---

<div class="space-y-6">
  {posts.length > 0 ? (
    posts.map((post, index) => (
      <article class="group">
        <div class="bg-card/60 backdrop-blur-md rounded-2xl overflow-hidden border border-border/40 hover:border-primary/50 transition-all duration-300 hover:transform hover:scale-[1.02] hover:shadow-xl hover:shadow-primary/5">
          <div class="flex flex-col md:flex-row">
            {/* Featured Image */}
            <div class="relative overflow-hidden md:w-80 md:flex-shrink-0">
              <img
                src={post.image}
                alt={post.title}
                loading="lazy"
                decoding="async"
                class="w-full h-48 md:h-full object-cover group-hover:scale-110 transition-transform duration-300"
              />
              <div class="absolute inset-0 bg-gradient-to-t md:bg-gradient-to-r from-background/50 to-transparent"></div>
            </div>
            
            {/* Content */}
            <div class="p-6 flex-1 flex flex-col justify-between">
              <div>
                <h2 class="text-xl font-bold text-card-foreground mb-3 group-hover:text-primary transition-colors duration-200">
                  <a href={`${postBaseUrl}${post.slug}`} data-astro-reload>
                    {post.title}
                  </a>
                </h2>
                
                <p class="text-muted-foreground mb-4 line-clamp-3">
                  {post.description}
                </p>
                
                {/* Tags */}
                <div class="flex flex-wrap gap-2 mb-4">
                  {post.tags.map((tag, tagIndex) => {
                    // 使用 tagId 如果存在，否则使用 tag 本身
                    const tagRoute = post.tagId && Array.isArray(post.tagId) && tagIndex < post.tagId.length
                      ? post.tagId[tagIndex]
                      : tag.toLowerCase();
                    
                    return (
                      <a 
                        href={`/${lang === 'en' ? '' : 'zh/'}blog/tags/${encodeURIComponent(tagRoute)}`}
                        class="px-2 py-1 text-xs bg-muted text-muted-foreground rounded-full hover:bg-muted/80 transition-colors"
                      >
                        # {tag}
                      </a>
                    );
                  })}
                </div>
              </div>
              
              {/* Meta Info */}
              <div class="flex items-center justify-between text-sm text-muted-foreground">
                <div class="flex items-center space-x-4">
                  <span class="flex items-center">
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 002 2v12a2 2 0 002 2z"></path>
                    </svg>
                    {post.date}
                  </span>
                  <span>{post.readTime}</span>
                </div>
                
                <a 
                  href={`${postBaseUrl}${post.slug}`}
                  data-astro-reload
                  class="text-primary hover:text-primary font-medium flex items-center group"
                >
                  {readMoreText}
                  <svg class="w-4 h-4 ml-1 group-hover:translate-x-1 transition-transform duration-200" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 8l4 4m0 0l-4 4m4-4H3"></path>
                  </svg>
                </a>
              </div>
            </div>
          </div>
        </div>
      </article>
    ))
  ) : (
    <div class="flex flex-col items-center justify-center py-20 text-center bg-card/30 backdrop-blur-sm rounded-2xl border border-border p-8 min-h-[300px]">
      <svg class="w-16 h-16 text-primary/70 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"></path>
      </svg>
      <p class="text-xl text-muted-foreground mb-4">
        {lang === 'zh' ? '暂无博客文章' : 'No blog posts yet'}
      </p>
      <p class="text-sm text-muted-foreground/70 mb-6 max-w-md">
        {lang === 'zh' ? '我们正在努力创作新的内容，请稍后再来查看。' : 'We are working on creating new content. Please check back later.'}
      </p>
      <a 
        href={`/${lang === 'en' ? '' : 'zh/'}`}
        class="px-4 py-2 bg-primary/10 hover:bg-primary/20 text-primary rounded-full transition-colors duration-200 flex items-center"
      >
        <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
        </svg>
        {lang === 'zh' ? '返回首页' : 'Back to Home'}
      </a>
    </div>
  )}
</div>

<style>
  .line-clamp-3 {
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
</style>
