import { useContext, useEffect, useRef } from "react";

import { BreadcrumbContext, type BreadcrumbItem } from "./breadcrumb-context";

export function useBreadcrumb(trail: BreadcrumbItem[]): void {
  const { setTrail } = useContext(BreadcrumbContext);
  const trailRef = useRef(trail);
  useEffect(() => {
    trailRef.current = trail;
  });
  const key = JSON.stringify(trail.map((item) => [item.label, item.to ?? null]));
  useEffect(() => {
    setTrail(trailRef.current);
  }, [key, setTrail]);
}
