<script lang="ts">
	import type { PaginationMeta } from '$lib/types';
	import { page } from '$app/stores';
	import { t } from '$lib/i18n';

	export let meta: PaginationMeta;
	$: pageNum = Number($page.url.searchParams.get('page')) || 1;
	$: firstPage = pageNum === 1;
	$: lastPage = pageNum === meta.pageCount;
	$: pageButtons = Array.from({ length: meta.pageCount }, (_, i) => i + 1);
</script>

<nav class="pager">
	<a
		class="page-button page-prev {firstPage ? 'disabled' : ''}"
		href={`?page=${pageNum - 1}`}
		tabindex={firstPage ? -1 : 0}
		aria-label={$t('common.previous')}
		aria-disabled={firstPage}>&lt;&lt;</a
	>

	{#each pageButtons as buttonNumber}
		{@const active = buttonNumber === pageNum}
		<a
			class="page-button page-link {active ? 'disabled' : ''}"
			href={`?page=${buttonNumber}`}
			tabindex={active ? -1 : 0}
			aria-label={`${$t('common.page')} ${buttonNumber}`}
			aria-disabled={active}>{buttonNumber}</a
		>
	{/each}

	<a
		class="page-button page-prev {lastPage ? 'disabled' : ''}"
		tabindex={lastPage ? -1 : 0}
		href={`?page=${pageNum + 1}`}
		aria-label={$t('common.next')}
		aria-disabled={lastPage}>&gt;&gt;</a
	>
</nav>

<style>
	.pager {
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.page-button {
		--in-page-button-size: 28px;
		display: block;
		background-color: #fff;
		color: #000;
		min-width: var(--in-page-button-size);
		height: var(--in-page-button-size);
		line-height: var(--in-page-button-size);
		text-align: center;
		box-shadow: 0 0 4px rgba(0, 0, 0, 0.25);
		border-radius: 4px;
		text-decoration: none;

		&:hover {
			background-color: #ececec;
		}

		&.disabled {
			user-select: none;
			pointer-events: none;
			background-color: #ececec;
			color: #616161;
		}
	}
</style>
