"use client";

import * as React from "react";

declare global {
  interface Window {
    fbq?: (...args: unknown[]) => void;
    _fbq?: unknown;
  }
}

/** Fire a standard Meta Pixel event when the pixel is configured; silent otherwise. */
export function track(event: "ViewContent" | "Contact" | "Lead" | "Search" | "InitiateCheckout", params?: Record<string, unknown>) {
  try {
    window.fbq?.("track", event, params ?? {});
  } catch {}
}

/**
 * Meta Pixel for ad campaigns. Loaded only on the public site and only when
 * an ID is set in Settings → Website & reviews, so nothing runs for staff.
 */
export function FacebookPixel({ id }: { id: string }) {
  React.useEffect(() => {
    if (!id || !/^\d{6,20}$/.test(id) || window.fbq) return;
    const n = function (...args: unknown[]) {
      const f = n as unknown as { callMethod?: (...a: unknown[]) => void; queue: unknown[] };
      if (f.callMethod) f.callMethod(...args);
      else f.queue.push(args);
    } as unknown as { (...args: unknown[]): void; push: unknown; loaded: boolean; version: string; queue: unknown[] };
    n.push = n;
    n.loaded = true;
    n.version = "2.0";
    n.queue = [];
    window.fbq = n;
    window._fbq = n;
    const s = document.createElement("script");
    s.async = true;
    s.src = "https://connect.facebook.net/en_US/fbevents.js";
    document.head.appendChild(s);
    window.fbq("init", id);
    window.fbq("track", "PageView");
  }, [id]);
  return null;
}
