﻿"use client";

import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import MetaPixel from "@/components/analytics/MetaPixel";

type PixelConfig = {
  enabled: boolean;
  pixelId: string | null;
  eventName: "PageView" | "ViewContent" | "Lead" | "CompleteRegistration";
  source: "url" | "content" | "global" | "off";
};

export default function SitePixel() {
  const pathname = usePathname();
  const [config, setConfig] = useState<PixelConfig | null>(null);

  useEffect(() => {
    let active = true;
    setConfig(null);

    fetch(`/api/analytics/pixel?path=${encodeURIComponent(pathname || "/")}`, {
      cache: "no-store",
    })
      .then((response) => {
        if (!response.ok) throw new Error("Pixel configuration unavailable");
        return response.json();
      })
      .then((data: PixelConfig) => {
        if (active) setConfig(data);
      })
      .catch(() => {
        if (active) {
          setConfig({
            enabled: false,
            pixelId: null,
            eventName: "PageView",
            source: "off",
          });
        }
      });

    return () => {
      active = false;
    };
  }, [pathname]);

  if (!config?.enabled || !config.pixelId) return null;

  return (
    <>
      <MetaPixel
        enabled={true}
        pixelId={config.pixelId}
        eventName="PageView"
      />
      {config.eventName !== "PageView" && (
        <MetaPixel
          enabled={true}
          pixelId={config.pixelId}
          eventName={config.eventName}
        />
      )}
    </>
  );
}
