import { getTranslations } from 'next-intl/server'
import { Link } from '@/i18n/navigation'

/**
 * Paginación por número de página. `hrefFor(p)` construye la ruta de cada página
 * (p.ej. `/forum/5?page=2`). No renderiza nada si solo hay una página.
 */
export async function Pagination({
  page,
  totalPages,
  hrefFor,
}: {
  page: number
  totalPages: number
  hrefFor: (page: number) => string
}) {
  if (totalPages <= 1) return null
  const t = await getTranslations('Common')

  // Ventana de páginas alrededor de la actual.
  const from = Math.max(1, page - 2)
  const to = Math.min(totalPages, page + 2)
  const pages: number[] = []
  for (let p = from; p <= to; p++) pages.push(p)

  const cls = (active: boolean) => `ns-page-link${active ? ' ns-page-current' : ''}`

  return (
    <nav className="centered separate" aria-label="pagination">
      {page > 1 && (
        <Link href={hrefFor(page - 1)} className="ns-page-link">
          ← {t('prev')}
        </Link>
      )}
      {from > 1 && (
        <>
          <Link href={hrefFor(1)} className="ns-page-link">
            1
          </Link>
          {from > 2 && <span className="third-brown">…</span>}
        </>
      )}
      {pages.map((p) => (
        <Link key={p} href={hrefFor(p)} className={cls(p === page)} aria-current={p === page ? 'page' : undefined}>
          {p}
        </Link>
      ))}
      {to < totalPages && (
        <>
          {to < totalPages - 1 && <span className="third-brown">…</span>}
          <Link href={hrefFor(totalPages)} className="ns-page-link">
            {totalPages}
          </Link>
        </>
      )}
      {page < totalPages && (
        <Link href={hrefFor(page + 1)} className="ns-page-link">
          {t('next')} →
        </Link>
      )}
    </nav>
  )
}
