---
import BlogLayout from '../../layouts/BlogLayout.astro';
import BlogList from '../../components/blog/BlogList.astro';
import CategoryCard from '../../components/blog/CategoryCard.astro';
import TagCard from '../../components/blog/TagCard.astro';
import Container from '../../components/ui/Container.astro';
import { type BlogPost } from '@/types';
import { type Lang } from '@/types/i18n';
import { defaultLang } from '@/i18n/ui';
import { sortPostsByDate } from '@/utils/blog-utils';

const lang = Astro.currentLocale as Lang || defaultLang;

const allPosts = await import.meta.glob('./posts/*.md', { eager: true });

const blogPosts: BlogPost[] = Object.values(allPosts).map((post: any) => {
  const slug = post.url?.split('/').filter(Boolean).pop() || '';
  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,
    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',
  };
});

const sortedBlogPosts = sortPostsByDate(blogPosts);
---

<BlogLayout title="Writing - Joey Z." description="Engineering notes on architecture, delivery, and AI-assisted development workflows.">
  <main class="min-h-screen">
    <Container className="pt-24 pb-12">
      <div class="text-center mb-16">
        <h1 class="text-5xl md:text-6xl font-bold bg-gradient-to-r from-foreground via-primary to-primary dark:from-foreground dark:via-blue-200 dark:to-orange-300 bg-clip-text text-transparent mb-6">
          <span class="text-primary">Writing</span>
        </h1>
        <p class="text-xl text-muted-foreground page-content-main">
          Engineering notes on architecture, delivery, and AI-assisted development workflows.
        </p>
      </div>
    </Container>

    <Container className="pb-20">
      <div class="grid grid-cols-1 lg:grid-cols-4 gap-8">
        <div class="lg:col-span-1 space-y-8">
          <CategoryCard lang="en" />
          <TagCard lang="en" />
        </div>

        <div class="lg:col-span-3">
          <BlogList posts={sortedBlogPosts} lang="en" />
        </div>
      </div>
    </Container>
  </main>
</BlogLayout>

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