'use client';

/**
 * BreadcrumbBar — Derives breadcrumb segments from the current pathname.
 *
 * Features:
 * - Always starts with "Dashboards" as the root segment
 * - Maps path segments to labels using navItems from navigation.ts
 * - Falls back to capitalized path segment for unknown paths
 * - Exports a pure `buildBreadcrumbs` function for independent testing
 *
 * Requirements: 2.1, 2.2
 */

import { usePathname } from 'next/navigation';
import Link from 'next/link';
import { navItems, type NavItem } from '@/lib/constants/navigation';

export interface BreadcrumbSegment {
  label: string;
  href: string;
}

export interface BreadcrumbBarProps {
  className?: string;
}

/**
 * Pure function to build breadcrumb segments from a pathname and nav items.
 * Can be tested independently without React rendering.
 */
export function buildBreadcrumbs(pathname: string, items: NavItem[]): BreadcrumbSegment[] {
  const segments: BreadcrumbSegment[] = [
    { label: 'Dashboards', href: '/overview' },
  ];

  // Remove leading slash and split into parts
  const parts = pathname.replace(/^\//, '').split('/').filter(Boolean);

  if (parts.length === 0) {
    return segments;
  }

  // Build the breadcrumb for each path part
  let currentPath = '';
  for (const part of parts) {
    currentPath += `/${part}`;

    // Try to find a matching nav item for this path
    const matchingItem = items.find((item) => item.href === currentPath);

    const label = matchingItem
      ? matchingItem.label
      : part.charAt(0).toUpperCase() + part.slice(1);

    segments.push({ label, href: currentPath });
  }

  return segments;
}

export default function BreadcrumbBar({ className }: BreadcrumbBarProps) {
  const pathname = usePathname();
  const breadcrumbs = buildBreadcrumbs(pathname, [...navItems]);

  return (
    <nav aria-label="Breadcrumb" className={className}>
      <ol className="flex items-center gap-1.5 text-sm">
        {breadcrumbs.map((segment, index) => {
          const isLast = index === breadcrumbs.length - 1;

          return (
            <li key={`${index}-${segment.href}`} className="flex items-center gap-1.5">
              {index > 0 && (
                <svg
                  className="h-3.5 w-3.5 text-divisi-text-secondary/50"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <polyline points="9 18 15 12 9 6" />
                </svg>
              )}
              {isLast ? (
                <span className="text-divisi-text-primary font-medium">
                  {segment.label}
                </span>
              ) : (
                <Link
                  href={segment.href}
                  className="text-divisi-text-secondary hover:text-divisi-text-primary transition-colors duration-150"
                >
                  {segment.label}
                </Link>
              )}
            </li>
          );
        })}
      </ol>
    </nav>
  );
}
