---
// 通用分页组件
export interface Props {
  currentPage: number;
  totalPages: number;
  baseUrl?: string; // 基础链接，拼接?page=xxx
  pageParam?: string; // 分页参数名，默认'page'
}
const { currentPage = 1, totalPages = 1, baseUrl = '', pageParam = 'page' } = Astro.props;

function getPageUrl(page: number) {
//   if (!baseUrl) return `?${pageParam}=${page}`;
  // 若baseUrl已带?，则拼接&，否则?
  return baseUrl +  `${page}`;
}

const showPages = [];
if (totalPages <= 7) {
  for (let i = 1; i <= totalPages; i++) showPages.push(i);
} else {
  if (currentPage <= 4) {
    showPages.push(1, 2, 3, 4, 5, '...', totalPages);
  } else if (currentPage >= totalPages - 3) {
    showPages.push(1, '...', totalPages - 4, totalPages - 3, totalPages - 2, totalPages - 1, totalPages);
  } else {
    showPages.push(1, '...', currentPage - 1, currentPage, currentPage + 1, '...', totalPages);
  }
}
console.log(showPages)
---
<nav class="pagination">
  <ul>
    <li class={currentPage == 1 ? 'disabled' : ''}>
      <a href={currentPage == 1 ? undefined : getPageUrl(currentPage - 1)} aria-label="上一页">«</a>
    </li>
    {showPages.map(page =>
      typeof page == 'number' ? (
        <li class={page == currentPage ? 'active' : ''}>
          <a href={getPageUrl(page)}>{page}</a>
        </li>
      ) : (
        <li class="ellipsis">{page}</li>
      )
    )}
    <li class={currentPage == totalPages ? 'disabled' : ''}>
      <a href={currentPage == totalPages ? undefined : getPageUrl(currentPage + 1)} aria-label="下一页">»</a>
    </li>
  </ul>
</nav>

<style>
.pagination {
  display: flex;
  justify-content: center;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}
.pagination ul {
  display: flex;
  gap: 0.5rem;
  list-style: none;
  padding: 0;
  margin: 0;
}
.pagination li {
  min-width: 32px;
  text-align: center;
  border-radius: 4px;
  background: #fff;
  color: #333;
  font-size: 1rem;
  user-select: none;
  transition: background 0.2s, color 0.2s;
}
.pagination li.active {
  background: #F4BB36;
  color: #fff;
  font-weight: bold;
}
.pagination li.disabled a {
  pointer-events: none;
  color: #bbb;
}
.pagination li a {
  display: block;
  /* padding: 0.5rem 0.75rem; */
  color: inherit;
  text-decoration: none;
  border-radius: 4px;
}
.pagination li.ellipsis {
  background: none;
  color: #bbb;
  pointer-events: none;
  min-width: 24px;
  padding: 0.5rem 0.2rem;
}
@media (max-width: 600px) {
  .pagination {
    /* margin: 1rem 0; */
    font-size: 0.95rem;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
  }
  .pagination ul {
    gap: 0.15rem;
  }
  .pagination li {
    min-width: 28px;
    font-size: 0.95rem;
  }
  .pagination li a {
    padding: 0.35rem 0.5rem;
    font-size: 0.95rem;
  }
}
</style> 