<script setup lang="ts">
import { computed } from "vue";

const props = defineProps<{
  total: number;
  limit: number;
  offset: number;
}>();

const emit = defineEmits<{
  "update:offset": [offset: number];
}>();

const totalPages = computed(() => Math.ceil(props.total / props.limit) || 1);
const currentPage = computed(() => Math.floor(props.offset / props.limit) + 1);

const pages = computed(() => {
  const total = totalPages.value;
  const current = currentPage.value;
  const result: (number | "...")[] = [];

  for (let i = 1; i <= total; i++) {
    if (i === 1 || i === total || (i >= current - 1 && i <= current + 1)) {
      result.push(i);
    } else if (result[result.length - 1] !== "...") {
      result.push("...");
    }
  }
  return result;
});

function goToPage(page: number) {
  emit("update:offset", (page - 1) * props.limit);
}
</script>

<template>
  <div v-if="totalPages > 1" class="pagination">
    <button
      class="page-btn"
      :disabled="currentPage === 1"
      @click="goToPage(currentPage - 1)"
    >
      Prev
    </button>
    <template v-for="(page, idx) in pages" :key="idx">
      <span v-if="page === '...'" class="ellipsis">...</span>
      <button
        v-else
        class="page-btn"
        :class="{ active: page === currentPage }"
        @click="goToPage(page as number)"
      >
        {{ page }}
      </button>
    </template>
    <button
      class="page-btn"
      :disabled="currentPage === totalPages"
      @click="goToPage(currentPage + 1)"
    >
      Next
    </button>
  </div>
</template>

<style scoped>
.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.25rem;
  margin-top: 1.5rem;
}
.page-btn {
  padding: 0.35rem 0.7rem;
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm);
  background: var(--color-bg-card);
  color: var(--color-text);
  cursor: pointer;
  font-size: 0.85rem;
}
.page-btn:hover:not(:disabled) {
  background: var(--color-bg-secondary);
}
.page-btn:disabled {
  opacity: 0.4;
  cursor: default;
}
.page-btn.active {
  background: var(--color-primary);
  color: #fff;
  border-color: var(--color-primary);
}
.ellipsis {
  padding: 0 0.25rem;
  color: var(--color-text-muted);
}
</style>
