import JsonLd from './JsonLd'

const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL || 'https://example.com'

interface BreadcrumbItem {
  name: string
  /** Relative or absolute URL */
  url: string
}

interface Props {
  items: BreadcrumbItem[]
}

/**
 * Renders Schema.org BreadcrumbList structured data.
 * Usage:
 *   <BreadcrumbJsonLd items={[
 *     { name: 'Home', url: '/' },
 *     { name: 'Blog', url: '/blog' },
 *     { name: 'My Post', url: '/blog/my-post' },
 *   ]} />
 */
export default function BreadcrumbJsonLd({ items }: Props) {
  const data = {
    '@context': 'https://schema.org',
    '@type': 'BreadcrumbList',
    itemListElement: items.map((item, index) => ({
      '@type': 'ListItem',
      position: index + 1,
      name: item.name,
      item: item.url.startsWith('http')
        ? item.url
        : `${SITE_URL}${item.url}`,
    })),
  }

  return <JsonLd id="breadcrumb-jsonld" data={data} />
}
