---
// src/pages/tag/[tag].astro
// Dynamic route for tag pages with enhanced visualization

import BaseLayout from '../../layouts/BaseLayout.astro';
import Header from '../../components/Header.astro';
import Footer from '../../components/Footer.astro';
import KnowledgeGraph from '../../components/KnowledgeGraph.astro';
import { getCollection } from 'astro:content';

export async function getStaticPaths() {
  try {
    // Get all posts
    const allPosts = await getCollection('posts', ({ data }) => {
      // Exclude draft posts in production
      return import.meta.env.PROD ? !data.draft : true;
    });
    
    // Extract all unique tags
    const allTags = [...new Set(allPosts.flatMap(post => post.data.tags || []))];
    
    // Create a path for each tag
    return allTags.map((tag) => {
      // Filter posts to only those with this tag
      const filteredPosts = allPosts.filter((post) => 
        (post.data.tags || []).includes(tag)
      );
      
      return {
        params: { tag },
        props: { 
          posts: filteredPosts,
          tag,
          allPosts // Pass all posts for knowledge graph
        },
      };
    });
  } catch (error) {
    console.error("Error in getStaticPaths:", error);
    // Return empty array as fallback
    return [];
  }
}

const { tag } = Astro.params;
const { posts, allPosts } = Astro.props;

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

// Sort posts by date (newest first)
const sortedPosts = [...posts].sort((a, b) => {
  const dateA = new Date(a.data.pubDate || 0);
  const dateB = new Date(b.data.pubDate || 0);
  return dateB.getTime() - dateA.getTime();
});

// Prepare Knowledge Graph data
const graphData = {
  nodes: [
    // Add the current tag as a central node
    {
      id: `tag-${tag}`,
      label: tag,
      type: 'tag',
      url: `/tag/${tag}`
    },
    
    // Add posts with this tag
    ...sortedPosts.map(post => ({
      id: post.slug,
      label: post.data.title,
      type: 'post',
      category: post.data.category || 'Uncategorized',
      tags: post.data.tags || [],
      url: `/posts/${post.slug}/`
    })),
    
    // Add related tags (tags that appear alongside this tag in posts)
    ...posts.flatMap(post => 
      (post.data.tags || [])
        .filter(t => t !== tag) // Don't include current tag
        .map(relatedTag => ({
          id: `tag-${relatedTag}`,
          label: relatedTag,
          type: 'tag',
          url: `/tag/${relatedTag}`
        }))
    ).filter((v, i, a) => a.findIndex(t => t.id === v.id) === i) // Deduplicate
  ],
  edges: [
    // Connect posts to the current tag
    ...sortedPosts.map(post => ({
      source: post.slug,
      target: `tag-${tag}`,
      type: 'post-tag',
      strength: 2
    })),
    
    // Connect related tags to their posts
    ...posts.flatMap(post => 
      (post.data.tags || [])
        .filter(t => t !== tag) // Skip current tag
        .map(relatedTag => ({
          source: post.slug,
          target: `tag-${relatedTag}`,
          type: 'post-tag',
          strength: 1
        }))
    )
  ]
};
---

<BaseLayout title={`Posts tagged with "${tag}" | LaForce IT Blog`} description={`Articles and guides related to ${tag}`}>
  <Header slot="header" />
  
  <main class="tag-page-container">
    <section class="tag-hero">
      <div class="container">
        <h1>Posts tagged with <span class="tag-highlight">{tag}</span></h1>
        <p class="tag-description">
          Explore {sortedPosts.length} {sortedPosts.length === 1 ? 'article' : 'articles'} related to {tag}
        </p>
      </div>
    </section>
    
    <section class="tag-content container">
      <div class="knowledge-graph-section">
        <h2>Content Connections</h2>
        <p class="section-description">
          Explore how {tag} relates to other content and tags
        </p>
        
        <div class="graph-wrapper">
          <KnowledgeGraph graphData={graphData} height="400px" initialFilter="all" />
        </div>
      </div>
      
      <div class="posts-section">
        <h2>Articles</h2>
        <div class="posts-grid">
          {sortedPosts.length > 0 ? sortedPosts.map((post) => (
            <article class="post-card">
              <a href={`/posts/${post.slug}/`} class="post-card-link">
                {post.data.heroImage && (
                  <div class="post-image-wrapper">
                    <img 
                      src={post.data.heroImage} 
                      alt="" 
                      class="post-image"
                      width="400"
                      height="225"
                      loading="lazy"
                    />
                  </div>
                )}
                
                <div class="post-content">
                  <div class="post-meta">
                    <time datetime={post.data.pubDate?.toISOString()}>
                      {formatDate(post.data.pubDate)}
                    </time>
                    {post.data.readTime && (
                      <span class="read-time">{post.data.readTime}</span>
                    )}
                  </div>
                  
                  <h3 class="post-title">{post.data.title}</h3>
                  
                  {post.data.description && (
                    <p class="post-description">{post.data.description}</p>
                  )}
                  
                  {post.data.tags && post.data.tags.length > 0 && (
                    <div class="post-tags">
                      {post.data.tags.map(postTag => (
                        <span class={`post-tag ${postTag === tag ? 'current-tag' : ''}`}>
                          #{postTag}
                        </span>
                      ))}
                    </div>
                  )}
                </div>
              </a>
            </article>
          )) : (
            <div class="no-posts">
              <p>No posts found with the tag "{tag}".</p>
              <a href="/blog" class="back-to-blog">Browse all posts</a>
            </div>
          )}
        </div>
      </div>
      
      <div class="tag-navigation">
        <a href="/blog" class="back-button">
          <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" 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 All Posts
        </a>
      </div>
    </section>
  </main>
  
  <Footer slot="footer" />
