﻿"use client";

import { useEffect } from "react";

type MetaPixelFunction = {
  (...args: unknown[]): void;
  callMethod?: (...args: unknown[]) => void;
  queue: unknown[];
  loaded: boolean;
  version: string;
};

declare global {
  interface Window {
    fbq?: MetaPixelFunction;
    _fbq?: MetaPixelFunction;
  }
}

type MetaPixelProps = {
  pixelId?: string | null;
  enabled?: boolean;
  eventName?: "PageView" | "ViewContent" | "Lead" | "CompleteRegistration";
};

export default function MetaPixel({
  pixelId,
  enabled = false,
  eventName = "PageView",
}: MetaPixelProps) {
  useEffect(() => {
    if (!enabled || !pixelId) return;

    const id = pixelId.trim();

    if (!/^\d{5,30}$/.test(id)) return;

    if (!window.fbq) {
      const fbq: MetaPixelFunction = (...args: unknown[]) => {
        if (fbq.callMethod) {
          fbq.callMethod(...args);
        } else {
          fbq.queue.push(args);
        }
      };

      fbq.queue = [];
      fbq.loaded = true;
      fbq.version = "2.0";

      window.fbq = fbq;
      window._fbq = fbq;

      const script = document.createElement("script");
      script.async = true;
      script.src =
        "https://connect.facebook.net/en_US/fbevents.js";

      document.head.appendChild(script);
    }

    window.fbq("init", id);
    window.fbq("track", eventName);
  }, [pixelId, enabled, eventName]);

  return null;
}
