<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);

	const makePageUrl = (params: URLSearchParams, pageNumber: number) => {
		const searchParams = new URLSearchParams(params);
		searchParams.set('page', String(pageNumber));
		return searchParams.toString();
	};
</script>

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

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

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

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

	.page-button {
		--in-page-button-size: 28px;
		display: block;
		background-color: var(--in-button-primary-background);
		color: var(--in-button-primary-color);
		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: var(--in-button-primary-hover-background);
		}

		&.disabled {
			user-select: none;
			pointer-events: none;
			background-color: var(--in-button-primary-disabled-background);
			color: var(--in-button-primary-disabled-color);
		}
	}
</style>
