import React, { useEffect, useRef, useState } from 'react';
import { useLocation } from 'react-router-dom';
import privacyService, {
  PublicPrivacyConfig,
} from '../../services/api/privacyService';
import { useCookieConsent } from '../../contexts/CookieConsentContext';

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

const AnalyticsLoader: React.FC = () => {
  const location = useLocation();
  const { consent } = useCookieConsent();
  const [config, setConfig] = useState<PublicPrivacyConfig | null>(null);
  const gaLoadedRef = useRef(false);
  const fbLoadedRef = useRef(false);

  
  useEffect(() => {
    let mounted = true;
    const loadConfig = async () => {
      try {
        const cfg = await privacyService.getPublicConfig();
        if (!mounted) return;
        setConfig(cfg);
      } catch {
        
      }
    };
    void loadConfig();
    return () => {
      mounted = false;
    };
  }, []);

  
  useEffect(() => {
    if (!config || !consent) return;
    const measurementId = config.integrations.ga_measurement_id;
    const analyticsAllowed =
      config.policy.analytics_enabled && consent.categories.analytics;
    if (!measurementId || !analyticsAllowed || gaLoadedRef.current) return;

    
    const script = document.createElement('script');
    script.async = true;
    script.src = `https://www.googletagmanager.com/gtag/js?id=${measurementId}`;
    document.head.appendChild(script);

    window.dataLayer = window.dataLayer || [];
    function gtag(...args: any[]) {
      window.dataLayer.push(args);
    }
    window.gtag = gtag;
    gtag('js', new Date());
    gtag('config', measurementId, { anonymize_ip: true });

    gaLoadedRef.current = true;

    return () => {
      
    };
  }, [config, consent]);

  
  useEffect(() => {
    if (!gaLoadedRef.current || !config?.integrations.ga_measurement_id) return;
    if (typeof window.gtag !== 'function') return;
    window.gtag('config', config.integrations.ga_measurement_id, {
      page_path: location.pathname + location.search,
    });
  }, [location, config]);

  
  useEffect(() => {
    if (!config || !consent) return;
    const pixelId = config.integrations.fb_pixel_id;
    const marketingAllowed =
      config.policy.marketing_enabled && consent.categories.marketing;
    if (!pixelId || !marketingAllowed || fbLoadedRef.current) return;

    
    (function (f: any, b: Document, e: string) {
      if (f.fbq) return;
      const n: any = f.fbq = function () {
        (n.callMethod ? n.callMethod : n.queue.push).apply(n, arguments);
      };
      if (!f._fbq) f._fbq = n;
      n.push = n;
      n.loaded = true;
      n.version = '2.0';
      n.queue = [];
      const t = b.createElement(e) as HTMLScriptElement;
      t.async = true;
      t.src = 'https://connect.facebook.net/en_US/fbevents.js';
      const s = b.getElementsByTagName(e)[0];
      if (s && s.parentNode) {
        s.parentNode.insertBefore(t, s);
      }
    })(window, document, 'script');

    window.fbq('init', pixelId);
    window.fbq('track', 'PageView');
    fbLoadedRef.current = true;
  }, [config, consent]);

  return null;
};

export default AnalyticsLoader;

