"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { IconArrowLeft, IconArrowRight } from "@tabler/icons-react";

import type { DocsNavLink } from "@/lib/docs/navigation";

// Previous / next links at the bottom of each doc page.
export function DocsPager({
  lang,
  links,
  labels,
}: {
  lang: string;
  links: DocsNavLink[];
  labels: { previous: string; next: string };
}) {
  const pathname = usePathname();
  // Strip an optional trailing slash so matching works whether or not Next.js
  // appends one (otherwise the pager silently renders no prev/next links).
  const normalized = pathname.replace(/\/+$/, "");
  const current = normalized.replace(new RegExp(`^/${lang}`), "") || "/docs";
  const index = links.findIndex((link) => link.href === current);
  if (index === -1) return null;

  const prev = index > 0 ? links[index - 1] : null;
  const next = index < links.length - 1 ? links[index + 1] : null;

  return (
    <div className="border-hairline mt-16 flex items-center justify-between border-t pt-8">
      {prev ? (
        <Link
          href={`/${lang}${prev.href}`}
          className="text-ink-3 hover:text-ink-1 group flex flex-col gap-1 text-sm transition"
        >
          <span className="text-ink-4 flex items-center gap-1 text-xs">
            <IconArrowLeft className="size-3.5" /> {labels.previous}
          </span>
          <span className="font-medium">{prev.title}</span>
        </Link>
      ) : (
        <span />
      )}
      {next ? (
        <Link
          href={`/${lang}${next.href}`}
          className="text-ink-3 hover:text-ink-1 group flex flex-col items-end gap-1 text-right text-sm transition"
        >
          <span className="text-ink-4 flex items-center gap-1 text-xs">
            {labels.next} <IconArrowRight className="size-3.5" />
          </span>
          <span className="font-medium">{next.title}</span>
        </Link>
      ) : (
        <span />
      )}
    </div>
  );
}
