---
import { fmtDate, paginationWindow, type Article, type CategoryInfo } from "../lib/articles";

interface Props {
  items: Article[];
  categories: CategoryInfo[];
  totalCount: number;
  activeSlug: string | null;
  currentPage: number;
  lastPage: number;
  basePath: string;
}

const { items, categories, totalCount, activeSlug, currentPage, lastPage, basePath } = Astro.props as Props;
const pageHref = (page: number) => page <= 1 ? `${basePath}/` : `${basePath}/page/${page}/`;
const pages = paginationWindow(currentPage, lastPage);
---
<nav class="article-tabs" aria-label="学习资讯分类">
  <a class:list={["article-tab", { active: activeSlug === null }]} href="/articles/">全部 <span>{totalCount}</span></a>
  {categories.map((category) => (
    <a class:list={["article-tab", { active: activeSlug === category.slug }]} href={`/articles/topic/${category.slug}/`}>
      {category.name} <span>{category.count}</span>
    </a>
  ))}
</nav>

{items.length ? (
  <div class="article-grid">
    {items.map((item) => (
      <article class="article-card" data-reveal>
        <a href={`/articles/${item.id}/`} aria-label={`阅读：${item.data.title}`}>
          <div class="article-card__meta">
            <span>{item.data.category}</span><time datetime={fmtDate(item.data.date)}>{fmtDate(item.data.date)}</time>
          </div>
          <h2>{item.data.title}</h2>
          <p>{item.data.excerpt}</p>
          <strong>阅读全文</strong>
        </a>
      </article>
    ))}
  </div>
) : <p class="article-empty">该分类暂时还没有文章。</p>}

{lastPage > 1 && (
  <nav class="article-pagination" aria-label="资讯分页">
    {currentPage > 1 ? <a href={pageHref(currentPage - 1)} rel="prev">←</a> : <span aria-hidden="true">←</span>}
    {pages.map((page) => page === 0
      ? <span class="gap">…</span>
      : page === currentPage
        ? <span class="active" aria-current="page">{page}</span>
        : <a href={pageHref(page)}>{page}</a>
    )}
    {currentPage < lastPage ? <a href={pageHref(currentPage + 1)} rel="next">→</a> : <span aria-hidden="true">→</span>}
  </nav>
)}
