import Link from 'next/link';
import { abs } from '@/lib/site';
import { JsonLd } from './JsonLd';
import { ChevronRightIcon, HomeIcon } from './Icons';

export function Breadcrumbs({ items }: { items: { label: string; href?: string }[] }) {
  return (
    <>
      <nav aria-label="Breadcrumb" className="text-sm text-muted">
        <ol className="flex flex-wrap items-center gap-x-1.5 gap-y-1">
          {items.map((it, i) => {
            const last = i === items.length - 1;
            return (
              <li key={i} className="flex min-w-0 items-center gap-1.5">
                {i > 0 && <ChevronRightIcon className="h-3.5 w-3.5 text-rule-strong" />}
                {it.href && !last ? (
                  <Link href={it.href} className="inline-flex items-center gap-1.5 rounded px-1 py-0.5 hover:bg-sunken hover:text-ink">
                    {i === 0 && it.href === '/' && <HomeIcon className="h-3.5 w-3.5" />}
                    {it.label}
                  </Link>
                ) : (
                  <span aria-current={last ? 'page' : undefined} className={`truncate px-1 ${last ? 'max-w-[16rem] font-medium text-ink-2 sm:max-w-none' : ''}`}>
                    {it.label}
                  </span>
                )}
              </li>
            );
          })}
        </ol>
      </nav>
      <JsonLd
        data={{
          '@context': 'https://schema.org',
          '@type': 'BreadcrumbList',
          itemListElement: items
            .filter((i) => i.href)
            .map((it, i) => ({ '@type': 'ListItem', position: i + 1, name: it.label, item: abs(it.href!) })),
        }}
      />
    </>
  );
}
