import { ChevronRight } from 'lucide-react';
import { SITE_URL } from '@/lib/seo';
import { safeJsonLd } from '@/lib/sanitizeHtml';

interface BreadcrumbProps {
  items: Array<{ label: string; href?: string }>;
}

const Breadcrumb = ({ items }: BreadcrumbProps) => {
  const absoluteUrl = (href?: string): string | undefined => {
    if (!href) return undefined;
    if (/^https?:\/\//.test(href)) return href;
    return `${SITE_URL}${href.startsWith('/') ? href : `/${href}`}`;
  };

  // Mobile truncation: if more than 3 items, show "Accueil > … > Last two items"
  const mobileItems =
    items.length > 3
      ? [items[0], { label: '…' }, ...items.slice(-2)]
      : items;

  // Schema.org BreadcrumbList structured data
  const schemaData = {
    '@context': 'https://schema.org',
    '@type': 'BreadcrumbList',
    itemListElement: items.map((item, index) => ({
      '@type': 'ListItem',
      position: index + 1,
      name: item.label,
      ...(absoluteUrl(item.href) ? { item: absoluteUrl(item.href) } : {}),
    })),
  };

  const renderItems = (list: typeof items) =>
    list.map((item, index) => {
      const isLast = index === list.length - 1;

      return (
        <li key={index} className="flex items-center gap-1.5 min-w-0">
          {index > 0 && (
            <ChevronRight className="w-3.5 h-3.5 text-foreground/30 flex-shrink-0" />
          )}
          {isLast || !item.href ? (
            <span
              className={`truncate ${
                isLast
                  ? 'font-medium text-foreground/70'
                  : 'text-foreground/40'
              }`}
            >
              {item.label}
            </span>
          ) : (
            <a
              href={item.href}
              className="truncate text-foreground/40 hover:text-foreground/70 transition-colors"
            >
              {item.label}
            </a>
          )}
        </li>
      );
    });

  return (
    <nav
      aria-label="Fil d'Ariane"
      className="bg-[#faf9f5] border-b border-foreground/[0.06]"
    >
      <div className="container mx-auto px-4 lg:px-8">
        {/* Desktop */}
        <ol className="hidden sm:flex items-center gap-1.5 text-xs font-body h-10">
          {renderItems(items)}
        </ol>

        {/* Mobile (truncated) */}
        <ol className="flex sm:hidden items-center gap-1.5 text-xs font-body h-9">
          {renderItems(mobileItems)}
        </ol>
      </div>

      {/* Schema.org structured data */}
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: safeJsonLd(schemaData) }}
      />
    </nav>
  );
};

export default Breadcrumb;