</BaseLayout>

<style>
  .tag-page-container {
    padding-bottom: 4rem;
  }
  
  .container {
    max-width: 1280px;
    margin: 0 auto;
    padding: 0 var(--container-padding, 1.5rem);
  }
  
  .tag-hero {
    padding: 5rem 0 3rem;
    background: linear-gradient(to bottom, var(--bg-secondary), var(--bg-primary));
    text-align: center;
    position: relative;
    overflow: hidden;
  }
  
  .tag-hero::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: radial-gradient(circle at 30% 50%, rgba(6, 182, 212, 0.05) 0%, transparent 50%);
    pointer-events: none;
  }
  
  .tag-hero h1 {
    font-size: clamp(1.8rem, 4vw, 3rem);
    margin-bottom: 1rem;
    animation: fadeInUp 0.6s ease-out;
  }
  
  .tag-highlight {
    background: linear-gradient(90deg, var(--accent-primary), var(--accent-secondary));
    -webkit-background-clip: text;
    background-clip: text;
    color: transparent;
    font-weight: 700;
  }
  
  .tag-description {
    color: var(--text-secondary);
    font-size: clamp(1rem, 2vw, 1.2rem);
    max-width: 600px;
    margin: 0 auto;
    animation: fadeInUp 0.8s ease-out;
  }
  
  @keyframes fadeInUp {
    from {
      opacity: 0;
      transform: translateY(20px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
  
  .tag-content {
    margin-top: 3rem;
  }
  
  .knowledge-graph-section, 
  .posts-section {
    margin-bottom: 4rem;
  }
  
  .knowledge-graph-section h2,
  .posts-section h2 {
    font-size: 1.8rem;
    margin-bottom: 0.5rem;
    text-align: center;
  }
  
  .section-description {
    text-align: center;
    color: var(--text-secondary);
    margin-bottom: 2rem;
  }
  
  .graph-wrapper {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  }
  
  .posts-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: 2rem;
  }
  
  .post-card {
    height: 100%;
    animation: fadeIn 0.6s ease-out forwards;
    opacity: 0;
  }
  
  .post-card:nth-child(1) { animation-delay: 0.1s; }
  .post-card:nth-child(2) { animation-delay: 0.2s; }
  .post-card:nth-child(3) { animation-delay: 0.3s; }
  .post-card:nth-child(4) { animation-delay: 0.4s; }
  .post-card:nth-child(5) { animation-delay: 0.5s; }
  .post-card:nth-child(6) { animation-delay: 0.6s; }
  
  @keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
  }
  
  .post-card-link {
    display: flex;
    flex-direction: column;
    height: 100%;
    background: var(--card-bg);
    border: 1px solid var(--card-border);
    border-radius: 12px;
    overflow: hidden;
    text-decoration: none;
    transition: all 0.3s ease;
  }
  
  .post-card-link:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
    border-color: var(--accent-primary);
  }
  
  .post-image-wrapper {
    height: 200px;
    overflow: hidden;
    border-bottom: 1px solid var(--card-border);
  }
  
  .post-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.5s ease;
  }
  
  .post-card-link:hover .post-image {
    transform: scale(1.05);
  }
  
  .post-content {
    padding: 1.5rem;
    display: flex;
    flex-direction: column;
    flex-grow: 1;
  }
  
  .post-meta {
    display: flex;
    justify-content: space-between;
    font-size: 0.85rem;
    color: var(--text-tertiary);
    margin-bottom: 1rem;
  }
  
  .read-time {
    font-family: var(--font-mono);
  }
  
  .post-title {
    font-size: 1.2rem;
    color: var(--text-primary);
    margin-bottom: 0.75rem;
    line-height: 1.4;
  }
  
  .post-description {
    color: var(--text-secondary);
    font-size: 0.95rem;
    margin-bottom: 1.5rem;
    flex-grow: 1;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
  
  .post-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
    margin-top: auto;
  }
  
  .post-tag {
    font-size: 0.75rem;
    color: var(--text-secondary);
    background: rgba(226, 232, 240, 0.05);
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
  }
  
  .post-tag.current-tag {
    background: rgba(16, 185, 129, 0.2);
    color: var(--accent-primary);
  }
  
  .no-posts {
    grid-column: 1 / -1;
    text-align: center;
    padding: 3rem;
    background: var(--card-bg);
    border: 1px dashed var(--card-border);
    border-radius: 12px;
    color: var(--text-secondary);
  }
  
  .back-to-blog {
    display: inline-block;
    margin-top: 1rem;
    padding: 0.75rem 1.5rem;
    background: linear-gradient(90deg, var(--accent-primary), var(--accent-secondary));
    color: var(--bg-primary);
    border-radius: 6px;
    text-decoration: none;
    font-weight: 500;
    transition: all 0.3s ease;
  }
  
  .back-to-blog:hover {
    transform: translateY(-3px);
    box-shadow: 0 5px 15px rgba(6, 182, 212, 0.2);
  }
  
  .tag-navigation {
    display: flex;
    justify-content: center;
    margin-top: 2rem;
  }
  
  .back-button {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.8rem 1.5rem;
    background: var(--bg-secondary);
    border: 1px solid var(--border-primary);
    border-radius: 30px;
    color: var(--text-primary);
    text-decoration: none;
    transition: all 0.3s ease;
  }
  
  .back-button:hover {
    background: var(--bg-tertiary);
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  }
  
  @media (max-width: 768px) {
    .tag-hero {
      padding: 4rem 0 2rem;
    }
    
    .posts-grid {
      grid-template-columns: 1fr;
    }
  }
</style>