import { Thing, WithContext, Graph } from 'schema-dts';
import { getOrganizationSchema, getLocalBusinessSchema, SITE_URL } from '@/lib/schema';

interface JsonLdProps {
  id?: string;
  data?: WithContext<Thing> | WithContext<Thing>[];
  disableGlobal?: boolean;
}

export default function JsonLd({ id, data, disableGlobal = false }: JsonLdProps) {
  let finalSchema: any;

  if (disableGlobal && data) {
    // Escape hatch for overriding the global graph
    finalSchema = data;
  } else {
    // Construct the @graph array
    const graphItems: any[] = [];

    // Always include Organization, WebSite, and LocalBusiness for strong AI SEO presence
    graphItems.push(getOrganizationSchema());
    graphItems.push({
      '@context': 'https://schema.org',
      '@type': 'WebSite',
      name: 'E-TIB',
      url: SITE_URL,
      potentialAction: {
        '@type': 'SearchAction',
        target: {
          '@type': 'EntryPoint',
          urlTemplate: `${SITE_URL}/search?q={search_term_string}`,
        },
        'query-input': 'required name=search_term_string',
      },
    });
    graphItems.push(getLocalBusinessSchema());

    // Append dynamic data from props
    if (data) {
      if (Array.isArray(data)) {
        // Strip out their individual @context if we are pushing to a graph
        const cleanedData = data.map((d: any) => {
          const { '@context': _, ...rest } = d;
          return rest;
        });
        graphItems.push(...cleanedData);
      } else {
        const { '@context': _, ...rest } = data as any;
        graphItems.push(rest);
      }
    }

    finalSchema = {
      '@context': 'https://schema.org',
      '@graph': graphItems,
    };
  }

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