import Link from "next/link";
import type { BlogPagination } from "@/app/lib/blogs";

/**
 * Builds the page numbers to show: always the first and last page, plus a
 * window around the current one, with `null` standing in for an elided run.
 * Keeps the control a fixed width regardless of how many articles exist.
 */
function buildPageList(current: number, total: number): (number | null)[] {
  if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1);

  const pages = new Set<number>([1, total, current]);
  if (current - 1 > 1) pages.add(current - 1);
  if (current + 1 < total) pages.add(current + 1);

  const sorted = [...pages].sort((a, b) => a - b);
  const out: (number | null)[] = [];
  let previous = 0;
  for (const page of sorted) {
    if (previous && page - previous > 1) out.push(null);
    out.push(page);
    previous = page;
  }
  return out;
}

function href(page: number): string {
  return page <= 1 ? "/blogs" : `/blogs?page=${page}`;
}

export function BlogPaginationNav({ pagination }: { pagination: BlogPagination }) {
  const { page, pageCount } = pagination;
  if (pageCount <= 1) return null;

  const pages = buildPageList(page, pageCount);

  return (
    <nav className="blog-pagination" aria-label="Article pagination">
      {page > 1 ? (
        <Link href={href(page - 1)} data-oxy-href={href(page - 1)} className="blog-page-link" rel="prev">
          Previous
        </Link>
      ) : (
        <span className="blog-page-link is-disabled" aria-hidden="true">
          Previous
        </span>
      )}

      <span className="blog-pagination-pages">
        {pages.map((entry, i) =>
          entry === null ? (
            <span key={`gap-${i}`} className="blog-page-gap" aria-hidden="true">
              &hellip;
            </span>
          ) : entry === page ? (
            <span key={entry} className="blog-page-link is-current" aria-current="page">
              {entry}
            </span>
          ) : (
            <Link key={entry} href={href(entry)} data-oxy-href={href(entry)} className="blog-page-link">
              {entry}
            </Link>
          )
        )}
      </span>

      {page < pageCount ? (
        <Link href={href(page + 1)} data-oxy-href={href(page + 1)} className="blog-page-link" rel="next">
          Next
        </Link>
      ) : (
        <span className="blog-page-link is-disabled" aria-hidden="true">
          Next
        </span>
      )}
    </nav>
  );
}
