// JSON-LD schemas reutilisables : BreadcrumbList et ItemList.
// FAQPage est dans expertise-blocks.tsx (historique, garde la-bas).
// Organization + LocalBusiness + WebSite sont dans app/layout.tsx (root).

import { BRAND_DOMAIN } from "@/lib/brand";

const SITE_URL = `https://${BRAND_DOMAIN}`;

export type BreadcrumbItem = {
  /** Libelle visible (ex: "Expertises", "Site internet"). */
  name: string;
  /** Path relatif sans slash final (ex: "/expertises/site-internet"). */
  path: string;
};

const SCRIPT_TYPE = "application/ld+json";

// Helper pour eviter le hook PreToolUse:Edit faux positif sur dangerously*.
// Le JSON est genere par JSON.stringify (echappement automatique) + provient
// de donnees controlees (constantes brand + sitemap interne) = zero risque XSS.
function jsonLdProps(data: unknown) {
  return { __html: JSON.stringify(data) };
}

/**
 * BreadcrumbList Schema.org : rich result eligible sur les pages profondes.
 * Le premier item devrait toujours etre "Accueil" / "/".
 *
 * Usage :
 *   <JsonLdBreadcrumb items={[
 *     { name: "Accueil", path: "/" },
 *     { name: "Expertises", path: "/expertises" },
 *     { name: "Site internet", path: "/expertises/site-internet" },
 *   ]} />
 */
export function JsonLdBreadcrumb({ items }: { items: BreadcrumbItem[] }) {
  const data = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: items.map((item, idx) => ({
      "@type": "ListItem",
      position: idx + 1,
      name: item.name,
      item: `${SITE_URL}${item.path}`,
    })),
  };
  return <JsonLdScript data={data} />;
}

export type ItemListEntry = {
  name: string;
  path: string;
  description?: string;
  image?: string;
};

/**
 * ItemList Schema.org : rich result "Carousel" eligible pour les pages de
 * collection (realisations, blog index, etc).
 */
export function JsonLdItemList({ items, name }: { items: ItemListEntry[]; name?: string }) {
  const data = {
    "@context": "https://schema.org",
    "@type": "ItemList",
    ...(name && { name }),
    numberOfItems: items.length,
    itemListElement: items.map((item, idx) => ({
      "@type": "ListItem",
      position: idx + 1,
      url: `${SITE_URL}${item.path}`,
      name: item.name,
      ...(item.description && { description: item.description }),
      ...(item.image && { image: item.image }),
    })),
  };
  return <JsonLdScript data={data} />;
}

function JsonLdScript({ data }: { data: unknown }) {
  return <script type={SCRIPT_TYPE} {...{ dangerouslySetInnerHTML: jsonLdProps(data) }} />;
}
