---
import BaseLayout from '../../layouts/BaseLayout.astro';
import PageViewTracker from '../../components/seo/PageViewTracker.astro';
import SharePanel from '../../components/seo/SharePanel.astro';
import TerminalWindow from '../../components/ui/TerminalWindow.astro';
import CommandPrompt from '../../components/ui/CommandPrompt.astro';
import PostCard from '../../components/PostCard.astro';
import { apiClient, DEFAULT_SITE_SETTINGS } from '../../lib/api/client';
import { getI18n } from '../../lib/i18n';
import { buildPostItemList } from '../../lib/seo';
import type { Post, Tag } from '../../lib/types';
import { buildTagUrl, getAccentVars, getTagTheme } from '../../lib/utils';

export const prerender = false;

const { slug } = Astro.params;
const { locale, t } = getI18n(Astro);
const isEnglish = locale.startsWith('en');

let tags: Tag[] = [];
let posts: Post[] = [];
let siteSettings = DEFAULT_SITE_SETTINGS;

const [tagsResult, postsResult, settingsResult] = await Promise.allSettled([
  apiClient.getTags(),
  apiClient.getPosts(),
  apiClient.getSiteSettings(),
]);

if (tagsResult.status === 'fulfilled') {
  tags = tagsResult.value;
} else {
  console.error('Failed to fetch tags:', tagsResult.reason);
}

if (postsResult.status === 'fulfilled') {
  posts = postsResult.value;
} else {
  console.error('Failed to fetch tag posts:', postsResult.reason);
}

if (settingsResult.status === 'fulfilled') {
  siteSettings = settingsResult.value;
}

const requested = decodeURIComponent(slug || '').trim().toLowerCase();
const tag =
  tags.find((item) => {
    return [item.slug, item.name].some(
      (value) => (value || '').trim().toLowerCase() === requested,
    );
  }) || null;

if (!tag) {
  return new Response(null, {
    status: tagsResult.status !== 'fulfilled' ? 503 : 404,
    headers: tagsResult.status !== 'fulfilled' ? { 'Retry-After': '120' } : undefined,
  });
}

const canonicalUrl = buildTagUrl(tag);
if (slug && slug !== tag.slug && tag.slug) {
  return Astro.redirect(canonicalUrl, 301);
}

const filteredPosts = posts.filter((post) =>
  post.tags.some((item) => item.trim().toLowerCase() === tag.name.trim().toLowerCase()),
);
const tagTheme = getTagTheme(tag.name);
const pageTitle = tag.seoTitle || `${tag.name} - ${t('tags.title')}`;
const pageDescription = tag.seoDescription || tag.description || t('tags.selectedSummary', {
  tag: tag.name,
  count: filteredPosts.length,
});
const siteBaseUrl = (siteSettings.siteUrl || new URL(Astro.request.url).origin).replace(/\/$/, '');
const absoluteCanonicalUrl = new URL(canonicalUrl, siteBaseUrl).toString();
const sharePanelCopy = isEnglish
  ? {
      badge: 'tag hub',
      title: 'Share this tag hub',
      description:
        'Use this tag archive as a compact topic cluster so people and AI retrieval systems can discover related posts from one canonical URL.',
      posts: 'Posts',
      tag: 'Tag',
    }
  : {
      badge: '标签页',
      title: '分享这个标签页',
      description: '分享这个标签页，方便集中查看相关内容。',
      posts: '文章数',
      tag: '标签',
    };
const jsonLd = [
  {
    '@context': 'https://schema.org',
    '@type': 'CollectionPage',
    name: pageTitle,
    description: pageDescription,
    url: absoluteCanonicalUrl,
    about: {
      '@type': 'DefinedTerm',
      name: tag.name,
      termCode: tag.slug || tag.name,
      description: tag.description || pageDescription,
    },
    keywords: [tag.name, tag.slug].filter(Boolean),
  },
  {
    '@context': 'https://schema.org',
    '@type': 'ItemList',
    name: `${tag.name} posts`,
    itemListElement: buildPostItemList(filteredPosts, siteBaseUrl),
  },
  {
    '@context': 'https://schema.org',
    '@type': 'BreadcrumbList',
    itemListElement: [
      {
        '@type': 'ListItem',
        position: 1,
        name: 'Termi',
        item: siteBaseUrl,
      },
      {
        '@type': 'ListItem',
        position: 2,
        name: t('tags.title'),
        item: new URL('/tags', siteBaseUrl).toString(),
      },
      {
        '@type': 'ListItem',
        position: 3,
        name: tag.name,
        item: absoluteCanonicalUrl,
      },
    ],
  },
];
---

