import * as React from 'react'
import { ChevronRight } from 'lucide-react'
import { cn } from '../lib/cn'

export interface BreadcrumbItem {
  label: string
  href?: string
}

export interface BreadcrumbProps extends React.HTMLAttributes<HTMLElement> {
  items: BreadcrumbItem[]
  /** Accessible name for the nav landmark. */
  label?: string
}

/**
 * Semantic breadcrumb: <nav aria-label> + ordered list. The separator icon uses
 * `rtl:rotate-180` so the chevron points the right way under dir="rtl".
 */
export const Breadcrumb = React.forwardRef<HTMLElement, BreadcrumbProps>(
  ({ items, label = 'Breadcrumb', className, ...props }, ref) => (
    <nav ref={ref} aria-label={label} className={className} {...props}>
      <ol className="flex flex-wrap items-center gap-2">
        {items.map((item, i) => {
          const isLast = i === items.length - 1
          return (
            <li key={`${item.label}-${i}`} className="flex items-center gap-2">
              {item.href && !isLast ? (
                <a
                  href={item.href}
                  className="text-body-2 text-ink-soft underline-offset-2 hover:underline"
                >
                  {item.label}
                </a>
              ) : (
                <span
                  className={cn('text-body-2', isLast ? 'text-ink' : 'text-ink-soft')}
                  aria-current={isLast ? 'page' : undefined}
                >
                  {item.label}
                </span>
              )}
              {!isLast ? (
                <ChevronRight
                  className="h-4 w-4 text-ink-faint rtl:rotate-180"
                  aria-hidden="true"
                />
              ) : null}
            </li>
          )
        })}
      </ol>
    </nav>
  ),
)
Breadcrumb.displayName = 'Breadcrumb'
