---
import { type BlogPost as BaseBlogPost } from '@/types';
import { type Lang } from '@/types/i18n';

// Get current path and language information
const currentPath = Astro.url.pathname;
const isZh = currentPath.includes('/zh/');
const lang = isZh ? 'zh' : 'en';
const currentSlug = currentPath.split('/').filter(Boolean).pop();

// Read blog posts using import.meta.glob
const postsGlob = {
  en: await import.meta.glob('../../pages/blog/posts/*.md', { eager: true }),
  zh: await import.meta.glob('../../pages/zh/blog/posts/*.md', { eager: true })
};

// Get posts for current language
const allPosts = isZh ? Object.values(postsGlob.zh) : Object.values(postsGlob.en);

// Define BlogPost interface for navigation
interface BlogPost {
  title: string;
  slug: string;
  url: string;
  frontmatter: {
    title: string;
    description?: string;
    pubDate?: string;
    date?: string;
    readTime?: string;
    tags?: string[];
    category?: string;
  };
}

// Process blog posts for navigation
const posts: BlogPost[] = allPosts.map((post: any) => {
  const slug = post.url?.split('/').filter(Boolean).pop() || '';
  return {
    title: post.frontmatter.title,
    slug: slug,
    url: post.url || '',
    frontmatter: {
      title: post.frontmatter.title,
      description: post.frontmatter.description,
      pubDate: post.frontmatter.pubDate,
      date: post.frontmatter.date || post.frontmatter.pubDate,
      readTime: post.frontmatter.readTime,
      tags: post.frontmatter.tags,
      category: post.frontmatter.category
    }
  };
});

// Sort posts by date
const sortedPosts = posts
  .filter(post => post.frontmatter.date || post.frontmatter.pubDate)
  .sort((a, b) => {
    const dateA = new Date(a.frontmatter.date || a.frontmatter.pubDate || '').getTime();
    const dateB = new Date(b.frontmatter.date || b.frontmatter.pubDate || '').getTime();
    return dateB - dateA;
  });


const currentIndex = sortedPosts.findIndex((post) => post.slug === currentSlug);

const nextPost = currentIndex < sortedPosts.length - 1 ? sortedPosts[currentIndex + 1] : null;
const prevPost = currentIndex > 0 ? sortedPosts[currentIndex - 1] : null;

const prevText = lang === 'zh' ? '上一篇' : 'Previous Post';
const nextText = lang === 'zh' ? '下一篇' : 'Next Post';
---

<nav class="mt-8 flex flex-row gap-2 w-full p-6 max-xl:p-3 max-lg:p-2" role="navigation" aria-label="Blog post navigation">
  {prevPost && (
    <a
      href={prevPost.url}
      style="width: -webkit-fill-available"
      class="relative flex min-w-1/2 items-center justify-start gap-2 font-semibold dark:text-white text-black text-left text-pretty text-sm sm:text-base lg:text-lg leading-relaxed hover:text-primary hover:[text-shadow:1px_1px_11px_rgba(168,85,247,0.7)] transition-all duration-300 before:absolute before:-top-6 before:left-0 before:text-xs sm:before:text-sm before:font-light before:content-['Previous_Post'] hover:before:text-primary"
      tabindex="0"
      aria-label={`${prevText}: ${prevPost.frontmatter.title}`}
    >
      <svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M6.85355 3.85355C7.04882 3.65829 7.04882 3.34171 6.85355 3.14645C6.65829 2.95118 6.34171 2.95118 6.14645 3.14645L2.14645 7.14645C1.95118 7.34171 1.95118 7.65829 2.14645 7.85355L6.14645 11.8536C6.34171 12.0488 6.65829 12.0488 6.85355 11.8536C7.04882 11.6583 7.04882 11.3417 6.85355 11.1464L3.20711 7.5L6.85355 3.85355ZM12.8536 3.85355C13.0488 3.65829 13.0488 3.34171 12.8536 3.14645C12.6583 2.95118 12.3417 2.95118 12.1464 3.14645L8.14645 7.14645C7.95118 7.34171 7.95118 7.65829 8.14645 7.85355L12.1464 11.8536C12.3417 12.0488 12.6583 12.0488 12.8536 11.8536C13.0488 11.6583 13.0488 11.3417 12.8536 11.1464L9.20711 7.5L12.8536 3.85355Z" fill="currentColor" fill-rule="evenodd" clip-rule="evenodd"></path>
      </svg>
      {prevPost.frontmatter.title}
    </a>
  )}

  {nextPost && (
    <a
      href={nextPost.url}
      style="width: -webkit-fill-available"
      class="relative flex min-w-1/2 items-center justify-end gap-2 font-semibold dark:text-white text-black text-right text-pretty text-sm sm:text-base lg:text-lg leading-relaxed hover:text-primary hover:[text-shadow:1px_1px_11px_rgba(168,85,247,0.7)] transition-all duration-300 before:absolute before:-top-6 before:right-0 before:text-xs sm:before:text-sm before:font-light before:content-['Next_Post'] hover:before:text-primary"
      tabindex="0"
      aria-label={`${nextText}: ${nextPost.frontmatter.title}`}
    >
      {nextPost.frontmatter.title}
      <svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M2.14645 11.1464C1.95118 11.3417 1.95118 11.6583 2.14645 11.8536C2.34171 12.0488 2.65829 12.0488 2.85355 11.8536L6.85355 7.85355C7.04882 7.65829 7.04882 7.34171 6.85355 7.14645L2.85355 3.14645C2.65829 2.95118 2.34171 2.95118 2.14645 3.14645C1.95118 3.34171 1.95118 3.65829 2.14645 3.85355L5.79289 7.5L2.14645 11.1464ZM8.14645 11.1464C7.95118 11.3417 7.95118 11.6583 8.14645 11.8536C8.34171 12.0488 8.65829 12.0488 8.85355 11.8536L12.8536 7.85355C13.0488 7.65829 13.0488 7.34171 12.8536 7.14645L8.85355 3.14645C8.65829 2.95118 8.34171 2.95118 8.14645 3.14645C7.95118 3.34171 7.95118 3.65829 8.14645 3.85355L11.7929 7.5L8.14645 11.1464Z" fill="currentColor" fill-rule="evenodd" clip-rule="evenodd"></path>
      </svg>
    </a>
  )}
</nav>

<script>
  document.addEventListener('DOMContentLoaded', () => {
    const navLinks = document.querySelectorAll('nav[aria-label="Blog post navigation"] a');
    
    navLinks.forEach(link => {
      link.addEventListener('keydown', (event) => {
        const keyboardEvent = event as KeyboardEvent;
        if (keyboardEvent.key === 'Enter' || keyboardEvent.key === ' ') {
          event.preventDefault();
          const href = (event.target as HTMLAnchorElement).href;
          if (href) {
            window.location.href = href;
          }
        }
      });
    });
  });
</script>

<style>
  nav a:hover {
    transform: translateY(-2px);
  }
  
  nav a:focus {
    outline: 2px solid rgba(168, 85, 247, 0.5);
    outline-offset: 2px;
  }
</style>