﻿"use client";

import { useEffect } from "react";
import { usePathname } from "next/navigation";

type PixelEvent =
  | "PageView"
  | "ViewContent"
  | "Lead"
  | "CompleteRegistration";

type MetaPixelProps = {
  pixelId?: string | null;
  enabled?: boolean;
  eventName?: PixelEvent;
};

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

const initializedPixelIds = new Set<string>();
const trackedPageEvents = new Set<string>();

function ensureMetaPixel() {
  if (typeof window === "undefined") return;

  if (!window.fbq) {
    const fbq: any = function (...args: any[]) {
      if (fbq.callMethod) {
        fbq.callMethod.apply(fbq, args);
      } else {
        fbq.queue.push(args);
      }
    };

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

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

  const scriptExists = document.querySelector(
    'script[src*="connect.facebook.net/en_US/fbevents.js"]'
  );

  if (!scriptExists) {
    const script = document.createElement("script");
    script.async = true;
    script.src = "https://connect.facebook.net/en_US/fbevents.js";
    document.head.appendChild(script);
  }
}

export default function MetaPixel({
  pixelId,
  enabled = false,
  eventName = "PageView",
}: MetaPixelProps) {
  const pathname = usePathname();

  useEffect(() => {
    if (!enabled || !pixelId || !/^\d{5,30}$/.test(pixelId)) return;

    ensureMetaPixel();

    const fbq = window.fbq;
    if (!fbq) return;

    if (!initializedPixelIds.has(pixelId)) {
      fbq("init", pixelId);
      initializedPixelIds.add(pixelId);
    }

    const isPageEvent =
      eventName === "PageView" || eventName === "ViewContent";

    const eventKey = `${pixelId}:${eventName}:${pathname}`;

    if (isPageEvent && trackedPageEvents.has(eventKey)) return;

    if (isPageEvent) trackedPageEvents.add(eventKey);

    fbq("track", eventName);
  }, [enabled, pixelId, eventName, pathname]);

  return null;
}
