import Link from "next/link";
import { ChevronRight, Home } from "lucide-react";
import { clsx } from "clsx";

export type BreadcrumbItem = {
  label: string;
  href?: string;
};

type Props = {
  items: BreadcrumbItem[];
  className?: string;
  /** When true, prepend a Home icon link to /. */
  showHome?: boolean;
};

/**
 * Accessible breadcrumb trail used on product detail pages. The last item is
 * rendered as plain text (aria-current=page); intermediate items are links.
 * Home link is optional but on by default to match the rest of the site.
 */
export function Breadcrumbs({ items, className, showHome = true }: Props) {
  if (items.length === 0) return null;

  const full: BreadcrumbItem[] = showHome
    ? [{ label: "Home", href: "/" }, ...items]
    : items;

  return (
    <nav
      aria-label="Breadcrumb"
      className={clsx(
        "text-[12px] font-medium text-[var(--color-slate)]",
        className,
      )}
    >
      <ol className="flex flex-wrap items-center gap-1.5">
        {full.map((item, i) => {
          const isLast = i === full.length - 1;
          const isHome = showHome && i === 0;
          return (
            <li key={`${item.label}-${i}`} className="flex items-center gap-1.5">
              {i > 0 && (
                <ChevronRight
                  className="h-3 w-3 shrink-0 text-[var(--color-slate)]/60"
                  aria-hidden
                />
              )}
              {item.href && !isLast ? (
                <Link
                  href={item.href}
                  className="inline-flex items-center gap-1 rounded px-1 py-0.5 transition-colors hover:bg-[var(--color-mist)] hover:text-[var(--color-blue)]"
                >
                  {isHome ? (
                    <Home className="h-3.5 w-3.5" aria-hidden />
                  ) : null}
                  <span className={isHome ? "sr-only" : undefined}>
                    {item.label}
                  </span>
                  {!isHome && <span aria-hidden className="hidden" />}
                </Link>
              ) : (
                <span
                  aria-current={isLast ? "page" : undefined}
                  className={clsx(
                    "inline-flex items-center gap-1 px-1 py-0.5",
                    isLast && "font-semibold text-[var(--color-ink)]",
                  )}
                >
                  {isHome ? (
                    <Home className="h-3.5 w-3.5" aria-hidden />
                  ) : null}
                  <span className={isHome ? "sr-only" : undefined}>
                    {item.label}
                  </span>
                </span>
              )}
            </li>
          );
        })}
      </ol>
    </nav>
  );
}
