"use client";

import { ArrowLeftIcon } from "lucide-react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";

const FROM_TO_PATH: Record<string, string> = {
  portfolio: "/artworks",
  "animal-studies": "/artworks/animalstudies",
  "animal-index": "/artworks/animalstudies/index"
};

export function ContextBackButton() {
  const router = useRouter();
  const sp = useSearchParams();
  const from = sp.get("from") ?? "";

  const target = FROM_TO_PATH[from];
  if (!target) return null;

  return (
    <div className="w-full max-w-xl">
      <Link
        href={target}
        className={[
          "inline-flex items-center gap-2 rounded-md border px-3 py-2",
          "text-sm text-muted-foreground hover:text-foreground",
          "hover:bg-muted transition-colors",
        ].join(" ")}
        onClick={(e) => {
          // If user has real history, prefer back; otherwise use link target.
          // (Prevents “dead end” if they opened single page directly in new tab.)
          if (window.history.length > 1) {
            e.preventDefault();
            router.back();
          }
        }}
      >
        <ArrowLeftIcon className="h-4 w-4" />
        Back
      </Link>
    </div>
  );
}
