import { defineComponent, h } from "vue";
import { cx, iconNode } from "../utils.js";

export default defineComponent({
	name: "GnPagination",
	props: {
		page: { type: Number, required: true },
		totalPages: { type: Number, required: true },
		ariaLabel: { type: String, default: "Pagination" }
	},
	emits: ["update:page"],
	setup(props, { emit }) {
		const setPage = page => {
			if(page >= 1 && page <= props.totalPages && page !== props.page) {
				emit("update:page", page);
			}
		};

		return () => {
			const pages = Array.from({ length: props.totalPages }, (_, index) => index + 1);

			return h("nav", { class: "pagination", "aria-label": props.ariaLabel }, [
				h("button", {
					class: "pagination-item",
					type: "button",
					disabled: props.page <= 1,
					onClick: () => setPage(props.page - 1)
				}, [iconNode("ph-arrow-left")]),
				pages.map(page => h("button", {
					class: cx("pagination-item", { "pagination-item-active": page === props.page }),
					type: "button",
					"aria-current": page === props.page ? "page" : undefined,
					onClick: () => setPage(page)
				}, page)),
				h("button", {
					class: "pagination-item",
					type: "button",
					disabled: props.page >= props.totalPages,
					onClick: () => setPage(props.page + 1)
				}, [iconNode("ph-arrow-right")])
			]);
		};
	}
});
