// analytics.jsx — GA4 + Meta Pixel scaffolding with consent gating.
//
// Fill in the IDs below. Both are optional: if empty, that provider is
// skipped. When the user grants cookie consent (see CookieConsent below),
// this loads the tracking scripts. Before consent, `window.fenixTrack(...)`
// silently no-ops so components can call it unconditionally.
//
// After creating GA4 property:  https://analytics.google.com → Admin → Data Streams
// After creating Meta Pixel:    https://business.facebook.com → Events Manager

(function () {
  // ⚠️ Fill these when ready.
  const GA4_MEASUREMENT_ID = '';   // e.g. 'G-XXXXXXXXXX'
  const META_PIXEL_ID       = '';  // e.g. '123456789012345'

  const CONSENT_KEY = 'fenix.consent.v1';

  const readConsent = () => {
    try { return localStorage.getItem(CONSENT_KEY); } catch (e) { return null; }
  };
  const writeConsent = (v) => {
    try { localStorage.setItem(CONSENT_KEY, v); } catch (e) {}
  };

  let ga4Loaded = false;
  let metaLoaded = false;
  const queue = [];

  function loadGA4() {
    if (ga4Loaded || !GA4_MEASUREMENT_ID) return;
    ga4Loaded = true;
    const s = document.createElement('script');
    s.async = true;
    s.src = `https://www.googletagmanager.com/gtag/js?id=${GA4_MEASUREMENT_ID}`;
    document.head.appendChild(s);
    window.dataLayer = window.dataLayer || [];
    window.gtag = function () { window.dataLayer.push(arguments); };
    window.gtag('js', new Date());
    window.gtag('config', GA4_MEASUREMENT_ID, {
      anonymize_ip: true,
      cookie_flags: 'SameSite=Lax;Secure',
    });
  }

  function loadMetaPixel() {
    if (metaLoaded || !META_PIXEL_ID) return;
    metaLoaded = true;
    // Meta Pixel base code (standard)
    /* eslint-disable */
    !function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?
    n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;
    n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;
    t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}
    (window, document,'script','https://connect.facebook.net/en_US/fbevents.js');
    /* eslint-enable */
    window.fbq('init', META_PIXEL_ID);
    window.fbq('track', 'PageView');
  }

  function flushQueue() {
    while (queue.length) {
      const { event, params } = queue.shift();
      dispatch(event, params);
    }
  }

  function dispatch(event, params) {
    try {
      if (ga4Loaded && window.gtag) {
        window.gtag('event', event, params || {});
      }
      if (metaLoaded && window.fbq) {
        // Map common event names to Meta standard events where sensible
        const metaEvent = mapMetaEvent(event);
        if (metaEvent) window.fbq('track', metaEvent, params || {});
        else window.fbq('trackCustom', event, params || {});
      }
    } catch (e) { /* swallow */ }
  }

  function mapMetaEvent(event) {
    switch (event) {
      case 'lead_submit':   return 'Lead';
      case 'quote_submit':  return 'Lead';
      case 'contact_click': return 'Contact';
      case 'estimator_view': return 'ViewContent';
      case 'estimator_share': return 'Share';
      default: return null;
    }
  }

  function grantConsent() {
    writeConsent('granted');
    loadGA4();
    loadMetaPixel();
    flushQueue();
  }

  function denyConsent() {
    writeConsent('denied');
  }

  window.fenixAnalytics = {
    grantConsent,
    denyConsent,
    getConsent: readConsent,
    hasIds: () => !!(GA4_MEASUREMENT_ID || META_PIXEL_ID),
  };

  window.fenixTrack = function (event, params) {
    if (readConsent() !== 'granted') return;
    if (!ga4Loaded && !metaLoaded) queue.push({ event, params });
    else dispatch(event, params);
  };

  // Auto-load if user already consented in a previous session
  if (readConsent() === 'granted') {
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', () => { loadGA4(); loadMetaPixel(); flushQueue(); });
    } else {
      loadGA4();
      loadMetaPixel();
      flushQueue();
    }
  }
})();
