---
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 { api, DEFAULT_SITE_SETTINGS } from '../../lib/api/client';
import { getI18n } from '../../lib/i18n';
import { buildPostItemList } from '../../lib/seo';
import type { Category, Post } from '../../lib/types';
import { buildCategoryUrl, getAccentVars, getCategoryTheme } from '../../lib/utils';

export const prerender = false;

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

let categories: Category[] = [];
let posts: Post[] = [];
let siteSettings = DEFAULT_SITE_SETTINGS;
let categoriesFailed = false;

try {
  const [categoriesResult, postsResult, settingsResult] = await Promise.allSettled([
    api.getCategories(),
    api.getPosts(),
    api.getSiteSettings(),
  ]);

  if (categoriesResult.status === 'fulfilled') {
    categories = categoriesResult.value;
  } else {
    categoriesFailed = true;
    console.error('Failed to fetch categories:', categoriesResult.reason);
  }

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

  if (settingsResult.status === 'fulfilled') {
    siteSettings = settingsResult.value;
  }
} catch (error) {
  console.error('Failed to fetch category detail data:', error);
}

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

if (!category) {
  return new Response(null, {
    status: categoriesFailed ? 503 : 404,
    headers: categoriesFailed ? { 'Retry-After': '120' } : undefined,
  });
}

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

const filteredPosts = posts.filter(
  (post) => (post.category || '').trim().toLowerCase() === category.name.trim().toLowerCase(),
);
const categoryTheme = getCategoryTheme(category.name);
const pageTitle = category.seoTitle || `${category.name} - ${t('categories.title')}`;
const pageDescription =
  category.seoDescription || category.description || t('categories.categoryPosts', { name: category.name });
const siteBaseUrl = (siteSettings.siteUrl || new URL(Astro.request.url).origin).replace(/\/$/, '');
const absoluteCanonicalUrl = new URL(canonicalUrl, siteBaseUrl).toString();
const sharePanelCopy = isEnglish
  ? {
      badge: 'category hub',
      title: 'Share this category hub',
      description:
        'Turn this taxonomy page into a reusable discovery entry so people and AI search engines converge on the same topic cluster.',
      posts: 'Posts',
      slug: 'Slug',
    }
  : {
      badge: '分类页',
      title: '分享这个分类页',
      description: '分享这个分类页，方便集中查看同主题内容。',
      posts: '文章数',
      slug: 'Slug',
    };
const jsonLd = [
  {
    '@context': 'https://schema.org',
    '@type': 'CollectionPage',
    name: pageTitle,
    description: pageDescription,
    url: absoluteCanonicalUrl,
    about: {
      '@type': 'Thing',
      name: category.name,
      description: category.description || pageDescription,
    },
    keywords: [category.name, category.slug].filter(Boolean),
  },
  {
    '@context': 'https://schema.org',
    '@type': 'ItemList',
    name: `${category.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('categories.title'),
        item: new URL('/categories', siteBaseUrl).toString(),
      },
      {
        '@type': 'ListItem',
        position: 3,
        name: category.name,
        item: absoluteCanonicalUrl,
      },
    ],
  },
];
---

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

        <div class="terminal-panel ml-4 mt-4 space-y-5" style={getAccentVars(categoryTheme)}>
          <div class="flex flex-wrap items-start justify-between gap-4">
            <div class="space-y-4">
              <a href="/categories" 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-folder-tree"></i>
                  category detail
                </span>
                <span class="terminal-chip terminal-chip--accent">
                  <i class="fas fa-folder-open"></i>
                  {category.slug || category.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>
              {category.accentColor ? (
                <span class="terminal-stat-pill">
                  <i class="fas fa-droplet text-[var(--primary)]"></i>
                  <span>{category.accentColor}</span>
                </span>
              ) : null}
            </div>
          </div>

          <div class="space-y-3">
            <h1 class="text-3xl font-bold tracking-tight text-[var(--title-color)]">{category.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.slug, value: category.slug || category.name },
            ]}
            wechatShareQrEnabled={siteSettings.seo.wechatShareQrEnabled}
          />

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

      <div class="px-4 pb-8">
        <CommandPrompt command={`posts list --category "${category.name}"`} typing={false} />
        {filteredPosts.length > 0 ? (
          <div class="ml-4 mt-4 space-y-4">
            {filteredPosts.map((post) => (
              <PostCard post={post} />
            ))}
          </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('categories.emptyPosts')}</p>
          </div>
        )}
      </div>
    </TerminalWindow>
  </div>
</BaseLayout>
