/**
 * WebPageSchema.jsx
 *
 * Injects a JSON-LD WebPage schema for silo/service pages.
 *
 * Usage:
 *   <WebPageSchema
 *     pageSlug="test-preparation"
 *     pageData={pageData}
 *     breadcrumbs={[                 // optional
 *       { name: "Home", href: "/" },
 *       { name: "Test Preparation", href: "/test-preparation" },
 *     ]}
 *   />
 */

const BASE_URL = process.env.NEXT_PUBLIC_APP_URL || "https://example.com";
const SITE_NAME =
  process.env.NEXT_PUBLIC_APP_WEBSITE_NAME || "Study Abroad Consultants";

function toTitleCase(slug) {
  return slug
    .split("-")
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(" ");
}


export default function WebPageSchema({ pageSlug, pageData, breadcrumbs }) {
  if (!pageSlug || !pageData) return null;

  const pageUrl = `${BASE_URL}/${pageSlug}`;

  const breadcrumbItems =
    breadcrumbs && breadcrumbs.length > 0
      ? breadcrumbs
      : [
          { name: "Home", href: "/" },
          { name: toTitleCase(pageSlug), href: `/${pageSlug}` },
        ];

  const schema = {
    "@context": "https://schema.org",
    "@type": "WebPage",
    "@id": `${pageUrl}#webpage`,
    url: pageUrl,
    name: pageData?.meta_title || pageData?.simple_title || SITE_NAME,
    description: pageData?.meta_description || pageData?.short_description || "",
    inLanguage: "en-US",
    isPartOf: {
      "@type": "WebSite",
      "@id": `${BASE_URL}/#website`,
      url: BASE_URL,
      name: SITE_NAME,
    },
    dateModified: pageData?.updated_at || new Date().toISOString(),
    breadcrumb: {
      "@type": "BreadcrumbList",
      itemListElement: breadcrumbItems.map((item, index) => ({
        "@type": "ListItem",
        position: index + 1,
        name: item.name,
        item: `${BASE_URL}${item.href}`,
      })),
    },
  };

  return (
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={{ __html: JSON.stringify(schema, null, 2) }}
    />
  );
}