import { Breadcrumb } from 'react-bootstrap';
import { Link, useMatches } from 'react-router-dom';

export interface CrumbHandle {
  crumb: string;
}

/**
 * Reads `handle.crumb` from each matched route and renders a Bootstrap
 * breadcrumb. Routes that don't define a handle are skipped.
 */
export default function AppBreadcrumb() {
  const matches = useMatches();

  const crumbs = matches
    .filter((m) => m.handle && (m.handle as CrumbHandle).crumb)
    .map((m) => ({
      label: (m.handle as CrumbHandle).crumb,
      path: m.pathname,
    }));

  if (crumbs.length <= 1) return null;

  return (
    <Breadcrumb className="mb-3">
      {crumbs.map((c, i) => {
        const isLast = i === crumbs.length - 1;
        return isLast ? (
          <Breadcrumb.Item key={c.path} active>
            {c.label}
          </Breadcrumb.Item>
        ) : (
          <Breadcrumb.Item key={c.path} linkAs={Link} linkProps={{ to: c.path }}>
            {c.label}
          </Breadcrumb.Item>
        );
      })}
    </Breadcrumb>
  );
}
