'use client';

import Script from 'next/script';

const FBEVENTS_URL = 'https://connect.facebook.net/en_US/fbevents.js';

const PIXEL_SCRIPT = (pixelId: string) => `
  !function(f,b,e,v,n,t,s)
  {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
  n.callMethod.apply(n,arguments):n.queue.push(arguments)};
  if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
  n.queue=[];t=b.createElement(e);t.async=!0;
  t.src=v;s=b.getElementsByTagName(e)[0];
  s.parentNode.insertBefore(t,s)}(window, document,'script','${FBEVENTS_URL}');
  fbq('init', '${pixelId.replace(/'/g, "\\'")}');
  fbq('track', 'PageView');
`;

export type MetaPixelProps = {
  /** Meta Pixel ID. When null/undefined, nothing is rendered. */
  pixelId: string | null | undefined;
};

/**
 * Renders the Meta (Facebook) Pixel base code: loads fbevents.js, initializes
 * the pixel, and tracks PageView. Use in the root layout when ads config
 * provides a meta_pixel_id.
 */
export function MetaPixel({ pixelId }: MetaPixelProps) {
  const raw = typeof pixelId === 'string' ? pixelId.trim() : '';
  const id = raw && raw !== 'null' && /^\d+$/.test(raw) ? raw : '';
  if (!id) {
    return null;
  }

  return (
    <>
      <Script
        id="meta-pixel"
        strategy="afterInteractive"
        dangerouslySetInnerHTML={{ __html: PIXEL_SCRIPT(id) }}
      />
      <noscript>
        {/* eslint-disable-next-line @next/next/no-img-element -- 1x1 tracking pixel for no-JS fallback; next/image not applicable in noscript */}
        <img
          height={1}
          width={1}
          style={{ display: 'none' }}
          src={`https://www.facebook.com/tr?id=${id}&ev=PageView&noscript=1`}
          alt=""
        />
      </noscript>
    </>
  );
}
