import { Link } from 'react-router';
import { ChevronRight, Home } from 'lucide-react';

type BreadcrumbProps = {
  path: string;
  onNavigate: (path: string) => void;
  basePath?: string;
  /**
   * Query string for a folder, when this browser owns the address bar. Given, the crumbs are real links
   * and cmd-click opens the folder in a new tab; absent (a dashboard panel, the widget) they stay buttons,
   * because that browser's location is not in the URL and there would be nothing for the new tab to read.
   */
  searchForPath?: ((path: string) => string) | null;
};

export const Breadcrumb = ({ path, onNavigate, basePath = '/', searchForPath }: BreadcrumbProps) => {
  const relativePath = basePath !== '/' && path.startsWith(basePath) ? path.slice(basePath.length) : path;
  const segments = relativePath.split('/').filter(Boolean);

  const Crumb = ({ to, children, className }: { to: string; children: React.ReactNode; className: string }) =>
    searchForPath ? (
      <Link to={{ search: searchForPath(to) }} className={className}>
        {children}
      </Link>
    ) : (
      <button onClick={() => onNavigate(to)} className={className}>
        {children}
      </button>
    );

  return (
    <div className="shrink-0 border-b border-duck-dark/10 px-4 py-2">
      <nav className="flex items-center gap-1 text-sm flex-wrap">
        <Crumb
          to={basePath}
          className="flex items-center gap-1 text-duck-forest hover:text-duck-teal transition-colors cursor-pointer font-medium"
        >
          <Home className="h-4 w-4" />
          <span>{basePath === '/' ? 'home' : basePath.split('/').pop()}</span>
        </Crumb>

        {segments.map((segment, i) => {
          const relative = '/' + segments.slice(0, i + 1).join('/');
          const segmentPath = basePath === '/' ? relative : basePath + relative;
          const isLast = i === segments.length - 1;

          return (
            <span key={segmentPath} className="flex items-center gap-1">
              <ChevronRight className="h-4 w-4 text-duck-dark/40" />
              {isLast ? (
                <span className="text-duck-dark font-semibold">{segment}</span>
              ) : (
                <Crumb
                  to={segmentPath}
                  className="text-duck-forest hover:text-duck-teal transition-colors cursor-pointer font-medium"
                >
                  {segment}
                </Crumb>
              )}
            </span>
          );
        })}
      </nav>
    </div>
  );
};
