---
// src/pages/blog/[slug].astro
import { getCollection } from 'astro:content';
import BaseLayout from '../../layouts/BaseLayout.astro';

// Required getStaticPaths function for dynamic routes
export async function getStaticPaths() {
  try {
    // Try first from 'blog' collection (auto-generated)
    let allPosts = [];
    try {
      allPosts = await getCollection('blog', ({ data }) => {
        return import.meta.env.PROD ? !data.draft : true;
      });
    } catch (e) {
      console.log('Blog collection not found, trying posts');
    }
    
    // If that fails or is empty, try 'posts' collection
    if (allPosts.length === 0) {
      allPosts = await getCollection('posts', ({ data }) => {
        return import.meta.env.PROD ? !data.draft : true;
      });
    }
    
    return allPosts.map(post => ({
      params: { slug: post.slug },
      props: { post },
    }));
  } catch (error) {
    console.error('Error fetching posts:', error);
    // Return empty array if both collections don't exist or are empty
    return [];
  }
}

// Get the post from props
const { post } = Astro.props;

// Format date helper
const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  return d.toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });
};

// Generate datetime attribute safely
const getISODate = (date) => {
  if (!date) return '';
  // Handle various date formats
  try {
    // If already a Date object
    if (date instanceof Date) {
      return date.toISOString();
    }
    // If it's a string or number, convert to Date
    return new Date(date).toISOString();
  } catch (error) {
    // Fallback if date is invalid
    console.error('Invalid date format:', date);
    return '';
  }
};

// Get the Content component for rendering markdown
const { Content } = await post.render();
---

<BaseLayout title={post.data.title} description={post.data.description || ''}>
  <article class="container blog-post">
    <header class="post-header">
      <h1>{post.data.title}</h1>
      <div class="post-meta">
        {post.data.pubDate && <time datetime={getISODate(post.data.pubDate)}>{formatDate(post.data.pubDate)}</time>}
        {post.data.updatedDate && <div class="updated-date">Updated: {formatDate(post.data.updatedDate)}</div>}
        {post.data.readTime && <div class="read-time">{post.data.readTime} read</div>}
        {post.data.author && <div class="author">By {post.data.author}</div>}
      </div>
    </header>
    
    {post.data.heroImage && (
      <div class="hero-image">
        <img src={post.data.heroImage} alt={post.data.title} />
      </div>
    )}
    
    <div class="post-content">
      <div class="post-body">
        <Content />
      </div>
      
      <aside class="post-sidebar">
        {post.data.tags && post.data.tags.length > 0 && (
          <div class="tags-section">
            <h3>Tags</h3>
            <div class="tags">
              {post.data.tags.map(tag => (
                <a href={`/tag/${tag}`} class="tag">{tag}</a>
              ))}
            </div>
          </div>
        )}
        
        <div class="category-section">
          <h3>Category</h3>
          <a href={`/categories/${post.data.category || 'Uncategorized'}`} class="category">
            {post.data.category || 'Uncategorized'}
          </a>
        </div>
        
        {post.data.categories && post.data.categories.length > 0 && (
          <div class="categories-section">
            <h3>Categories</h3>
            <div class="categories">
              {post.data.categories.map(category => (
                <a href={`/categories/${category}`} class="category">
                  {category}
                </a>
              ))}
            </div>
          </div>
        )}
      </aside>
    </div>
  </article>
</BaseLayout>

<style>
  .container {
    max-width: 1280px;
    margin: 0 auto;
    padding: 0 var(--container-padding, 1.5rem);
  }
  
  .blog-post {
    padding: 2rem 0;
  }
  
  .post-header {
    margin-bottom: 2rem;
    text-align: center;
  }
  
  .post-header h1 {
    font-size: var(--font-size-4xl, 2.25rem);
    margin-bottom: 1rem;
    line-height: 1.2;
  }
  
  .post-meta {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 1rem;
    color: var(--text-tertiary);
    font-size: var(--font-size-sm, 0.875rem);
    font-family: var(--font-mono);
  }
  
  .hero-image {
    margin-bottom: 2rem;
    border-radius: 12px;
    overflow: hidden;
    border: 1px solid var(--border-primary);
  }
  
  .hero-image img {
    width: 100%;
    height: auto;
    display: block;
  }
  
  .post-content {
    display: grid;
    grid-template-columns: 3fr 1fr;
    gap: 2rem;
  }
  
  .post-body {
    background: var(--card-bg);
    border-radius: 12px;
    padding: 2rem;
    border: 1px solid var(--border-primary);
  }
  
  .post-sidebar {
    display: flex;
    flex-direction: column;
    gap: 1.5rem;
  }
  
  .tags-section, .category-section, .categories-section {
    background: var(--card-bg);
    border-radius: 8px;
    padding: 1.5rem;
    border: 1px solid var(--border-primary);
  }
  
  .tags-section h3, .category-section h3, .categories-section h3 {
    font-size: var(--font-size-lg, 1.125rem);
    margin-bottom: 1rem;
    color: var(--text-primary);
  }
  
  .tags {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
  }
  
  .tag {
    display: inline-block;
    padding: 0.25rem 0.75rem;
    background: rgba(56, 189, 248, 0.1);
    border-radius: 20px;
    color: var(--accent-primary);
    font-size: var(--font-size-xs, 0.75rem);
    text-decoration: none;
    transition: all 0.2s ease;
  }
  
  .tag:hover {
    background: rgba(56, 189, 248, 0.2);
    transform: translateY(-2px);
  }
  
  .category, .categories {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
  }
  
  .category {
    display: inline-block;
    padding: 0.5rem 1rem;
    background: linear-gradient(90deg, var(--accent-primary), var(--accent-secondary));
    border-radius: 20px;
    color: var(--bg-primary);
    font-size: var(--font-size-sm, 0.875rem);
    text-decoration: none;
    font-weight: 500;
    transition: all 0.3s ease;
    text-align: center;
  }
  
  .category:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  }
  
  @media (max-width: 768px) {
    .post-content {
      grid-template-columns: 1fr;
    }
    
    .post-header h1 {
      font-size: var(--font-size-2xl, 1.5rem);
    }
  }
</style>