---
import BaseLayout from '../../layouts/BaseLayout.astro';
import DiscoveryBrief from '../../components/seo/DiscoveryBrief.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 PostCard from '../../components/PostCard.astro';
import { api, DEFAULT_SITE_SETTINGS } from '../../lib/api/client';
import { getI18n } from '../../lib/i18n';
import { buildDiscoveryHighlights, buildFaqJsonLd, buildPageFaqs, buildPostItemList } from '../../lib/seo';
import type { Category, Post, Tag } from '../../lib/types';
import { getAccentVars, getCategoryTheme, getPostTypeTheme, getTagTheme } from '../../lib/utils';

export const prerender = false;

const url = new URL(Astro.request.url);
const selectedSearch = url.searchParams.get('search') || '';
const selectedType = url.searchParams.get('type') || 'all';
const selectedTag = url.searchParams.get('tag') || '';
const selectedCategory = url.searchParams.get('category') || '';
const requestedPage = Number.parseInt(url.searchParams.get('page') || '1', 10);
const postsPerPage = 10;
const { locale, t } = getI18n(Astro);
const isEnglish = locale.startsWith('en');

let paginatedPosts: Post[] = [];
let allTags: Tag[] = [];
let allCategories: Category[] = [];
let siteSettings = DEFAULT_SITE_SETTINGS;
let totalPosts = 0;
let totalPages = 1;
let currentPage = Number.isFinite(requestedPage) && requestedPage > 0 ? requestedPage : 1;

try {
  const [pageResult, categories, rawTags] = await Promise.all([
    selectedSearch
      ? api.searchPostsPage({
          query: selectedSearch,
          page: currentPage,
          pageSize: postsPerPage,
          category: selectedCategory || undefined,
          tag: selectedTag || undefined,
          postType: selectedType !== 'all' ? selectedType : undefined,
        })
      : api.getPostsPage({
          page: currentPage,
          pageSize: postsPerPage,
          search: undefined,
          category: selectedCategory || undefined,
          tag: selectedTag || undefined,
          postType: selectedType !== 'all' ? selectedType : undefined,
        }),
    api.getCategories(),
    api.getTags(),
  ]);

  paginatedPosts = pageResult.items;
  totalPosts = pageResult.total;
  totalPages = pageResult.totalPages;
  currentPage = pageResult.page;
  allCategories = categories;

  const seenTagIds = new Set<string>();
  allTags = rawTags.filter((tag) => {
    const key = `${tag.slug}:${tag.name}`.toLowerCase();
    if (seenTagIds.has(key)) return false;
    seenTagIds.add(key);
    return true;
  });

  try {
    siteSettings = await api.getSiteSettings();
  } catch (settingsError) {
    console.error('Failed to fetch site settings for articles index:', settingsError);
  }
} catch (error) {
  console.error('API Error:', error);
}

const normalizedSelectedTag = selectedTag.trim().toLowerCase();
const isSelectedTag = (tag: Tag) =>
  tag.name.trim().toLowerCase() === normalizedSelectedTag ||
  tag.slug.trim().toLowerCase() === normalizedSelectedTag;

const postTypeFilters = [
  { id: 'all', name: t('common.all'), icon: 'fa-stream' },
  { id: 'article', name: t('common.article'), icon: 'fa-file-alt' },
  { id: 'tweet', name: t('common.tweet'), icon: 'fa-comment-dots' },
];

const typePromptCommand =
  selectedType === 'all'
    ? 'posts query --type all'
    : `posts query --type ${selectedType}`;
const categoryPromptCommand = selectedCategory
  ? `posts query --category "${selectedCategory}"`
  : 'categories list --sort name';
const tagPromptCommand = selectedTag
  ? `posts query --tag "${selectedTag}"`
  : 'tags list --sort popularity';
const hasActiveFilters =
  Boolean(selectedSearch || selectedTag || selectedCategory || selectedType !== 'all' || currentPage > 1);
const canonicalUrl = hasActiveFilters ? '/articles' : undefined;
const siteBaseUrl = (siteSettings.siteUrl || new URL(Astro.request.url).origin).replace(/\/$/, '');
const absoluteCanonicalUrl = new URL('/articles', siteBaseUrl).toString();
const sharePanelCopy = isEnglish
  ? {
      badge: 'content archive',
      title: 'Share the article archive',
      description:
        'Use the articles index as the canonical discovery shelf for AI retrieval and readers, then branch into type, category, and tag filters from one source.',
      posts: 'Posts',
      categories: 'Categories',
      tags: 'Tags',
      page: 'Page',
    }
    : {
      badge: '文章列表',
      title: '分享文章列表',
      description: '把文章列表分享出去，方便继续按分类、标签和类型浏览。',
      posts: '文章数',
      categories: '分类数',
      tags: '标签数',
      page: '页码',
    };
