import { NAV_SECTIONS, type NavItem } from "@/lib/nav";
import type { Crumb } from "@/components/ui/breadcrumbs";

/**
 * Breadcrumb trail for a workspace route.
 *
 * Labels come from the same nav model the sidebar renders, so a trail can never
 * disagree with the menu. The page's own name is normally omitted (the heading
 * right below it already says it) unless the caller passes `self`.
 */

/** Every nav item, flattened, for lookup. */
const ALL_ITEMS: NavItem[] = NAV_SECTIONS.flatMap((section) => section.items);

/** The item whose href is the longest prefix of `pathname`. */
function matchItem(pathname: string): NavItem | null {
  let best: NavItem | null = null;
  for (const item of ALL_ITEMS) {
    const matches = pathname === item.href || pathname.startsWith(`${item.href}/`);
    if (!matches) continue;
    if (!best || item.href.length > best.href.length) best = item;
  }
  return best;
}

/**
 * Build the trail for `pathname`.
 *
 * @param pathname Current route, e.g. `/dashboard/courses/abc`.
 * @param self     Label for the current page, appended as the final crumb.
 * @param parents  Extra links to insert between the nav item and `self`.
 */
export function routeCrumbs(
  pathname: string,
  self?: string,
  parents: Crumb[] = []
): Crumb[] {
  const item = matchItem(pathname);
  const crumbs: Crumb[] = [];

  // A nested page under a section (e.g. /courses/abc) gets its section as a link.
  if (item && item.href !== pathname) {
    crumbs.push({ label: item.label, href: item.href });
  }

  crumbs.push(...parents);

  if (self) crumbs.push({ label: self });
  return crumbs;
}
