"use client";

/**
 * Smart back link for the manufacturer profile page.
 *
 * Renders as a server-rendered <a> linking to the directory so search
 * engines and no-JS users still get a sensible href. Client-side it
 * intercepts the click and calls `router.back()` — if the user arrived
 * here from anywhere on the BB site (homepage Content Partners hover,
 * an article body link, the directory itself) we'll return them there.
 * Falls through to the directory only when there is no in-app history.
 */
import Link from "next/link";
import { useRouter } from "next/navigation";
import type { MouseEvent } from "react";

export default function BackLink() {
  const router = useRouter();
  function onClick(e: MouseEvent<HTMLAnchorElement>) {
    if (typeof window === "undefined") return;
    // Same-origin Referer means we have somewhere to go back to. The
    // browser history length > 1 check catches the case where the user
    // opened the profile in a new tab — in that case we leave the default
    // navigation (to /manufacturers) alone.
    const sameOrigin = !!document.referrer && new URL(document.referrer).origin === window.location.origin;
    if (sameOrigin && window.history.length > 1) {
      e.preventDefault();
      router.back();
    }
  }
  return (
    <Link href="/manufacturers" onClick={onClick} className="hover:text-[#1D4ED8]">
      ← Back
    </Link>
  );
}
