import type { Service } from "@/data/services-catalog";

const BASE_URL = "https://www.elevaseo.com";

export function ServiceSchema({
  service,
  locale,
  path,
  dateModified,
  author,
}: {
  service: Service;
  locale: string;
  path: string;
  dateModified?: string;
  author?: {
    name: string;
    url?: string;
    image?: string;
    jobTitle?: string;
    sameAs?: string[];
  };
}) {
  const prefix = locale === "fr" ? "" : `/${locale}`;

  const formatSchemaPrice = (
    price: number | string
  ): { price: string; priceSpecification?: Record<string, unknown> } => {
    if (typeof price === "number") {
      return { price: price.toString() };
    }
    const [min, max] = price.split("-").map(Number);
    return {
      price: min.toString(),
      priceSpecification: {
        "@type": "UnitPriceSpecification",
        minPrice: min,
        maxPrice: max,
        priceCurrency: service.currency,
      },
    };
  };

  const priceData = formatSchemaPrice(service.price);

  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "Service",
    name: service.title,
    description: service.description,
    url: `${BASE_URL}${prefix}${path}`,
    ...(dateModified && { dateModified }),
    provider: {
      "@type": "Organization",
      name: "ElevaSEO",
      url: BASE_URL,
    },
    ...(author && {
      author: {
        "@type": "Person",
        name: author.name,
        ...(author.jobTitle && { jobTitle: author.jobTitle }),
        ...(author.url && { url: author.url }),
        ...(author.image && { image: author.image }),
        ...(author.sameAs && { sameAs: author.sameAs }),
      },
    }),
    offers: {
      "@type": "Offer",
      price: priceData.price,
      priceCurrency: service.currency,
      availability: "https://schema.org/InStock",
      ...(priceData.priceSpecification && {
        priceSpecification: priceData.priceSpecification,
      }),
    },
  };

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