const articleIndexHighlights = buildDiscoveryHighlights([
  t('articlesPage.description'),
  `${sharePanelCopy.posts}: ${totalPosts}`,
  `${sharePanelCopy.categories}: ${allCategories.length}`,
  `${sharePanelCopy.tags}: ${allTags.length}`,
  selectedType !== 'all' ? `type=${selectedType}` : '',
]);
const articleIndexFaqs = buildPageFaqs({
  locale,
  pageTitle: t('articlesPage.title'),
  summary: t('articlesPage.description'),
  primaryLabel: t('articlesPage.title'),
  primaryUrl: absoluteCanonicalUrl,
  relatedLinks: [
    { label: t('nav.categories'), url: `${siteBaseUrl}/categories` },
    { label: t('nav.tags'), url: `${siteBaseUrl}/tags` },
    { label: t('nav.timeline'), url: `${siteBaseUrl}/timeline` },
  ],
  signals: articleIndexHighlights,
});
const articleIndexFaqJsonLd = buildFaqJsonLd(articleIndexFaqs);
const jsonLd = [
  {
    '@context': 'https://schema.org',
    '@type': 'CollectionPage',
    name: t('articlesPage.title'),
    description: t('articlesPage.description'),
    url: new URL('/articles', siteBaseUrl).toString(),
  },
  {
    '@context': 'https://schema.org',
    '@type': 'ItemList',
    name: `${t('articlesPage.title')} page ${currentPage}`,
    itemListElement: buildPostItemList(paginatedPosts, siteBaseUrl),
  },
];

const buildArticlesUrl = ({
  type = selectedType,
  search = selectedSearch,
  tag = selectedTag,
  category = selectedCategory,
  page,
}: {
  type?: string;
  search?: string;
  tag?: string;
  category?: string;
  page?: number;
}) => {
  const params = new URLSearchParams();

  if (type && type !== 'all') params.set('type', type);
  if (search) params.set('search', search);
  if (tag) params.set('tag', tag);
  if (category) params.set('category', category);
  if (page && page > 1) params.set('page', String(page));

  const queryString = params.toString();
  return queryString ? `/articles?${queryString}` : '/articles';
};
---

<BaseLayout
  title={`${t('articlesPage.title')} - Termi`}
  siteSettings={siteSettings}
  canonical={canonicalUrl}
  noindex={hasActiveFilters}
  jsonLd={[...jsonLd, articleIndexFaqJsonLd].filter(Boolean)}
