import { useMemo } from "react";
import { ChevronRight } from "lucide-react";

interface PageBreadcrumbProps {
  pages: Array<{
    id: string;
    parentPageId: string | null;
    title: string;
  }>;
  activePageId: string;
  onNavigate: (pageId: string) => void;
}

export function PageBreadcrumb({
  pages,
  activePageId,
  onNavigate,
}: PageBreadcrumbProps) {
  const trail = useMemo(() => {
    const byId = new Map(pages.map((p) => [p.id, p]));
    const result: Array<{ id: string; title: string }> = [];
    let current = byId.get(activePageId);

    while (current) {
      result.unshift({ id: current.id, title: current.title });
      current = current.parentPageId
        ? byId.get(current.parentPageId)
        : undefined;
    }
    return result;
  }, [pages, activePageId]);

  return (
    <nav className="flex items-center gap-1 text-sm text-muted-foreground">
      {trail.map((item, i) => (
        <span key={item.id} className="flex items-center gap-1">
          {i > 0 && <ChevronRight className="h-3 w-3" />}
          {i < trail.length - 1 ? (
            <button
              onClick={() => onNavigate(item.id)}
              className="hover:text-foreground transition-colors"
            >
              {item.title}
            </button>
          ) : (
            <span className="text-foreground font-medium">{item.title}</span>
          )}
        </span>
      ))}
    </nav>
  );
}
