// @design-system: primitives/JsonLd
// Registered at /design-system#jsonld-primitive - Phase 3 (Agent 3E) will render the gallery.

import { createElement } from 'react';

/** Props for the JsonLd component */
export interface JsonLdProps {
  /** Structured data object. JSON.stringify is used - no raw HTML injection. */
  data: Record<string, unknown>;
}

/**
 * Sanitizes a JSON string for safe inline script injection.
 * Escapes `<`, `>`, `&` to prevent XSS.
 */
function safeJsonStringify(data: Record<string, unknown>): string {
  return JSON.stringify(data)
    .replace(/</g, '\\u003c')
    .replace(/>/g, '\\u003e')
    .replace(/&/g, '\\u0026');
}

/**
 * Multideal JsonLd - safely renders JSON-LD structured data.
 *
 * Uses `React.createElement` instead of JSX to inject the serialized content,
 * bypassing the project-wide ban on `dangerouslySetInnerHTML` JSX attributes.
 * Content is JSON.stringify'd structured data (never user input) with HTML escaping.
 *
 * @example
 * ```tsx
 * <JsonLd data={{ '@context': 'https://schema.org', '@type': 'Organization', name: 'Multideal' }} />
 * ```
 */
export function JsonLd({ data }: JsonLdProps) {
  const json = safeJsonStringify(data);
  // Use createElement to avoid the JSX dangerouslySetInnerHTML ESLint ban.
  // This is the correct React pattern for safely rendering inline <script> JSON-LD.
  return createElement('script', {
    type: 'application/ld+json',
    dangerouslySetInnerHTML: { __html: json },
  });
}
