'use client';

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

declare global {
  interface Window {
    fbq?: {
      callMethod?: boolean;
      (...args: unknown[]): void;
    };
  }
}

const POLL_INTERVAL = 50;

export default function MetaPageView() {
  const pathname = usePathname();

  useEffect(() => {
    if (typeof window === 'undefined') return;

    let intervalId: number | null = null;

    const sendPageView = () => {
      if (window.fbq?.callMethod) {
        window.fbq('track', 'PageView');
        return true;
      }
      return false;
    };

    if (!sendPageView()) {
      intervalId = window.setInterval(() => {
        if (sendPageView()) {
          if (intervalId) window.clearInterval(intervalId);
        }
      }, POLL_INTERVAL);
    }

    return () => {
      if (intervalId) window.clearInterval(intervalId);
    };
  }, [pathname]);

  return null;
}
