<script lang="ts">
  import { Button } from "$lib/components/ui/button";
  import { _ } from "svelte-i18n";

  interface Props {
    currentPage: number;
    totalPages: number;
    onPageChange: (page: number) => void;
  }

  let { currentPage, totalPages, onPageChange }: Props = $props();

  const pageNumbers = $derived(() => {
    const pages: (number | -1)[] = [];
    if (totalPages <= 7) {
      for (let i = 1; i <= totalPages; i++) pages.push(i);
    } else {
      pages.push(1);
      if (currentPage > 3) pages.push(-1);
      for (
        let i = Math.max(2, currentPage - 1);
        i <= Math.min(totalPages - 1, currentPage + 1);
        i++
      )
        pages.push(i);
      if (currentPage < totalPages - 2) pages.push(-1);
      pages.push(totalPages);
    }
    return pages;
  });
</script>

{#if totalPages > 1}
  <div class="flex items-center gap-1">
    <Button
      variant="outline"
      disabled={currentPage <= 1}
      onclick={() => onPageChange(currentPage - 1)}
    >
      {$_("common.previous")}
    </Button>
    {#each pageNumbers() as p, i (i)}
      {#if p === -1}
        <span class="px-2 text-muted-foreground select-none">…</span>
      {:else}
        <Button
          variant={p === currentPage ? "default" : "outline"}
          class="min-w-9"
          onclick={() => onPageChange(p)}
        >
          {p}
        </Button>
      {/if}
    {/each}
    <Button
      variant="outline"
      disabled={currentPage >= totalPages}
      onclick={() => onPageChange(currentPage + 1)}
    >
      {$_("common.next")}
    </Button>
  </div>
{/if}
