import { ref, computed } from 'vue'

/**
 * Composable for client-side pagination of an already-loaded array.
 *
 * @param {import('vue').Ref<Array>|import('vue').ComputedRef<Array>} items - reactive array to paginate
 * @param {import('vue').Ref<number>} pageSize - reactive page size
 * @returns {{ currentPage, totalPages, totalItems, paginatedItems, goToPage }}
 */
export function useClientPagination(items, pageSize) {
	const currentPage = ref(1)

	const totalItems = computed(() => items.value.length)

	const totalPages = computed(() => Math.max(1, Math.ceil(totalItems.value / pageSize.value)))

	const paginatedItems = computed(() => {
		const start = (currentPage.value - 1) * pageSize.value
		return items.value.slice(start, start + pageSize.value)
	})

	function goToPage(page) {
		if (page >= 1 && page <= totalPages.value) {
			currentPage.value = page
		}
	}

	function resetPage() {
		currentPage.value = 1
	}

	return { currentPage, totalPages, totalItems, paginatedItems, goToPage, resetPage }
}
