import type { Thing } from "schema-dts";

export interface JsonLdRendererProps {
  data: Thing | Thing[];
}

/**
 * Serializes a schema-dts Thing (or array of Things) to a JSON-LD string.
 * Adds "@context": "https://schema.org" to each item.
 * Escapes </script> sequences to prevent XSS.
 */
export function serializeJsonLd(data: Thing | Thing[]): string {
  const addContext = (item: Thing): Record<string, unknown> =>
    Object.assign({ "@context": "https://schema.org" }, item as object);

  const withContext = Array.isArray(data)
    ? data.map(addContext)
    : addContext(data);

  return JSON.stringify(withContext).replace(/<\//g, "\\u003c/");
}

/**
 * Renders a <script type="application/ld+json"> block with the serialized
 * JSON-LD data. Safe for SSR — the content is escaped against script injection.
 */
export function JsonLdRenderer({ data }: JsonLdRendererProps): JSX.Element {
  return (
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={{ __html: serializeJsonLd(data) }}
    />
  );
}
