'use client';

import Link from 'next/link';
import { ChevronRight, Home } from 'lucide-react';

export interface BreadcrumbItem {
  label: string;
  href?: string;
}

interface BreadcrumbProps {
  items: BreadcrumbItem[];
  showHomeIcon?: boolean;
  className?: string;
  /** Set true when rendered on a dark background */
  darkMode?: boolean;
}

export default function Breadcrumb({
  items,
  showHomeIcon = true,
  className = '',
  darkMode = false,
}: BreadcrumbProps) {
  const separatorColor = darkMode ? 'text-white/25' : 'text-gray-400';
  const activeColor    = darkMode ? 'text-white/90' : 'text-gray-900';
  const inactiveColor  = darkMode ? 'text-white/45' : 'text-gray-500';
  const hoverColor     = darkMode ? 'hover:text-white/80' : 'hover:text-blue-600';
  const iconColor      = darkMode ? 'text-white/30' : 'text-gray-400';
  const iconHover      = darkMode ? 'group-hover:text-white/60' : 'group-hover:text-blue-500';
  const underline      = darkMode ? 'decoration-white/30' : 'decoration-blue-400';

  return (
    <nav
      aria-label="Breadcrumb"
      className={`flex items-center flex-wrap gap-1 ${className}`}
    >
      {items.map((item, index) => {
        const isLast  = index === items.length - 1;
        const isFirst = index === 0;

        return (
          <span key={index} className="flex items-center gap-1">
            {!isFirst && (
              <ChevronRight
                className={`w-3.5 h-3.5 shrink-0 ${separatorColor}`}
                aria-hidden="true"
              />
            )}

            {isLast || !item.href ? (
              <span
                aria-current={isLast ? 'page' : undefined}
                className={`text-sm font-medium leading-none ${
                  isLast ? activeColor : inactiveColor
                } truncate max-w-50 sm:max-w-xs`}
                title={item.label}
              >
                {isFirst && showHomeIcon && (
                  <Home
                    className={`w-3.5 h-3.5 inline-block mr-1 -mt-0.5 ${iconColor}`}
                    aria-hidden="true"
                  />
                )}
                {item.label}
              </span>
            ) : (
              <Link
                href={item.href}
                className={`text-sm font-medium leading-none flex items-center gap-1 transition-colors group ${inactiveColor} ${hoverColor}`}
              >
                {isFirst && showHomeIcon && (
                  <Home
                    className={`w-3.5 h-3.5 transition-colors ${iconColor} ${iconHover}`}
                    aria-hidden="true"
                  />
                )}
                <span className={`hover:underline underline-offset-2 ${underline}`}>
                  {item.label}
                </span>
              </Link>
            )}
          </span>
        );
      })}
    </nav>
  );
}