<script setup>
const props = defineProps({
  imgshow: Array,
  currentPage: Number,
  perPage: Number,
});

const emit = defineEmits(['changePage']);
const pageCount = computed(() => Math.ceil(props.imgshow.length / props.perPage));
const pages = computed(() => genPages(props.currentPage, pageCount.value, 2));

function genPages(current_page, last_page, onSides = 2) {
  let pages = [];
  // Loop through
  for (let i = 1; i <= last_page; i++) {
    // Define offset
    let offset = (i == 1 || last_page) ? onSides + 1 : onSides;
    // If added
    if (i == 1 || (current_page - offset <= i && current_page + offset >= i) || 
        i == current_page || i == last_page) {
        pages.push(i);
    } else if (i == current_page - (offset + 1) || i == current_page + (offset + 1)) {
        pages.push('...');
    }
  }
  return pages;
}

function changePage(page) {
  emit('changePage', page);
}

function previous() {
  if (props.currentPage > 1) changePage(props.currentPage - 1)
}

function next() {
  if (props.currentPage < props.imgshow.length - 1) changePage(props.currentPage + 1)
}
</script>
<template>
<nav class="pagination pb-4" role="navigation" aria-label="pagination">
  <ul class="pagination-list">
    <li v-for="page in pages">
      <button v-if="typeof page === 'number'" 
        :class="['pagination-link', currentPage === page && 'is-current has-background-primary']"
        :aria-label="`Goto page ${page}`"
        :aria-current="'page'"
        @click="changePage(page)"
      >
        {{ page }}
      </button>
      <span v-else class="pagination-ellipsis">&hellip;</span>
    </li>
      <li>
        <button 
          @click="previous()"
          class="pagination-previous ml-5"
          :disabled="currentPage <= 1"
          >
          <SvgIcon v-bind="{ name: 'left1.svg', type: 'dark', size: 18, alt: 'Previous Page'}" />
        </button>
      </li>
      <li>
        <button
          @click="next()"
          class="pagination-next"
          :disabled="currentPage >= pageCount"
        >
          <SvgIcon v-bind="{ name: 'right.svg', type: 'dark', size: 18, alt: 'Next page'}" />
        </button>
      </li>
  </ul>
</nav>
</template>