<script>
  let { page = 1, totalPages = 1, onpage } = $props()

  function go(n) {
    if (n >= 1 && n <= totalPages) onpage?.(n)
  }

  let pages = $derived.by(() => {
    if (totalPages <= 7) return Array.from({ length: totalPages }, (_, i) => i + 1)
    if (page <= 4) return [1, 2, 3, 4, 5, '…', totalPages]
    if (page >= totalPages - 3) return [1, '…', totalPages - 4, totalPages - 3, totalPages - 2, totalPages - 1, totalPages]
    return [1, '…', page - 1, page, page + 1, '…', totalPages]
  })
</script>

<nav aria-label="Pagination" class="flex items-center justify-center gap-1 mt-4">
  <button
    onclick={() => go(page - 1)}
    disabled={page === 1}
    aria-label="Previous page"
    class="inline-flex items-center justify-center h-9 w-9 rounded-md border border-input bg-background text-sm hover:bg-accent hover:text-accent-foreground disabled:pointer-events-none disabled:opacity-50 transition-colors"
  >
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" class="w-4 h-4">
      <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 19.5 8.25 12l7.5-7.5" />
    </svg>
  </button>

  {#each pages as p}
    {#if p === '…'}
      <span class="inline-flex items-center justify-center h-9 w-9 text-sm text-muted-foreground select-none">…</span>
    {:else}
      <button
        onclick={() => go(p)}
        aria-current={p === page ? 'page' : undefined}
        class="inline-flex items-center justify-center h-9 w-9 rounded-md border text-sm transition-colors
               {p === page
                 ? 'border-primary bg-primary text-primary-foreground font-medium'
                 : 'border-input bg-background hover:bg-accent hover:text-accent-foreground'}"
      >{p}</button>
    {/if}
  {/each}

  <button
    onclick={() => go(page + 1)}
    disabled={page === totalPages}
    aria-label="Next page"
    class="inline-flex items-center justify-center h-9 w-9 rounded-md border border-input bg-background text-sm hover:bg-accent hover:text-accent-foreground disabled:pointer-events-none disabled:opacity-50 transition-colors"
  >
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" class="w-4 h-4">
      <path stroke-linecap="round" stroke-linejoin="round" d="m8.25 4.5 7.5 7.5-7.5 7.5" />
    </svg>
  </button>
</nav>
