'use client';

import { useEffect, useRef } from 'react';
import { trackPurchase, CustomerTrackingPayload, isSitePixelEnabled } from '@/lib/tracking';

interface PurchaseTrackerProps {
  orderId: string;
  total: number;
  deliveryFee: number;
  status: string;
  customer?: CustomerTrackingPayload;
  items: Array<{
    id: number | string;
    name: string;
    price: number;
    quantity: number;
    brand?: string;
  }>;
}

export default function PurchaseTracker({
  orderId,
  total,
  deliveryFee,
  status,
  customer,
  items,
}: PurchaseTrackerProps) {
  const hasDispatchedRef = useRef(false);

  useEffect(() => {
    if (!orderId || status === 'cancelled' || status === 'failed') {
      return;
    }

    if (hasDispatchedRef.current) {
      return;
    }

    const storageKey = `rb_purchase_tracked_${orderId}`;
    if (typeof window !== 'undefined' && localStorage.getItem(storageKey)) {
      return;
    }

    let attempts = 0;
    const maxAttempts = 25; // 25 * 200ms = 5 seconds

    const interval = setInterval(() => {
      attempts++;
      // Wait for fbq only when the site itself sends Meta Pixel events
      const isFbqReady =
        !isSitePixelEnabled() ||
        (typeof window !== 'undefined' && typeof window.fbq === 'function');

      if (isFbqReady || attempts >= maxAttempts) {
        clearInterval(interval);

        if (hasDispatchedRef.current) {
          return;
        }
        hasDispatchedRef.current = true;

        trackPurchase({
          id: orderId,
          total,
          deliveryFee,
          customer,
          items,
        });

        try {
          localStorage.setItem(storageKey, '1');
        } catch (e) {}
      }
    }, 200);

    return () => {
      clearInterval(interval);
    };
  }, [orderId, total, deliveryFee, status, customer, items]);

  return null;
}
