<script lang="ts">
  import '$lib/iconify-offline';
  import Icon from "@iconify/svelte";
  import { useTranslate } from "$lib/translations";
  import { T } from "$lib/translations";

  const t = useTranslate();

  let {
    currentPage = 1,
    totalPages = 1,
    basePath = "/posts",
    activeTag = null,
  }: {
    currentPage: number;
    totalPages: number;
    basePath?: string;
    activeTag?: string | null;
  } = $props();

  function tagHref(tagSlug: string | null): string {
    if (!tagSlug) return `${basePath}/`;
    return `${basePath}/tag/${encodeURIComponent(tagSlug)}/`;
  }

  function pageHref(page: number): string {
    if (page <= 1) return tagHref(activeTag ?? null);
    const tagPart = activeTag
      ? `/tag/${encodeURIComponent(activeTag)}`
      : "";
    return `${basePath}${tagPart}/page/${page}/`;
  }

  const showPagination = $derived(totalPages > 1);
  const hasPrev = $derived(currentPage > 1);
  const hasNext = $derived(currentPage < totalPages);
  const prevPage = $derived(currentPage - 1);
  const nextPage = $derived(currentPage + 1);

  const pageNumbers = $derived.by(() => {
    const max = 5;
    let start = Math.max(1, currentPage - Math.floor(max / 2));
    const end = Math.min(totalPages, start + max - 1);
    if (end - start + 1 < max) start = Math.max(1, end - max + 1);
    return Array.from({ length: end - start + 1 }, (_, i) => start + i);
  });

  const baseShape =
    "rounded-xs h-8 mx-[2px] flex justify-center items-center no-underline text-sm font-medium border transition-colors";
  const inactiveColors =
    "text-stein-700 border-stein-200 bg-white hover:bg-stein-50 hover:border-wald-300";
  const activeColors =
    "text-white border-wald-500 bg-wald-500 hover:bg-wald-600 hover:border-wald-600 pointer-events-none";
  const numberShape = "min-w-8 px-2";
  const navShape = "px-3 gap-1";
</script>

{#if showPagination}
  <nav class="inline-flex py-4 items-center" aria-label="Seitennavigation">
    <div class="flex items-center">
      {#if hasPrev}
        <a href={pageHref(prevPage)} class="{baseShape} {navShape} {inactiveColors}" aria-label={t(T.pagination_prev)}>
          <Icon icon="mdi:chevron-left" class="size-4" aria-hidden="true" />
          <span class="hidden sm:inline">{t(T.pagination_prev)}</span>
        </a>
      {/if}
      {#each pageNumbers as num}
        <a
          href={pageHref(num)}
          class="{baseShape} {numberShape} {num === currentPage ? activeColors : inactiveColors}"
          aria-current={num === currentPage ? 'page' : undefined}
        >
          {num}
        </a>
      {/each}
      {#if hasNext}
        <a href={pageHref(nextPage)} class="{baseShape} {navShape} {inactiveColors}" aria-label={t(T.pagination_next)}>
          <span class="hidden sm:inline">{t(T.pagination_next)}</span>
          <Icon icon="mdi:chevron-right" class="size-4" aria-hidden="true" />
        </a>
      {/if}
    </div>
  </nav>
{/if}
