---
import { getCollection } from 'astro:content';
import BaseLayout from '../../layouts/BaseLayout.astro';
import SEO from '../../components/SEO.astro';

const allPosts = await getCollection('blog', ({ data }) => !data.draft);
const sortedPosts = allPosts.sort((a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf());

const categories = ['All', 'Web Development', 'Mobile Apps', 'AI/ML', 'Cloud', 'DevOps', 'Security'] as const;

function getReadingTime(content: string): number {
  const wordsPerMinute = 200;
  const words = content.split(/\s+/).length;
  return Math.ceil(words / wordsPerMinute);
}

function formatDate(date: Date): string {
  return date.toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  });
}
---

<BaseLayout
  title="Software Development & Technology Insights"
  description="Insights on web development, ERP, cloud migration, AI, and government IT from the WorkRoot engineering team — field notes from real, large-scale deployments."
>
  <SEO
    slot="head"
    type="WebPage"
    breadcrumbs={[
      { name: 'Home', url: '/' },
      { name: 'Blog', url: '/blog' }
    ]}
  />
  <!-- Hero Section -->
  <section class="relative bg-gradient-to-br from-secondary-900 via-secondary-800 to-secondary-900 py-20 overflow-hidden">
    <div class="absolute inset-0 opacity-30">
      <div class="absolute top-20 left-10 w-72 h-72 bg-primary-500 rounded-full blur-[120px]"></div>
      <div class="absolute bottom-10 right-20 w-96 h-96 bg-accent-500 rounded-full blur-[150px]"></div>
    </div>

    <div class="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
      <h1 class="text-4xl md:text-5xl lg:text-6xl font-bold text-white mb-6">
        Our <span class="text-transparent bg-clip-text bg-gradient-to-r from-primary-400 to-accent-400">Blog</span>
      </h1>
      <p class="text-xl text-secondary-300 max-w-3xl mx-auto">
        Insights, tutorials, and industry trends from our team of experts. Stay ahead with the latest in technology.
      </p>
    </div>
  </section>

  <!-- Category Filter -->
  <section class="bg-secondary-50 dark:bg-secondary-900 border-b border-secondary-200 dark:border-secondary-700">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
      <div class="flex flex-wrap gap-2 justify-center" role="tablist" aria-label="Filter posts by category">
        {categories.map((category, index) => (
          <button
            type="button"
            role="tab"
            aria-selected={index === 0 ? 'true' : 'false'}
            data-category={category}
            class:list={[
              'filter-btn px-4 py-2 rounded-full text-sm font-medium transition-all duration-200',
              index === 0
                ? 'bg-primary-500 text-white'
                : 'bg-white dark:bg-secondary-800 text-secondary-600 dark:text-secondary-400 hover:bg-secondary-100 dark:hover:bg-secondary-700 border border-secondary-200 dark:border-secondary-600',
            ]}
          >
            {category}
          </button>
        ))}
      </div>
    </div>
  </section>

  <!-- Blog Posts Grid -->
  <section class="py-16 bg-white dark:bg-secondary-900">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8" id="posts-grid">
        {sortedPosts.map((post) => {
          const readingTime = getReadingTime(post.body);
          return (
            <article
              class="post-card group bg-white dark:bg-secondary-800 rounded-2xl shadow-lg overflow-hidden border border-secondary-100 dark:border-secondary-700 hover:shadow-xl hover:border-primary-200 dark:hover:border-primary-500 transition-all duration-300"
              data-category={post.data.category}
            >
              <!-- Post Image -->
              <a href={`/blog/${post.slug}`} class="block aspect-video overflow-hidden bg-secondary-200 dark:bg-secondary-700">
                {post.data.heroImage ? (
                  <img
                    src={post.data.heroImage}
                    alt={post.data.title}
                    width="640"
                    height="360"
                    class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                    loading="lazy"
                    decoding="async"
                  />
                ) : (
                  <div class="w-full h-full flex items-center justify-center bg-gradient-to-br from-primary-500 to-primary-700">
                    <svg class="w-16 h-16 text-white/50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M19 20H5a2 2 0 01-2-2V6a2 2 0 012-2h10a2 2 0 012 2v1m2 13a2 2 0 01-2-2V7m2 13a2 2 0 002-2V9a2 2 0 00-2-2h-2m-4-3H9M7 16h6M7 8h6v4H7V8z" />
                    </svg>
                  </div>
                )}
              </a>

              <!-- Post Content -->
              <div class="p-6">
                <!-- Category & Reading Time -->
                <div class="flex items-center gap-3 mb-3">
                  <span class="px-3 py-1 bg-primary-50 dark:bg-primary-900/30 text-primary-700 dark:text-primary-300 text-xs font-semibold rounded-full">
                    {post.data.category}
                  </span>
                  <span class="text-secondary-400 dark:text-secondary-500 text-sm flex items-center gap-1">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    {readingTime} min read
                  </span>
                </div>

                <!-- Title -->
                <h2 class="text-xl font-bold text-secondary-900 dark:text-secondary-100 mb-3 line-clamp-2 group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors">
                  <a href={`/blog/${post.slug}`}>{post.data.title}</a>
                </h2>

                <!-- Description -->
                <p class="text-secondary-600 dark:text-secondary-400 text-sm mb-4 line-clamp-3">
                  {post.data.description}
                </p>

                <!-- Tags -->
                <div class="flex flex-wrap gap-2 mb-4">
                  {post.data.tags.slice(0, 3).map((tag) => (
                    <span class="text-xs text-secondary-500 dark:text-secondary-400 bg-secondary-100 dark:bg-secondary-700 px-2 py-1 rounded">
                      #{tag}
                    </span>
                  ))}
                </div>

                <!-- Author & Date -->
                <div class="flex items-center justify-between pt-4 border-t border-secondary-100 dark:border-secondary-700">
                  <div class="flex items-center gap-2">
                    <div class="w-8 h-8 rounded-full bg-gradient-to-br from-primary-400 to-primary-600 flex items-center justify-center text-white text-sm font-bold">
                      {post.data.author.name.charAt(0)}
                    </div>
                    <span class="text-sm text-secondary-600 dark:text-secondary-400">{post.data.author.name}</span>
                  </div>
                  <time class="text-sm text-secondary-400 dark:text-secondary-500" datetime={post.data.pubDate.toISOString()}>
                    {formatDate(post.data.pubDate)}
                  </time>
                </div>
              </div>
            </article>
          );
        })}
      </div>

      <!-- Empty State -->
      <div id="empty-state" class="hidden text-center py-16">
        <svg class="w-16 h-16 text-secondary-300 dark:text-secondary-600 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M12 2C6.477 2 2 6.477 2 12s4.477 10 10 10 10-4.477 10-10S17.523 2 12 2z" />
        </svg>
        <h3 class="text-xl font-semibold text-secondary-600 dark:text-secondary-400 mb-2">No posts found</h3>
        <p class="text-secondary-400 dark:text-secondary-500">Try selecting a different category.</p>
      </div>
    </div>
  </section>
