<script lang="ts">
    import { onMount } from "svelte";
    let {
        currentPag,
        cantpag,
        queryPag,
        centrado = false,
    }: {
        currentPag: number;
        cantpag: number;
        queryPag: (a: number) => void;
        centrado: boolean;
    } = $props();

    function getVisiblePages() {
        if (!centrado || cantpag <= 5) {
            return Array.from({ length: cantpag }, (_, i) => i + 1);
        }

        if (currentPag <= 3) {
            return [1, 2, 3, 4, 5];
        } else if (currentPag >= cantpag - 2) {
            return [
                cantpag - 4,
                cantpag - 3,
                cantpag - 2,
                cantpag - 1,
                cantpag,
            ];
        } else {
            return [
                currentPag - 2,
                currentPag - 1,
                currentPag,
                currentPag + 1,
                currentPag + 2,
            ];
        }
    }
    let visiblePages = $derived.by(getVisiblePages);
</script>

{#if cantpag > 1}
    <nav aria-label="Paginador">
        <ul class="pagination">
            <li class="page-item {currentPag === 1 ? 'disabled' : ''}">
                <button
                    class="page-link"
                    onclick={() => currentPag > 1 && queryPag(currentPag - 1)}
                >
                    Anterior
                </button>
            </li>
            {#each visiblePages as num}
                <li class="page-item">
                    <button
                        class="page-link"
                        class:active={currentPag === num}
                        onclick={() => queryPag(num)}
                    >
                        {String(num)}
                    </button>
                </li>
            {/each}
            <li class="page-item {currentPag === cantpag ? 'disabled' : ''}">
                <button
                    class="page-link"
                    onclick={() =>
                        currentPag < cantpag && queryPag(currentPag + 1)}
                    >Siguiente</button
                >
            </li>
        </ul>
    </nav>
{/if}