>
  <PageViewTracker pageType="articles" entityId={`articles-page-${currentPage}`} />
  <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <TerminalWindow title="~/articles/index" class="w-full">
      <div class="px-4 pb-2">
        <CommandPrompt command="posts list --sort published_at --order desc" />

        <div class="ml-4 mt-4 space-y-3">
          <h1 class="text-3xl font-bold tracking-tight text-[var(--title-color)]">{t('articlesPage.title')}</h1>
          <p class="max-w-2xl text-sm leading-7 text-[var(--text-secondary)]">
            {t('articlesPage.description')}
          </p>
          <div class="flex flex-wrap gap-2">
            <span class="terminal-stat-pill">
              <i class="fas fa-file-lines text-[var(--primary)]"></i>
              <span>{t('articlesPage.totalPosts', { count: totalPosts })}</span>
            </span>
            {selectedSearch && (
              <span class="terminal-stat-pill">
                <i class="fas fa-magnifying-glass text-[var(--primary)]"></i>
                search: {selectedSearch}
              </span>
            )}
            {selectedCategory && (
              <span
                class="terminal-stat-pill terminal-stat-pill--accent"
                style={getAccentVars(getCategoryTheme(selectedCategory))}
              >
                <i class="fas fa-folder-open"></i>
                <span>{selectedCategory}</span>
              </span>
            )}
            {selectedTag && (
              <span
                class="terminal-stat-pill terminal-stat-pill--accent"
                style={getAccentVars(getTagTheme(selectedTag))}
              >
                <i class="fas fa-hashtag"></i>
                <span>{selectedTag}</span>
              </span>
            )}
          </div>

          <SharePanel
            shareTitle={`${t('articlesPage.title')} - ${siteSettings.siteShortName || siteSettings.siteName}`}
            summary={t('articlesPage.description')}
            canonicalUrl={absoluteCanonicalUrl}
            badge={sharePanelCopy.badge}
            kicker="geo / archive"
            title={sharePanelCopy.title}
            description={sharePanelCopy.description}
            stats={[
              { label: sharePanelCopy.posts, value: String(totalPosts) },
              { label: sharePanelCopy.categories, value: String(allCategories.length) },
              { label: sharePanelCopy.tags, value: String(allTags.length) },
              { label: sharePanelCopy.page, value: `${currentPage}/${Math.max(totalPages, 1)}` },
            ]}
            wechatShareQrEnabled={siteSettings.seo.wechatShareQrEnabled}
          />

          <div class="mt-4">
            <DiscoveryBrief
              badge={isEnglish ? 'archive brief' : '归档摘要'}
              kicker="geo / archive"
              title={isEnglish ? 'AI-readable archive brief' : '给 AI 看的归档摘要'}
              summary={t('articlesPage.description')}
              highlights={articleIndexHighlights}
              faqs={articleIndexFaqs}
            />
          </div>
        </div>
      </div>

      <div class="px-4 pb-2 space-y-4">
        <div class="ml-4">
          <CommandPrompt promptId="articles-type-prompt" command={typePromptCommand} typing={false} />
          <div class="mt-3 flex flex-wrap gap-3">
            {postTypeFilters.map((filter) => (
              <FilterPill
                href={buildArticlesUrl({ type: filter.id, page: 1 })}
                tone={filter.id === 'all' ? 'neutral' : 'accent'}
                active={selectedType === filter.id}
                style={filter.id === 'all' ? undefined : getAccentVars(getPostTypeTheme(filter.id))}
              >
                <i class={`fas ${filter.icon}`}></i>
                <span class="font-medium">{filter.name}</span>
              </FilterPill>
            ))}
          </div>
        </div>

        {allCategories.length > 0 && (
          <div class="ml-4">
            <CommandPrompt promptId="articles-category-prompt" command={categoryPromptCommand} typing={false} />
            <div class="mt-3 flex flex-wrap gap-3">
              <FilterPill href={buildArticlesUrl({ category: '', page: 1 })} tone="amber" active={!selectedCategory}>
                <i class="fas fa-folder-tree"></i>
                <span class="font-medium">{t('articlesPage.allCategories')}</span>
              </FilterPill>
              {allCategories.map((category) => (
                <FilterPill
                  href={buildArticlesUrl({ category: category.name, page: 1 })}
                  tone="accent"
                  active={selectedCategory.toLowerCase() === category.name.toLowerCase()}
                  style={getAccentVars(getCategoryTheme(category.name))}
                >
                  <i class="fas fa-folder-open"></i>
                  <span class="font-medium">{category.name}</span>
                  <span class="text-xs text-[var(--text-tertiary)]">{category.count}</span>
                </FilterPill>
              ))}
            </div>
          </div>
        )}

        {allTags.length > 0 && (
          <div class="ml-4">
            <CommandPrompt promptId="articles-tag-prompt" command={tagPromptCommand} typing={false} />
            <div class="mt-3 flex flex-wrap gap-3">
              <FilterPill href={buildArticlesUrl({ tag: '', page: 1 })} tone="teal" active={!selectedTag}>
                <i class="fas fa-hashtag"></i>
                <span class="font-medium">{t('articlesPage.allTags')}</span>
              </FilterPill>
              {allTags.map((tag) => (
                <FilterPill
                  href={buildArticlesUrl({ tag: tag.slug || tag.name, page: 1 })}
                  tone="accent"
                  active={isSelectedTag(tag)}
                  style={getAccentVars(getTagTheme(tag.name))}
                >
                  <i class="fas fa-hashtag"></i>
                  <span class="font-medium">{tag.name}</span>
                </FilterPill>
              ))}
            </div>
          </div>
        )}
      </div>

      <div class="px-4">
        {paginatedPosts.length > 0 ? (
          <div class="ml-4 mt-4 space-y-4">
            {paginatedPosts.map((post) => (
              <PostCard post={post} selectedTag={selectedTag} highlightTerm={selectedSearch} />
            ))}
          </div>
        ) : null}
        <div class:list={['terminal-empty ml-4 mt-4', totalPosts > 0 && 'hidden']}>
          <div class="mx-auto flex max-w-md flex-col items-center gap-3">
            <span class="terminal-section-icon">
              <i class="fas fa-folder-open"></i>
            </span>
            <h2 class="text-xl font-semibold text-[var(--title-color)]">{t('articlesPage.emptyTitle')}</h2>
            <p class="text-sm leading-7 text-[var(--text-secondary)]">
              {t('articlesPage.emptyDescription')}
            </p>
            <a href="/articles" class="terminal-action-button terminal-action-button-primary">
              <i class="fas fa-rotate-left"></i>
              <span>{t('common.resetFilters')}</span>
            </a>
          </div>
        </div>
      </div>

      <div class="px-4 py-6">
        <div class:list={['terminal-panel-muted ml-4 mt-4 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between', totalPages <= 1 && 'hidden']}>
          <span class="text-sm text-[var(--text-secondary)]">
            {t('articlesPage.pageSummary', { current: currentPage, total: totalPages, count: totalPosts })}
          </span>
          <div class="flex flex-wrap gap-2">
            {currentPage > 1 && (
              <a href={buildArticlesUrl({ page: currentPage - 1 })} class="terminal-action-button">
                <i class="fas fa-chevron-left"></i>
                <span>{t('articlesPage.previous')}</span>
              </a>
            )}
            {currentPage < totalPages && (
              <a href={buildArticlesUrl({ page: currentPage + 1 })} class="terminal-action-button terminal-action-button-primary">
                <span>{t('articlesPage.next')}</span>
                <i class="fas fa-chevron-right"></i>
              </a>
            )}
          </div>
        </div>
      </div>
    </TerminalWindow>
  </div>
</BaseLayout>