</BaseLayout>

<script>
  const filterButtons = document.querySelectorAll('.filter-btn');
  const postCards = document.querySelectorAll('.post-card');
  const emptyState = document.getElementById('empty-state');

  filterButtons.forEach((btn) => {
    btn.addEventListener('click', () => {
      const category = btn.getAttribute('data-category');
      const isDark = document.documentElement.classList.contains('dark');

      // Update button states
      filterButtons.forEach((b) => {
        b.classList.remove('bg-primary-500', 'text-white');
        if (isDark) {
          b.classList.add('bg-secondary-800', 'text-secondary-400', 'border', 'border-secondary-600');
          b.classList.remove('bg-white', 'text-secondary-600', 'border-secondary-200');
        } else {
          b.classList.add('bg-white', 'text-secondary-600', 'border', 'border-secondary-200');
          b.classList.remove('bg-secondary-800', 'text-secondary-400', 'border-secondary-600');
        }
        b.setAttribute('aria-selected', 'false');
      });
      btn.classList.remove('bg-white', 'bg-secondary-800', 'text-secondary-600', 'text-secondary-400', 'border', 'border-secondary-200', 'border-secondary-600');
      btn.classList.add('bg-primary-500', 'text-white');
      btn.setAttribute('aria-selected', 'true');

      // Filter posts
      let visibleCount = 0;
      postCards.forEach((card) => {
        const postCategory = card.getAttribute('data-category');
        if (category === 'All' || postCategory === category) {
          card.classList.remove('hidden');
          visibleCount++;
        } else {
          card.classList.add('hidden');
        }
      });

      // Show empty state if no posts
      if (emptyState) {
        emptyState.classList.toggle('hidden', visibleCount > 0);
      }
    });
  });
</script>
