---
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 FilterPill from '../../components/ui/FilterPill.astro';
import { apiClient, DEFAULT_SITE_SETTINGS } from '../../lib/api/client';
import { getI18n } from '../../lib/i18n';
import type { Tag } from '../../lib/types';
import { buildTagUrl, getAccentVars, getTagTheme } from '../../lib/utils';

export const prerender = false;

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

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

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

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

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

const siteBaseUrl = (siteSettings.siteUrl || new URL(Astro.request.url).origin).replace(/\/$/, '');
const canonicalUrl = new URL('/tags', siteBaseUrl).toString();
const sharePanelCopy = isEnglish
  ? {
      badge: 'tag directory',
      title: 'Share the tag directory',
      description:
        'Publish the tag overview as a compact topic graph so AI retrieval and readers can jump into the right subject clusters from one canonical page.',
      tags: 'Tags',
      site: 'Site',
    }
  : {
      badge: '标签总览',
      title: '分享标签总览',
      description: '把标签总览分享出去，方便按关键词继续浏览。',
      tags: '标签数',
      site: '站点',
    };
const jsonLd = [
  {
    '@context': 'https://schema.org',
    '@type': 'CollectionPage',
    name: t('tags.title'),
    description: t('tags.intro'),
    url: canonicalUrl,
  },
  {
    '@context': 'https://schema.org',
    '@type': 'ItemList',
    name: `${t('tags.title')} list`,
    itemListElement: tags.map((tag, index) => ({
      '@type': 'ListItem',
      position: index + 1,
      url: new URL(buildTagUrl(tag), siteBaseUrl).toString(),
      name: tag.name,
      description: tag.description || tag.seoDescription || `${tag.name} topic hub`,
    })),
  },
];
---

<BaseLayout title={`${t('tags.pageTitle')} - Termi`} jsonLd={jsonLd}>
  <PageViewTracker pageType="tags" entityId="tags-index" />
  <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <TerminalWindow title="~/tags" class="w-full">
      <div class="mb-6 px-4">
        <CommandPrompt command="tags list --sort popularity" />
        <div class="terminal-panel ml-4 mt-4">
          <div class="terminal-kicker">tag index</div>
          <div class="terminal-section-title mt-4">
            <span class="terminal-section-icon">
              <i class="fas fa-hashtag"></i>
            </span>
            <div>
              <h1 class="text-2xl font-bold text-[var(--title-color)]">{t('tags.title')}</h1>
              <p class="mt-2 max-w-2xl text-sm leading-6 text-[var(--text-secondary)]">
                {t('tags.intro')}
              </p>
            </div>
          </div>
          <div class="mt-5 flex flex-wrap gap-2">
            <span class="terminal-stat-pill">
              <i class="fas fa-tags text-[var(--primary)]"></i>
              <span>{t('common.tagsCount', { count: tags.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('tags.pageTitle')} - ${siteSettings.siteShortName || siteSettings.siteName}`}
            summary={t('tags.intro')}
            canonicalUrl={canonicalUrl}
            badge={sharePanelCopy.badge}
            kicker="geo / taxonomy"
            title={sharePanelCopy.title}
            description={sharePanelCopy.description}
            stats={[
              { label: sharePanelCopy.tags, value: String(tags.length) },
              { label: sharePanelCopy.site, value: siteSettings.siteShortName || siteSettings.siteName },
            ]}
            wechatShareQrEnabled={siteSettings.seo.wechatShareQrEnabled}
          />
        </div>
      </div>

      <div class="px-4">
        <div class="terminal-panel ml-4 mt-4">
          <div class="mb-4 text-[11px] uppercase tracking-[0.22em] text-[var(--text-tertiary)]">
            {t('tags.browseTags')}
          </div>

          {tags.length === 0 ? (
            <div class="terminal-empty w-full">
              {t('tags.emptyTags')}
            </div>
          ) : (
            <div class="flex flex-wrap gap-3">
              {tags.map((tag) => (
                <FilterPill
                  tone="accent"
                  href={buildTagUrl(tag)}
                  style={getAccentVars(getTagTheme(tag.name))}
                >
                  <i class="fas fa-hashtag"></i>
                  <span>{tag.name}</span>
                  {typeof tag.count === 'number' ? (
                    <span class="text-xs text-[var(--text-tertiary)]">{tag.count}</span>
                  ) : null}
                </FilterPill>
              ))}
            </div>
          )}
        </div>
      </div>
    </TerminalWindow>
  </div>
</BaseLayout>
