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

  function go(n) {
    if (n >= 1 && n <= totalPages) {
      const y = window.scrollY
      onpage?.(n)
      requestAnimationFrame(() => requestAnimationFrame(() => window.scrollTo({ top: y, behavior: 'instant' })))
    }
  }

  function noFocusScroll(e) {
    e.preventDefault()
  }

  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 mt-4">
  <div class="flex items-center border border-input rounded-lg bg-background overflow-hidden divide-x divide-input shadow-sm">
    <button
      onmousedown={noFocusScroll}
      onclick={() => go(page - 1)}
      disabled={page === 1}
      aria-label="Previous page"
      class="inline-flex items-center justify-center h-9 w-10 text-xs hover:bg-accent hover:text-accent-foreground disabled:pointer-events-none disabled:opacity-40 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-10 text-xs text-muted-foreground select-none">…</span>
      {:else}
        <button
          onmousedown={noFocusScroll}
          onclick={() => go(p)}
          aria-current={p === page ? 'page' : undefined}
          class="inline-flex items-center justify-center h-9 w-10 text-xs transition-colors
                 {p === page ? 'bg-muted font-medium' : 'hover:bg-accent hover:text-accent-foreground'}"
        >{p}</button>
      {/if}
    {/each}

    <button
      onmousedown={noFocusScroll}
      onclick={() => go(page + 1)}
      disabled={page === totalPages}
      aria-label="Next page"
      class="inline-flex items-center justify-center h-9 w-10 text-xs hover:bg-accent hover:text-accent-foreground disabled:pointer-events-none disabled:opacity-40 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>
  </div>
</nav>
