"use client";

import { usePathname } from "next/navigation";
import LanguageAwareLink from "@/src/lib/utils/LanguageAwareLink";
import { useNavHistory } from "@/src/lib/context/NavHistoryContext";
import { fallbackEntry } from "@/src/lib/utils/navLabels";

interface BackButtonProps {
  /** Extra classes on the link. Defaults suit the white-on-blue hero banners. */
  className?: string;
  /** Overrides the "Go back to " prefix. */
  prefix?: string;
}

export default function BackButton({ className = "", prefix = "Go back to" }: BackButtonProps) {
  const { previous } = useNavHistory();
  const pathname = usePathname();

  if (!pathname || pathname === "/") return null;

  // No history (direct landing, shared link, fresh tab) → walk up to the
  // nearest named ancestor so the button is never a dead end.
  const target = previous ?? fallbackEntry(pathname);

  // The label is "Back navigation" rather than "Back" because ScrollToTopButton
  // already claims aria-label="Back".
  return (
    <nav aria-label="Back navigation" className="max-w-[1300px] mx-auto w-full">
      <LanguageAwareLink
        href={target.href}
        className={`group inline-flex items-center gap-[16px] text-white transition-opacity hover:opacity-80 ${className}`}
      >
        <span
          aria-hidden="true"
          className="flex h-[24px] w-[24px] shrink-0 items-center justify-center rounded-full border-[1.5px] border-current transition-transform group-hover:-translate-x-0.5"
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" aria-hidden="true">
            <path
              d="M19 12H5m0 0 7-7m-7 7 7 7"
              stroke="currentColor"
              strokeWidth="1.75"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
        </span>
        <span className="font-[family-name:var(--font-Noto_Sans)] text-[13px] font-light leading-none tracking-[0.02em]">
          {prefix} {target.label}
        </span>
      </LanguageAwareLink>
    </nav>
  );
}
