import Link from "next/link";
import { ChevronRight } from "lucide-react";
import { cn } from "@/lib/utils";

/**
 * Breadcrumb trail.
 *
 * Renders the hierarchy from the workspace root down to the current page. The
 * "Dasbor" root is prepended automatically, intermediate items are links, and
 * the final item is the current page — rendered as plain text with
 * `aria-current` so assistive technology announces it correctly.
 */

export interface Crumb {
  label: string;
  /** Omit on the final item — the current page is not a link. */
  href?: string;
}

const ROOT: Crumb = { label: "Dasbor", href: "/dashboard" };

export function Breadcrumbs({ items, className }: { items: Crumb[]; className?: string }) {
  if (items.length === 0) return null;

  // Pages that are themselves under the root get "Dasbor" prepended; a trail
  // that already starts at the root is left as-is.
  const trail: Crumb[] =
    items[0]?.href === ROOT.href || items[0]?.label === ROOT.label ? items : [ROOT, ...items];

  return (
    <nav aria-label="Breadcrumb" className={cn("text-xs text-tertiary", className)}>
      <ol className="flex flex-wrap items-center gap-1.5">
        {trail.map((crumb, index) => {
          const isLast = index === trail.length - 1;
          return (
            <li key={`${crumb.label}-${index}`} className="flex min-w-0 items-center gap-1.5">
              {index > 0 ? (
                <ChevronRight
                  className="size-3 shrink-0 text-tertiary/50"
                  aria-hidden="true"
                />
              ) : null}
              {isLast || !crumb.href ? (
                <span
                  className={cn("truncate", isLast && "font-medium text-secondary")}
                  aria-current={isLast ? "page" : undefined}
                  title={crumb.label}
                >
                  {crumb.label}
                </span>
              ) : (
                <Link
                  href={crumb.href}
                  className="shrink-0 transition-colors hover:text-primary"
                >
                  {crumb.label}
                </Link>
              )}
            </li>
          );
        })}
      </ol>
    </nav>
  );
}