<BaseLayout
  title={pageTitle}
  description={pageDescription}
  ogImage={tag.coverImage}
  canonical={canonicalUrl}
  jsonLd={jsonLd}
  twitterCard={tag.coverImage ? 'summary_large_image' : 'summary'}
>
  <PageViewTracker pageType="tag" entityId={tag.slug || tag.name} />
  <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <TerminalWindow title={`~/tags/${tag.slug || tag.name}`} class="w-full">
      <div class="px-4 pb-2">
        <CommandPrompt command={`posts query --tag "${tag.name}"`} />

        <div class="terminal-panel ml-4 mt-4 space-y-5" style={getAccentVars(tagTheme)}>
          <div class="flex flex-wrap items-start justify-between gap-4">
            <div class="space-y-4">
              <a href="/tags" class="terminal-link-arrow">
                <i class="fas fa-arrow-left"></i>
                <span>返回标签目录</span>
              </a>

              <div class="flex flex-wrap items-center gap-2">
                <span class="terminal-kicker">
                  <i class="fas fa-hashtag"></i>
                  tag detail
                </span>
                <span class="terminal-chip terminal-chip--accent">
                  <i class="fas fa-tag"></i>
                  {tag.slug || tag.name}
                </span>
              </div>
            </div>

            <div class="flex flex-wrap gap-2">
              <span class="terminal-stat-pill">
                <i class="fas fa-file-lines text-[var(--primary)]"></i>
                <span>{t('common.postsCount', { count: filteredPosts.length })}</span>
              </span>
              {typeof tag.count === 'number' ? (
                <span class="terminal-stat-pill">
                  <i class="fas fa-signal text-[var(--primary)]"></i>
                  <span>{tag.count}</span>
                </span>
              ) : null}
            </div>
          </div>

          <div class="space-y-3">
            <h1 class="text-3xl font-bold tracking-tight text-[var(--title-color)]">{tag.name}</h1>
            <p class="max-w-3xl text-base leading-8 text-[var(--text-secondary)]">{pageDescription}</p>
          </div>

          <SharePanel
            shareTitle={pageTitle}
            summary={pageDescription}
            canonicalUrl={absoluteCanonicalUrl}
            badge={sharePanelCopy.badge}
            kicker="geo / taxonomy"
            title={sharePanelCopy.title}
            description={sharePanelCopy.description}
            stats={[
              { label: sharePanelCopy.posts, value: String(filteredPosts.length) },
              { label: sharePanelCopy.tag, value: tag.slug || tag.name },
            ]}
            wechatShareQrEnabled={siteSettings.seo.wechatShareQrEnabled}
          />

          {tag.coverImage ? (
            <div class="overflow-hidden rounded-2xl border border-[var(--border-color)]">
              <img
                src={tag.coverImage}
                alt={tag.name}
                class="h-56 w-full object-cover"
              />
            </div>
          ) : null}
        </div>
      </div>

      <div class="px-4 pb-8">
        <CommandPrompt command={`posts list --tag "${tag.name}"`} typing={false} />
        {filteredPosts.length > 0 ? (
          <div class="ml-4 mt-4 space-y-4">
            {filteredPosts.map((post) => (
              <PostCard post={post} selectedTag={tag.name} />
            ))}
          </div>
        ) : (
          <div class="terminal-empty ml-4 mt-4">
            <i class="fas fa-inbox text-4xl mb-4 opacity-50 text-[var(--primary)]"></i>
            <p class="text-[var(--text-secondary)]">{t('tags.emptyPosts')}</p>
          </div>
        )}
      </div>
    </TerminalWindow>
  </div>
</BaseLayout>
