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

// Required getStaticPaths function for dynamic routes
export async function getStaticPaths() {
  try {
    // Get posts from the posts collection
    const allPosts = await getCollection('posts', ({ data }) => {
      return import.meta.env.PROD ? !data.draft : true;
    });
    
    return allPosts.map(post => ({
      params: { slug: post.slug },
      props: { post, allPosts },
    }));
  } catch (error) {
    console.error('Error fetching posts:', error);
    // Return empty array if collection doesn't exist
    return [];
  }
}

// Get the post and all posts from props
const { post, allPosts } = 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 '';
  }
};

// Find related posts by tags
const getRelatedPosts = (currentPost, allPosts, maxPosts = 3) => {
  if (!currentPost || !allPosts) return [];
  
  // Get current post tags
  const postTags = currentPost.data.tags || [];
  
  // If no tags, just return recent posts
  if (postTags.length === 0) {
    return allPosts
      .filter(p => p.slug !== currentPost.slug && !p.data.draft)
      .sort((a, b) => {
        const dateA = a.data.pubDate ? new Date(a.data.pubDate) : new Date(0);
        const dateB = b.data.pubDate ? new Date(b.data.pubDate) : new Date(0);
        return dateB.getTime() - dateA.getTime();
      })
      .slice(0, maxPosts);
  }
  
  // Score posts by matching tags
  const scoredPosts = allPosts
    .filter(p => p.slug !== currentPost.slug && !p.data.draft)
    .map(p => {
      const pTags = p.data.tags || [];
      const matchCount = pTags.filter(tag => postTags.includes(tag)).length;
      return { post: p, score: matchCount };
    })
    .filter(item => item.score > 0)
    .sort((a, b) => {
      // Sort by score first
      if (b.score !== a.score) return b.score - a.score;
      
      // If scores are equal, sort by date
      const dateA = a.post.data.pubDate ? new Date(a.post.data.pubDate) : new Date(0);
      const dateB = b.post.data.pubDate ? new Date(b.post.data.pubDate) : new Date(0);
      return dateB.getTime() - dateA.getTime();
    })
    .slice(0, maxPosts);
  
  // If we don't have enough related posts by tags, add recent posts
  if (scoredPosts.length < maxPosts) {
    const recentPosts = allPosts
      .filter(p => {
        return p.slug !== currentPost.slug && 
               !p.data.draft && 
               !scoredPosts.some(sp => sp.post.slug === p.slug);
      })
      .sort((a, b) => {
        const dateA = a.data.pubDate ? new Date(a.data.pubDate) : new Date(0);
        const dateB = b.data.pubDate ? new Date(b.data.pubDate) : new Date(0);
        return dateB.getTime() - dateA.getTime();
      })
      .slice(0, maxPosts - scoredPosts.length);
    
    return [...scoredPosts.map(sp => sp.post), ...recentPosts];
  }
  
  return scoredPosts.map(sp => sp.post);
};

// Get related posts
const relatedPosts = getRelatedPosts(post, allPosts);

// Check for explicitly related posts in frontmatter
const explicitRelatedPosts = post.data.related_posts 
  ? allPosts.filter(p => post.data.related_posts.includes(p.slug))
  : [];

// Combine explicit and tag-based related posts, with explicit ones first
const combinedRelatedPosts = [
  ...explicitRelatedPosts,
  ...relatedPosts.filter(p => !explicitRelatedPosts.some(ep => ep.slug === p.slug))
].slice(0, 3);

