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

export const prerender = false;

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

let categories: Category[] = [];
let siteSettings = DEFAULT_SITE_SETTINGS;

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

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

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

const siteBaseUrl = (siteSettings.siteUrl || new URL(Astro.request.url).origin).replace(/\/$/, '');
const canonicalUrl = new URL('/categories', siteBaseUrl).toString();
const sharePanelCopy = isEnglish
  ? {
      badge: 'taxonomy index',
      title: 'Share the category index',
      description:
        'Use the category directory as a high-level topic map so AI search and human readers can branch into the right content hubs from one canonical page.',
      categories: 'Categories',
      site: 'Site',
    }
  : {
      badge: '分类总览',
      title: '分享分类总览',
      description: '把分类总览分享出去，方便按主题快速找到内容。',
      categories: '分类数',
      site: '站点',
    };
const jsonLd = [
  {
    '@context': 'https://schema.org',
    '@type': 'CollectionPage',
    name: t('categories.title'),
    description: t('categories.intro'),
    url: canonicalUrl,
  },
  {
    '@context': 'https://schema.org',
    '@type': 'ItemList',
    name: `${t('categories.title')} list`,
    itemListElement: categories.map((category, index) => ({
      '@type': 'ListItem',
      position: index + 1,
      url: new URL(buildCategoryUrl(category), siteBaseUrl).toString(),
      name: category.name,
      description: category.description || t('categories.categoryPosts', { name: category.name }),
    })),
  },
];
---

<BaseLayout title={`${t('categories.pageTitle')} - Termi`} jsonLd={jsonLd}>
  <PageViewTracker pageType="categories" entityId="categories-index" />
  <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <TerminalWindow title="~/categories" class="w-full">
      <div class="mb-6 px-4">
        <CommandPrompt command="categories list --with-counts" />
        <div class="terminal-panel ml-4 mt-4">
          <div class="terminal-kicker">content taxonomy</div>
          <div class="terminal-section-title mt-4">
            <span class="terminal-section-icon">
              <i class="fas fa-folder-open"></i>
            </span>
            <div>
              <h1 class="text-2xl font-bold text-[var(--title-color)]">{t('categories.title')}</h1>
              <p class="mt-2 max-w-2xl text-sm leading-6 text-[var(--text-secondary)]">
                {t('categories.intro')}
              </p>
            </div>
          </div>
          <div class="mt-5 flex flex-wrap gap-2">
            <span class="terminal-stat-pill">
              <i class="fas fa-layer-group text-[var(--primary)]"></i>
              <span>{t('common.categoriesCount', { count: categories.length })}</span>
            </span>
            <span class="terminal-stat-pill">
              <i class="fas fa-terminal text-[var(--primary)]"></i>
              <span>点击进入分类专题详情页</span>
            </span>
          </div>
        </div>

        <div class="ml-4 mt-4">
          <SharePanel
            shareTitle={`${t('categories.pageTitle')} - ${siteSettings.siteShortName || siteSettings.siteName}`}
            summary={t('categories.intro')}
            canonicalUrl={canonicalUrl}
            badge={sharePanelCopy.badge}
            kicker="geo / taxonomy"
            title={sharePanelCopy.title}
            description={sharePanelCopy.description}
            stats={[
              { label: sharePanelCopy.categories, value: String(categories.length) },
              { label: sharePanelCopy.site, value: siteSettings.siteShortName || siteSettings.siteName },
            ]}
            wechatShareQrEnabled={siteSettings.seo.wechatShareQrEnabled}
          />
        </div>
      </div>

      <div class="px-4">
        <div class="ml-4">
          <CommandPrompt command="categories browse --mode detail-page" typing={false} />
          {categories.length > 0 ? (
            <div class="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
              {categories.map((category) => (
                <a
                  href={buildCategoryUrl(category)}
                  class="terminal-panel terminal-panel-accent terminal-interactive-card group p-5"
                  style={getAccentVars(getCategoryTheme(category.name))}
                >
                  <div class="flex items-start gap-4">
                    <div class="terminal-accent-icon shrink-0 flex h-12 w-12 items-center justify-center rounded-2xl border">
                      <i class="fas fa-folder-open text-lg"></i>
                    </div>
                    <div class="min-w-0 flex-1">
                      <div class="mb-2 flex items-start justify-between gap-3">
                        <div class="min-w-0">
                          <div class="mb-1 text-[11px] uppercase tracking-[0.22em] text-[var(--text-tertiary)]">
                            {category.slug || category.name}
                          </div>
                          <h2 class="truncate text-lg font-bold text-[var(--title-color)] transition-colors group-hover:text-[var(--primary)]">
                            {category.name}
                          </h2>
                        </div>
                        <span class="terminal-chip terminal-chip--accent text-xs py-1 px-2.5">
                          <span>{t('common.postsCount', { count: category.count ?? 0 })}</span>
                        </span>
                      </div>

                      <p class="line-clamp-3 text-sm leading-6 text-[var(--text-secondary)]">
                        {category.description || t('categories.categoryPosts', { name: category.name })}
                      </p>

                      <div class="mt-4 terminal-link-arrow">
                        <span>查看分类专题</span>
                        <i class="fas fa-arrow-right text-xs"></i>
                      </div>
                    </div>
                  </div>
                </a>
              ))}
            </div>
          ) : (
            <div class="terminal-empty 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.empty')}</p>
            </div>
          )}
        </div>
      </div>
    </TerminalWindow>
  </div>
</BaseLayout>
