---
import { pageViewEventParams } from '../lib/meta';

const pixelId = import.meta.env.PUBLIC_META_PIXEL_ID ?? import.meta.env.META_PIXEL_ID;
const capiEndpoint = import.meta.env.PUBLIC_META_CAPI_ENDPOINT ?? '';
const pageParams = pageViewEventParams(Astro.url.pathname);
---

{pixelId && (
  <script is:inline define:vars={{ pixelId, capiEndpoint, pageParams }}>
    function juozasCookie(name) {
      return document.cookie
        .split('; ')
        .find((row) => row.startsWith(`${name}=`))
        ?.split('=')[1];
    }

    function juozasEventId(eventName) {
      return `${eventName.toLowerCase()}.${Date.now()}.${Math.random().toString(36).slice(2)}`;
    }

    function juozasSendCapi(eventName, eventID, customData) {
      if (!capiEndpoint) return;
      const payload = {
        event_name: eventName,
        event_time: Math.floor(Date.now() / 1000),
        event_id: eventID,
        action_source: 'website',
        event_source_url: window.location.href,
        user_data: {
          client_user_agent: navigator.userAgent,
          fbp: juozasCookie('_fbp'),
          fbc: juozasCookie('_fbc'),
        },
        custom_data: customData,
      };
      const body = JSON.stringify(payload);
      if (navigator.sendBeacon) {
        navigator.sendBeacon(capiEndpoint, new Blob([body], { type: 'application/json' }));
        return;
      }
      fetch(capiEndpoint, {
        method: 'POST',
        body,
        headers: { 'Content-Type': 'application/json' },
        keepalive: true,
      }).catch(() => {});
    }

    window.juozasTrackMeta = function juozasTrackMeta(eventName, customData, options) {
      const eventID = juozasEventId(eventName);
      if (window.fbq) window.fbq('track', eventName, customData, { eventID });
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push({ event: `meta_${eventName}`, eventID, ...customData });
      if (options && options.capiDelayMs) {
        window.setTimeout(() => juozasSendCapi(eventName, eventID, customData), options.capiDelayMs);
        return;
      }
      juozasSendCapi(eventName, eventID, customData);
    };

    !(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 = true;
      n.version = '2.0';
      n.queue = [];
      t = b.createElement(e);
      t.async = true;
      t.src = v;
      s = b.getElementsByTagName(e)[0];
      s.parentNode.insertBefore(t, s);
    })(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');
    fbq('init', pixelId);
    window.juozasTrackMeta('PageView', pageParams, { capiDelayMs: 500 });

    if (!window.__juozasMetaEventsBound) {
      window.__juozasMetaEventsBound = true;
      document.addEventListener('click', (event) => {
        const link = event.target.closest('[data-meta-event]');
        if (!link) return;
        const eventName = link.dataset.metaEvent || 'Contact';
        const params = JSON.parse(link.dataset.metaParams || '{}');
        window.juozasTrackMeta(eventName, params);
      });
    }
  </script>
  <noscript>
    <img height="1" width="1" style="display:none" src={`https://www.facebook.com/tr?id=${pixelId}&ev=PageView&noscript=1`} alt="" />
  </noscript>
)}