// 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}</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 sidebar-block">
            <h3>Tags</h3>
            <div class="tags">
              {post.data.tags.map(tag => (
                <a href={`/tag/${tag}`} class="tag">{tag}</a>
              ))}
            </div>
          </div>
        )}
        
        {post.data.category && (
          <div class="category-section sidebar-block">
            <h3>Category</h3>
            <a href={`/categories/${post.data.category}`} class="category">
              {post.data.category}
            </a>
          </div>
        )}
        
        {post.data.categories && post.data.categories.length > 0 && (
          <div class="categories-section sidebar-block">
            <h3>Categories</h3>
            <div class="categories">
              {post.data.categories.map(category => (
                <a href={`/categories/${category}`} class="category">
                  {category}
                </a>
              ))}
            </div>
          </div>
        )}
        
        {combinedRelatedPosts.length > 0 && (
          <div class="related-posts-section sidebar-block">
            <h3>Related Articles</h3>
            <ul class="related-posts">
              {combinedRelatedPosts.map(relatedPost => (
                <li>
                  <a href={`/posts/${relatedPost.slug}/`} class="related-post">
                    <div class="related-post-title">{relatedPost.data.title}</div>
                    <div class="related-post-meta">
                      <span class="related-post-date">{formatDate(relatedPost.data.pubDate)}</span>
                    </div>
                  </a>
                </li>
              ))}
            </ul>
          </div>
        )}
      </aside>
    </div>
    
    <div class="post-navigation">
      <a href="/blog" class="back-to-blog">
        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <line x1="19" y1="12" x2="5" y2="12"></line>
          <polyline points="12 19 5 12 12 5"></polyline>
        </svg>
        Back to Blog
      </a>
    </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;
  }
  
  .sidebar-block {
    background: var(--card-bg);
    border-radius: 12px;
    padding: 1.5rem;
    border: 1px solid var(--border-primary);
  }
  
  .sidebar-block 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(16, 185, 129, 0.1);
    border-radius: 20px;
    color: #10B981;
    font-size: var(--font-size-xs, 0.75rem);
    text-decoration: none;
    transition: all 0.2s ease;
  }
  
  .tag:hover {
    background: rgba(16, 185, 129, 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);
  }
  
  /* Related Posts */
  .related-posts {
    list-style: none;
    padding: 0;
    margin: 0;
  }
  
  .related-posts li {
    margin-bottom: 1rem;
  }
  
  .related-posts li:last-child {
    margin-bottom: 0;
  }
  
  .related-post {
    display: block;
    padding: 0.75rem;
    border-radius: 8px;
    border: 1px solid var(--border-primary);
    text-decoration: none;
    transition: all 0.2s ease;
  }
  
  .related-post:hover {
    background: rgba(6, 182, 212, 0.05);
    border-color: var(--accent-primary);
    transform: translateY(-2px);
  }
  
  .related-post-title {
    color: var(--text-primary);
    font-size: 0.9rem;
    margin-bottom: 0.5rem;
    font-weight: 500;
  }
  
  .related-post-meta {
    font-size: 0.75rem;
    color: var(--text-tertiary);
    font-family: var(--font-mono);
  }

  /* Post Navigation */
  .post-navigation {
    margin-top: 3rem;
    display: flex;
    justify-content: center;
  }
  
  .back-to-blog {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    background: var(--card-bg);
    border: 1px solid var(--border-primary);
    padding: 0.75rem 1.5rem;
    border-radius: 30px;
    color: var(--text-primary);
    text-decoration: none;
    font-weight: 500;
    transition: all 0.2s ease;
  }
  
  .back-to-blog:hover {
    border-color: var(--accent-primary);
    background: var(--bg-tertiary);
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
  }
  
  /* Content Styling */
  .post-body {
    font-size: 1.05rem;
    line-height: 1.7;
    color: var(--text-primary);
  }
  
  .post-body h2 {
    font-size: 1.8rem;
    margin: 2rem 0 1rem;
    color: var(--text-primary);
  }
  
  .post-body h3 {
    font-size: 1.4rem;
    margin: 1.75rem 0 0.75rem;
    color: var(--text-primary);
  }
  
  .post-body p {
    margin-bottom: 1.25rem;
  }
  
  .post-body a {
    color: var(--accent-primary);
    text-decoration: none;
    border-bottom: 1px dashed var(--accent-primary);
    transition: all 0.2s ease;
  }
  
  .post-body a:hover {
    color: var(--accent-secondary);
    border-bottom-style: solid;
  }
  
  .post-body ul, .post-body ol {
    margin: 1rem 0 1.5rem 1.5rem;
  }
  
  .post-body li {
    margin-bottom: 0.5rem;
  }
  
  .post-body blockquote {
    margin: 1.5rem 0;
    padding: 1rem 1.5rem;
    border-left: 4px solid var(--accent-primary);
    background: rgba(6, 182, 212, 0.05);
    border-radius: 0 8px 8px 0;
    color: var(--text-secondary);
    font-style: italic;
  }
  
  .post-body code {
    font-family: var(--font-mono);
    background: rgba(15, 23, 42, 0.3);
    padding: 0.2rem 0.4rem;
    border-radius: 4px;
    font-size: 0.9em;
  }
  
  .post-body pre {
    background: rgba(15, 23, 42, 0.3);
    padding: 1rem;
    border-radius: 8px;
    overflow-x: auto;
    margin: 1.5rem 0;
    border: 1px solid var(--border-primary);
  }
  
  .post-body pre code {
    background: transparent;
    padding: 0;
    font-size: 0.9em;
    color: var(--text-primary);
  }
  
  .post-body img {
    max-width: 100%;
    height: auto;
    border-radius: 8px;
    margin: 1.5rem 0;
  }
  
  .post-body table {
    width: 100%;
    border-collapse: collapse;
    margin: 1.5rem 0;
  }
  
  .post-body th, .post-body td {
    border: 1px solid var(--border-primary);
    padding: 0.75rem;
  }
  
  .post-body th {
    background: rgba(15, 23, 42, 0.3);
    font-weight: 600;
    text-align: left;
  }
  
  /* Responsive Adjustments */
  @media (max-width: 1024px) {
    .post-header h1 {
      font-size: var(--font-size-3xl, 1.875rem);
    }
  }
  
  @media (max-width: 768px) {
    .post-content {
      grid-template-columns: 1fr;
    }
    
    .post-header h1 {
      font-size: var(--font-size-2xl, 1.5rem);
    }
    
    .post-body {
      padding: 1.5rem;
    }
  }
