/* Plazmacentrum — Meta Pixel + CAPI bridge (Phase 2)
 * - Loads the Meta pixel base and inits the EXISTING dataset (PlazmaCentrum-Fő).
 * - fbclid -> _fbc cookie (Meta format) when missing, to lift fbc coverage.
 * - Exposes window.plazmaMeta: { track, newEventId, fbp, fbc, pixelId }.
 * - Custom events only (trackCustom); names must match the dataset EXACTLY.
 * - Product decision: ALWAYS fires (Meta tracking is not gated by the cookie
 *   reject — opt-out posture, legal risk accepted by the owner).
 * The CAPI access token lives ONLY in the Supabase edge function (server-side).
 */
(function () {
  "use strict";
  var PIXEL_ID = "1112357976451125"; // public dataset/pixel id — safe in client

  try {
    function getCookie(k) {
      var m = document.cookie.match("(^|;)\\s*" + k + "\\s*=\\s*([^;]+)");
      return m ? decodeURIComponent(m[2]) : null;
    }
    function setCookie(k, v, days) {
      var d = new Date();
      d.setTime(d.getTime() + days * 864e5);
      document.cookie = k + "=" + v + ";expires=" + d.toUTCString() + ";path=/;SameSite=Lax";
    }
    function qp(n) {
      try { return new URLSearchParams(location.search).get(n); } catch (e) { return null; }
    }

    /* fbclid -> _fbc (Meta format: fb.1.<unix_ms>.<fbclid>), 90-day window */
    var fbclid = qp("fbclid");
    if (fbclid && !getCookie("_fbc")) {
      setCookie("_fbc", "fb.1." + Date.now() + "." + fbclid, 90);
    }

    /* Meta pixel base code (loads fbevents.js, sets up fbq + creates _fbp) */
    !(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);
    // No standard PageView — pages fire the custom 'PageView - {centrum}' event.

    function track(eventName, customData, eventId) {
      try {
        if (!window.fbq || !eventName) return;
        var opts = eventId ? { eventID: eventId } : undefined;
        window.fbq("trackCustom", eventName, customData || {}, opts);
      } catch (e) {}
    }
    function newEventId() {
      try { if (window.crypto && crypto.randomUUID) return crypto.randomUUID(); } catch (e) {}
      return "e-" + Date.now() + "-" + Math.random().toString(16).slice(2);
    }

    window.plazmaMeta = {
      pixelId: PIXEL_ID,
      track: track,
      newEventId: newEventId,
      fbp: function () { return getCookie("_fbp"); },
      fbc: function () { return getCookie("_fbc"); },
    };
  } catch (e) { /* never break the page */ }
})();
