<script lang="ts">
  export let totalPages: number = 1;
  export let currentPage: number = 1;
  export let goToPage: (page: number) => void;

  // 🗝️ Smart page window logic with ellipsis
  $: pageWindow = [];

  if (totalPages <= 5) {
    // For small sets, just show all pages
    pageWindow = Array(totalPages).fill(0).map((_, i) => i + 1);
  } else {
    pageWindow = [1];

    if (currentPage > 3) pageWindow.push("...");

    const start = Math.max(2, currentPage - 1);
    const end = Math.min(totalPages - 1, currentPage + 1);

    for (let i = start; i <= end; i++) {
      pageWindow.push(i);
    }

    if (currentPage < totalPages - 2) pageWindow.push("...");

    pageWindow.push(totalPages);
  }
</script>

<div class="flex space-x-1 items-center text-sm">
  <!-- Previous Button -->
  <button
    class="px-3 py-1 rounded border border-gray-300 bg-white hover:bg-gray-100 disabled:opacity-50"
    on:click={() => goToPage(currentPage - 1)}
    disabled={currentPage === 1}
  >
    Previous
  </button>

  <!-- Page Numbers + Ellipsis -->
  {#each pageWindow as page, i}
    {#if page === "..."}
      <span key={i}>...</span>
    {:else}
      <button
        class="px-3 py-1 rounded border text-sm
          {currentPage === page
            ? 'bg-blue-600 text-white border-blue-600'
            : 'bg-white border-gray-300 hover:bg-gray-100'}"
        on:click={() => goToPage(page)}
      >
        {page}
      </button>
    {/if}
  {/each}

  <!-- Next Button -->
  <button
    class="px-3 py-1 rounded border border-gray-300 bg-white hover:bg-gray-100 disabled:opacity-50"
    on:click={() => goToPage(currentPage + 1)}
    disabled={currentPage === totalPages}
  >
    Next
  </button>
</div>
