<template>
    <ul v-if="pages > 1" class="pagination">
        <li v-for="i in [-1, 1]" :key="i">
            <router-link
                :to="{ query: { ...$route.query, page: page + i } }"
                :class="{ 'pointer-events-none': page + i < 1 || page + i > pages }"
            >
                <Button :icon="getIcon(i)" link />
            </router-link>
        </li>
        <li v-for="(item, i) in items" :key="i" :style="{ order: i + 2 }">
            <router-link
                :to="{ query: { ...$route.query, page: item } }"
                :class="{ 'pointer-events-none': item == page }"
            >
                <Button :label="item" link :disabled="item == page" />
            </router-link>
        </li>
        <li v-show="pages > 5" :style="{ order: pages / 2 > page ? 6 : 2 }">
            <span>...</span>
        </li>
    </ul>
</template>

<script setup>
const props = defineProps(['pages'])

const route = useRoute()
const page = computed(() => +(route.query.page || 1))

const items = ref([])

const init = () => {
    items.value = [page.value]
    let temp = 1
    while (items.value.length < 5) {
        if (page.value - temp > 0) items.value.unshift(page.value - temp)
        if (page.value + temp <= props.pages) items.value.push(page.value + temp)
        temp++
        if (temp > 10) break
    }
    if (props.pages > 5) {
        if (props.pages / 2 > page.value) items.value.push(props.pages)
        else items.value.unshift(1)
    }
}

init()
watch(() => page.value, init)

const getIcon = (i) => 'isax isax-arrow-' + (i > 0 ? 'right-3' : 'left-2')
</script>

<style lang="scss">
.pagination {
    box-shadow: 0px 2px 20px rgba(1, 86, 153, 0.08);
    @apply bg-white rounded-lg gap-2 lg:gap-4 flex flex-row-reverse items-center justify-between px-2 lg:px-4;
    @apply w-auto h-10 lg:h-[3.7rem];

    li {
        @apply h-full flex items-center;

        button {
            @apply w-5 h-5 lg:w-6 lg:h-6 p-0 rounded-sm #{!important};

            .p-button-label {
                @apply text-sm lg:text-base font-bold font-vazir lg:leading-tight text-[#8C8C8C] lg:mt-0.5;
            }

            .p-button-icon {
                @apply text-[#8C8C8C] lg:mt-[0.2rem] text-xs;
            }

            &[disabled] {
                @apply bg-[#379956] opacity-100;

                .p-button-label {
                    @apply text-white;
                }
            }

            // &:has(.p-button-icon){
            //     @apply max-lg:bg-[#F2F2F2];
            // }
        }

        & > span {
            @apply text-[#8C8C8C] font-medium font-vazir leading-[1.7rem] mt-0.5;
        }

        &:nth-child(2) {
            @apply order-last;
        }
    }
}
</style>
