---
import { Hash } from 'lucide-react';
import { type Lang } from '@/types/i18n';
import { defaultLang } from '@/i18n/ui';
import { getBlogBaseUrl, extractTags } from '@/utils/blog-utils';

// Define component props
interface Props {
  lang?: Lang;
  currentTag?: string;
}

// Get component props
const { lang = defaultLang, currentTag = '' } = Astro.props;

// Determine base URL path
const baseUrl = getBlogBaseUrl(lang);

// Read all blog posts - choose different static paths based on language
const postsGlob = {
  en: await import.meta.glob('/src/pages/blog/posts/*.md', { eager: true }),
  zh: await import.meta.glob('/src/pages/zh/blog/posts/*.md', { eager: true })
};

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

// Extract tags from posts
const tagMap = extractTags(allPosts);

// Convert to array, add # prefix, and sort
const tags = Array.from(tagMap.keys()).map(tag => `# ${tag}`).sort();

// Multilingual titles
const titles = {
  en: 'Tags',
  zh: '标签'
};

// Get title for current language
const title = titles[lang] || titles[defaultLang];
---

<div class="bg-card/60 backdrop-blur-md rounded-2xl p-6 border border-border/40">
  <h3 class="text-xl font-semibold text-card-foreground mb-4 flex items-center">
    <Hash className='w-5 h-5 mr-2 text-primary' />
    {title}
  </h3>
  <div class="flex flex-wrap gap-2">
    {tags.length > 0 ? (
      tags.map((tagItem) => {
        const tagName = tagItem.slice(2); // 去掉 '# ' 前缀
        const tagId = tagMap.get(tagName) || tagName.toLowerCase();
        const isCurrentTag = tagId === currentTag.toLowerCase();
        return (
          <a href={`${baseUrl}/tags/${encodeURIComponent(tagId)}`} 
             class={`inline-block px-3 py-1 text-sm rounded-full transition-all duration-200 ${isCurrentTag ? 'bg-primary/20 text-primary font-medium' : 'bg-muted text-muted-foreground hover:bg-primary/20 hover:text-primary'}`}>
            {tagItem}
          </a>
        );
      })
    ) : (
      <div class="flex flex-col items-center justify-center py-6 w-full">
        <p class="text-muted-foreground text-center">{lang === 'zh' ? '暂无标签' : 'No tags yet'}</p>
      </div>
    )}
  </div>
</div>
