// components/DealerScripts.tsx
'use client';

import Script from 'next/script';
import { useMemo } from 'react';
import { parseDealerScripts } from '@/lib/parse-dealer-scripts';

interface DealerScriptsProps {
  headScripts?: string | null;
  bodyScripts?: string | null;
}

/**
 * Client component that renders dealer scripts using next/script.
 *
 * Uses `afterInteractive` strategy which loads scripts after Next.js
 * hydration completes. This is the recommended approach for analytics
 * and tracking scripts (GTM, GA4, Facebook Pixel, etc.).
 *
 * Scripts are parsed from HTML strings stored in the dealer database
 * and rendered as individual next/script components for proper
 * lifecycle management and optimization.
 *
 * Note: <noscript> fallbacks are NOT supported because this component
 * runs client-side where JavaScript is always enabled. For no-JS support,
 * scripts would need to be rendered server-side in the layout.
 */
export function DealerScripts({ headScripts, bodyScripts }: DealerScriptsProps) {
  // Parse all scripts from HTML strings
  const allScripts = useMemo(() => {
    const head = parseDealerScripts(headScripts);
    const body = parseDealerScripts(bodyScripts);
    return [...head, ...body];
  }, [headScripts, bodyScripts]);

  // Don't render anything if no scripts
  if (allScripts.length === 0) {
    return null;
  }

  return (
    <>
      {allScripts.map((script) => (
        <Script
          key={script.id}
          id={script.id}
          strategy="afterInteractive"
          src={script.src}
          async={script.async}
          defer={script.defer}
          {...(script.content && !script.src
            ? { dangerouslySetInnerHTML: { __html: script.content } }
            : {})}
          {...(script.dataAttributes || {})}
          onError={(e) => {
            console.error(`[DealerScripts] Failed to load script:`, script.src || script.id, e);
          }}
        />
      ))}
    </>
  );
}
