import { getProductDetailPath } from "@/lib/product-detail/constants";

type BreadcrumbListItem = {
  "@type": "ListItem";
  position: number;
  name: string;
  item?: string;
};

type ProductDetailStructuredDataProps = {
  category: string;
  subCategory: string;
  slug: string;
  productName: string;
  subCategoryName: string;
};

/**
 * Renders BreadcrumbList JSON-LD for the PDP (Home → Shop → Category → Subcategory → Product).
 * Server-rendered only; validate at https://search.google.com/test/rich-results
 */
export function ProductDetailStructuredData({
  category,
  subCategory,
  slug,
  productName,
  subCategoryName,
}: ProductDetailStructuredDataProps) {
  const baseUrl =
    process.env.NEXT_PUBLIC_APP_URL ??
    process.env.NEXT_PUBLIC_STOREFRONT_URL ??
    "";
  const base = baseUrl ? baseUrl.replace(/\/$/, "") : "";

  const items: BreadcrumbListItem[] = [
    { "@type": "ListItem", position: 1, name: "Home", item: base ? `${base}/` : undefined },
    { "@type": "ListItem", position: 2, name: "Shop", item: base ? `${base}/shop` : undefined },
    {
      "@type": "ListItem",
      position: 3,
      name: formatCategoryLabel(category),
      item: base ? `${base}/shop/${category}` : undefined,
    },
    {
      "@type": "ListItem",
      position: 4,
      name: subCategoryName,
      item: base ? `${base}/shop/${category}/${subCategory}` : undefined,
    },
    {
      "@type": "ListItem",
      position: 5,
      name: productName,
      item: base ? `${base}${getProductDetailPath(category, subCategory, slug)}` : undefined,
    },
  ];

  const breadcrumbList = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: items,
  };

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

function formatCategoryLabel(slug: string): string {
  if (slug === "other-pets") return "Other Pets";
  return slug.charAt(0).toUpperCase() + slug.slice(1);
}
