<script setup>
  import { computed } from 'vue'
  const props = defineProps(['pageNumber', 'pageTotal', 'maxItemDisplayed']);
  const emit = defineEmits(['pageChange']);

  const paginatedItems = computed(() => {
    let items = [];
    if (props.pageTotal > props.maxItemDisplayed) {

      //number of pages we can display before and after the current page
      const maxNumberOfItemsAroundCurrentItem = Math.floor((props.maxItemDisplayed - 2) / 2);

      items.push(1);
      //compute first item number
      let firstItemNumber;
      let lastItemNumber;

      if (props.pageNumber - maxNumberOfItemsAroundCurrentItem < 4) {
        //starting at the left
        firstItemNumber = 2;
        lastItemNumber = props.maxItemDisplayed;
      } else if (props.pageNumber + maxNumberOfItemsAroundCurrentItem > props.pageTotal - 2) {
        //starting at the right
        firstItemNumber = props.pageTotal - props.maxItemDisplayed + 1;
        lastItemNumber = props.pageTotal - 1;
      } else {
        firstItemNumber = props.pageNumber - maxNumberOfItemsAroundCurrentItem;
        lastItemNumber = props.pageNumber + maxNumberOfItemsAroundCurrentItem;
      }

      if (firstItemNumber !== 2) {
        items.push(-1);
      }

      for (let i = firstItemNumber; i <= lastItemNumber; i++) {
        items.push(i);
      }
      if (lastItemNumber !== props.pageTotal - 1) {
        items.push(-1);
      }
      items.push(props.pageTotal);
    } else {
      for (let i = 1; i <= props.pageTotal; i++) {
        items.push(i);
      }
    }
    return items;})
</script>

<template>
  <nav v-if="props.pageTotal > 1" class="pagination" role="navigation" aria-label="pagination">
    <a href="#" v-if="props.pageNumber > 1"
             @click="$emit('pageChange', Math.max(1, props.pageNumber - 1))"
             class="pagination-previous">
      {{$t('pagination.previous')}}
    </a>
  <a href="#" v-if="props.pageNumber < props.pageTotal"
    @click="$emit('pageChange', props.pageNumber + 1)"
    class="pagination-next">
    {{$t('pagination.next')}}
  </a>
  <ul class="pagination-list">
    <li v-for="item in paginatedItems" :key="item">
      <span v-if="item === -1" class="pagination-ellipsis">&hellip;</span>
      <a v-else
         href="#"
         @click="$emit('pageChange', item)"
         class="pagination-link"
         :class="item === props.pageNumber ? 'is-current' : ''"
         :aria-current="item === props.pageNumber ? 'page' : null"
         :aria-label="$t(item === props.pageNumber ? 'pagination.page' : 'pagination.goto', {pageNumber: item})">
        {{ item }}
      </a>
    </li>
  </ul>
</nav>
</template>


<style scoped>
</style>