</style>

<script>
  // Add functionality to handle post sharing and tag clicks
  document.addEventListener('DOMContentLoaded', () => {
    // Add click functionality to tags
    document.querySelectorAll('.tag').forEach(tag => {
      tag.addEventListener('click', (e) => {
        // Already links, no need for additional JS
      });
    });
    
    // Add scroll-to-top button when scrolling down
    const scrollToTop = document.createElement('button');
    scrollToTop.className = 'scroll-to-top';
    scrollToTop.innerHTML = `
      <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <polyline points="18 15 12 9 6 15"></polyline>
      </svg>
    `;
    document.body.appendChild(scrollToTop);
    
    // Show/hide scroll-to-top button
    window.addEventListener('scroll', () => {
      if (window.scrollY > 500) {
        scrollToTop.classList.add('visible');
      } else {
        scrollToTop.classList.remove('visible');
      }
    });
    
    // Scroll to top when clicked
    scrollToTop.addEventListener('click', () => {
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      });
    });
  });
</script>

<style is:global>
  /* Scroll to top button */
  .scroll-to-top {
    position: fixed;
    bottom: 30px;
    right: 30px;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background: linear-gradient(135deg, var(--accent-primary), var(--accent-secondary));
    color: white;
    border: none;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    visibility: hidden;
    transition: all 0.3s ease;
    transform: translateY(20px);
    z-index: 100;
  }
  
  .scroll-to-top.visible {
    opacity: 1;
    visibility: visible;
    transform: translateY(0);
  }
  
  .scroll-to-top:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
  }
  
  @media (max-width: 768px) {
    .scroll-to-top {
      width: 40px;
      height: 40px;
      bottom: 20px;
      right: 20px;
    }
    
    .scroll-to-top svg {
      width: 20px;
      height: 20px;
    }
  }
</style>