---
/**
 * Meta Pixel — browser-side event tracking for Facebook /
 * Instagram ad attribution and audience building.  Pairs with the
 * server-side Conversions API forwarder at
 * `api.kiln3d.com/api/marketing/meta/event`; both sides share an
 * `event_id` so Meta dedupes the pair on its end and we get full
 * coverage even when iOS-14.5+ ATT or ad-blockers strip the
 * browser-side fire.
 *
 * Marketing-site scope: PageView only by default.  Conversion
 * events (CompleteRegistration / Subscribe / Purchase) happen in
 * the workshop app at app.kiln3d.com against the same Pixel ID,
 * with their own browser+server pairing.  Marketing site exposes
 * `window.kilnTrackEvent(eventName, customData, userData)` for
 * any custom events surfaced from page-specific JS later (none
 * today).
 *
 * Two gates — both must be ON for any script to load:
 *   1. PUBLIC_META_PIXEL_ID is set (build-time)
 *   2. User has granted advertising consent (read-time)
 *
 * Dormant by default: PUBLIC_META_PIXEL_ID is unset on Vercel
 * until activation day.  The pixel ID gets baked into the static
 * JS at build time via Astro's `define:vars` — the env var
 * NAME (not the value) appears in the source; the value lives
 * in Vercel.
 *
 * @see ./CookieBanner.astro — the consent writer
 * @see ../../../PRIVACY.md §3.2 — public disclosure
 * @see kiln_pro/_rest/marketing.py — server-side CAPI forwarder
 */
const PIXEL_ID = import.meta.env.PUBLIC_META_PIXEL_ID;
const CAPI_ENDPOINT =
  import.meta.env.PUBLIC_META_CAPI_ENDPOINT ??
  "https://api.kiln3d.com/api/marketing/meta/event";
---

{PIXEL_ID && (
  <script is:inline define:vars={{ PIXEL_ID, CAPI_ENDPOINT }}>
    (() => {
      // Read consent at script-init time.  The CookieBanner
      // reloads after save, so this re-evaluates on the next
      // navigation.  Mirrors lib/consent.ts shape.
      const COOKIE = "kiln_consent";
      const raw = document.cookie
        .split("; ")
        .find((c) => c.startsWith(COOKIE + "="))
        ?.split("=")[1];
      let advertising = false;
      try {
        if (raw) {
          const parsed = JSON.parse(decodeURIComponent(raw));
          advertising = parsed?.advertising === true;
        }
      } catch {
        /* malformed cookie → default OFF */
      }
      if (!advertising) return;

      // Meta Pixel init — verbatim from Meta's published snippet.
      !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');

      window.fbq('init', PIXEL_ID);
      window.fbq('track', 'PageView');

      // Public helper: fire a Meta standard event with browser+
      // server dedup.  Generates an event_id, fires Pixel client-
      // side with that ID, then POSTs the same event to the CAPI
      // forwarder server-side with the same ID.  Meta dedupes the
      // pair, recovering ~30-40% of events that iOS ATT or ad-
      // blockers strip from the browser side.
      window.kilnTrackEvent = function (eventName, customData, userData) {
        customData = customData || {};
        userData = userData || {};

        // Re-read consent at fire time — withdrawn consent must
        // stop subsequent events even if the page hasn't reloaded.
        let allow = false;
        try {
          const r = document.cookie.split("; ").find((c) => c.startsWith(COOKIE + "="))?.split("=")[1];
          allow = r ? JSON.parse(decodeURIComponent(r))?.advertising === true : false;
        } catch {
          /* deny */
        }
        if (!allow) return;

        const eventId =
          (window.crypto && typeof window.crypto.randomUUID === "function")
            ? window.crypto.randomUUID()
            : (Date.now() + "-" + Math.random().toString(36).slice(2));

        if (typeof window.fbq === "function") {
          window.fbq("track", eventName, customData, { eventID: eventId });
        }

        // Server fire — fire-and-forget, never awaited so a slow
        // CAPI call cannot block the user-facing flow.
        try {
          fetch(CAPI_ENDPOINT, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              event_name: eventName,
              event_id: eventId,
              event_source_url: window.location.href,
              user_data: userData,
              custom_data: customData,
            }),
            keepalive: true,
          }).catch(() => {});
        } catch {
          /* swallow — server logs are the source of truth */
        }
      };
    })();
  </script>

  <noscript>
    <img
      height="1"
      width="1"
      style="display:none"
      src={`https://www.facebook.com/tr?id=${PIXEL_ID}&ev=PageView&noscript=1`}
      alt=""
    />
  </noscript>
)}
