/* Plazmacentrum first-party analytics (Phase 1)
 * - anonymous_id: 180-day durable (localStorage + cookie)
 * - session_id: new on 30-min inactivity OR new attribution (= new touch)
 * - captures UTM + click IDs (fbclid/gclid/ttclid/msclkid) + ref_code, persisted
 * - auto-tracks: page_view, scroll depth, section_view, cta_click, rage_click, engaged time
 * - opt-OUT consent: tracking starts immediately; stops only if the user clicks Reject
 * - batched, sent via the analytics-track Edge Function (adblock/ITP-resistant first-party)
 *
 * Exposes: window.plazmaTrack(type, props), window.plazmaIdentify(email, name, phone)
 * Config (set before this script):  window.PLAZMA_ANALYTICS = { persona, lang }
 */
(function () {
  "use strict";
  try {
    var CFG = window.PLAZMA_ANALYTICS || {};
    var PERSONA = CFG.persona || "unknown";
    var LANG = CFG.lang || (document.documentElement.lang || "hu");
    var ENDPOINT = "https://hoounjzhomovgvzovtyz.supabase.co/functions/v1/analytics-track";
    var ANON_KEY =
      "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9." +
      "eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imhvb3Vuanpob21vdmd2em92dHl6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3Nzg1MTI1MTcsImV4cCI6MjA5NDA4ODUxN30." +
      "0tvJmG_WQVT79XG4kCilN_LTbJIQa-1ITK8-zY-HItY";
    var SESSION_TIMEOUT = 30 * 60 * 1000; // 30 min
    var COOKIE_DAYS = 180;

    /* ---------- storage helpers (never throw) ---------- */
    function ls(k, v) {
      try { if (v === undefined) return localStorage.getItem(k); localStorage.setItem(k, v); } catch (e) {}
      return null;
    }
    function setCookie(k, v, days) {
      try {
        var d = new Date(); d.setTime(d.getTime() + days * 864e5);
        document.cookie = k + "=" + encodeURIComponent(v) + ";expires=" + d.toUTCString() + ";path=/;SameSite=Lax";
      } catch (e) {}
    }
    function getCookie(k) {
      try {
        var m = document.cookie.match("(^|;)\\s*" + k + "\\s*=\\s*([^;]+)");
        return m ? decodeURIComponent(m.pop()) : null;
      } catch (e) { return null; }
    }
    function uuid() {
      try { if (crypto && crypto.randomUUID) return crypto.randomUUID(); } catch (e) {}
      return "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, function (c) {
        var r = (Math.random() * 16) | 0, v = c === "x" ? r : (r & 0x3) | 0x8; return v.toString(16);
      });
    }

    /* ---------- consent (opt-out) ---------- */
    function consent() { return ls("pc_consent"); } // 'accepted' | 'rejected' | null
    var REJECTED = consent() === "rejected";

    /* ---------- anonymous_id (180d) ---------- */
    var aid = ls("pc_aid") || getCookie("pc_aid");
    if (!aid) { aid = "a_" + uuid(); }
    ls("pc_aid", aid);
    setCookie("pc_aid", aid, COOKIE_DAYS);

    /* ---------- attribution ---------- */
    function qp(name) {
      try { return new URLSearchParams(location.search).get(name) || null; } catch (e) { return null; }
    }
    function captureAttribution() {
      var a = {
        utm_source: qp("utm_source"), utm_medium: qp("utm_medium"), utm_campaign: qp("utm_campaign"),
        utm_content: qp("utm_content"), utm_term: qp("utm_term"),
        fbclid: qp("fbclid"), gclid: qp("gclid"), ttclid: qp("ttclid"), msclkid: qp("msclkid"),
        ref_code: qp("ref") || qp("ref_code") || qp("aff"),
      };
      // signature of "did this navigation carry a real ad-click / campaign?"
      a._sig = [a.utm_source, a.utm_campaign, a.fbclid, a.gclid, a.ttclid, a.msclkid, a.ref_code]
        .filter(Boolean).join("|");
      return a;
    }
    var attr = captureAttribution();
    // persist first-touch once (180d)
    if (!ls("pc_first_touch") && attr._sig) {
      ls("pc_first_touch", JSON.stringify({ at: Date.now(), persona: PERSONA, attr: attr }));
    }

    /* ---------- session (30-min timeout OR new attribution = new touch) ---------- */
    var nowTs = Date.now();
    var sid = ls("pc_sid");
    var lastSeen = parseInt(ls("pc_sid_last") || "0", 10);
    var lastSig = ls("pc_sid_sig") || "";
    var expired = !sid || (nowTs - lastSeen > SESSION_TIMEOUT);
    var newTouch = attr._sig && attr._sig !== lastSig; // a different ad click within the window = new touch
    if (expired || newTouch) {
      sid = "s_" + uuid();
      ls("pc_sid", sid);
      ls("pc_sid_sig", attr._sig || lastSig || "");
    }
    ls("pc_sid_last", String(nowTs));

    /* ---------- bot heuristic ---------- */
    var ua = (navigator.userAgent || "");
    var isBot = /bot|crawl|spider|slurp|bingpreview|headless|phantom|puppeteer|lighthouse/i.test(ua) ||
      (navigator.webdriver === true);

    function deviceType() {
      return /Mobi|Android|iPhone|iPad/i.test(ua) ? "mobile" : "desktop";
    }

    var META = {
      persona: PERSONA, lang: LANG,
      landing_url: location.pathname + location.search,
      referrer: document.referrer || null,
      utm_source: attr.utm_source, utm_medium: attr.utm_medium, utm_campaign: attr.utm_campaign,
      utm_content: attr.utm_content, utm_term: attr.utm_term,
      fbclid: attr.fbclid, gclid: attr.gclid, ttclid: attr.ttclid, msclkid: attr.msclkid,
      ref_code: attr.ref_code,
      device: deviceType(), user_agent: ua.slice(0, 400), is_bot: isBot,
    };

    /* ---------- event queue + flush ---------- */
    var queue = [];
    var flushTimer = null;

    // apikey in the URL so sendBeacon (which can't set headers) still authenticates with the Supabase gateway
    var ENDPOINT_AUTHED = ENDPOINT + "?apikey=" + ANON_KEY;
    function send(payloadEvents) {
      if (REJECTED) return;
      var body = JSON.stringify({ anonymous_id: aid, session_id: sid, meta: META, events: payloadEvents });
      try {
        if (navigator.sendBeacon) {
          // text/plain is a CORS-"simple" type → no preflight → cross-origin beacon succeeds.
          // The Edge Function parses the body with req.json() regardless of content-type.
          var blob = new Blob([body], { type: "text/plain;charset=UTF-8" });
          if (navigator.sendBeacon(ENDPOINT_AUTHED, blob)) return;
        }
      } catch (e) {}
      // fallback (keepalive so it survives unload)
      try {
        fetch(ENDPOINT_AUTHED, {
          method: "POST", keepalive: true,
          headers: { "Content-Type": "application/json", apikey: ANON_KEY, authorization: "Bearer " + ANON_KEY },
          body: body,
        });
      } catch (e) {}
    }

    function flush() {
      if (flushTimer) { clearTimeout(flushTimer); flushTimer = null; }
      if (REJECTED || !queue.length) return;
      var batch = queue.splice(0, queue.length);
      send(batch);
    }
    function scheduleFlush() {
      if (REJECTED) return;
      if (!flushTimer) flushTimer = setTimeout(flush, 4000);
    }

    function track(type, props) {
      if (REJECTED || isBot) return;
      ls("pc_sid_last", String(Date.now()));
      queue.push({ type: type, props: props || {}, ts: new Date().toISOString() });
      // conversions flush immediately, the rest batch
      if (type === "booked" || type === "identify" || type === "submit") flush();
      else scheduleFlush();
    }

    window.plazmaTrack = track;
    window.plazmaIdentify = function (email, name, phone) {
      if (!email) return;
      track("identify", { email: email, name: name || null, phone: phone || null });
    };

    /* ---------- auto: page_view ---------- */
    track("page_view", {
      title: document.title, path: location.pathname,
      first_touch: !ls("pc_returning"),
    });
    ls("pc_returning", "1");

    /* ---------- auto: scroll depth ---------- */
    var depths = [25, 50, 75, 100], hit = {};
    function onScroll() {
      var h = document.documentElement;
      var pct = (h.scrollTop + window.innerHeight) / (h.scrollHeight || 1) * 100;
      for (var i = 0; i < depths.length; i++) {
        if (pct >= depths[i] && !hit[depths[i]]) { hit[depths[i]] = 1; track("scroll", { depth: depths[i] }); }
      }
    }
    window.addEventListener("scroll", throttle(onScroll, 400), { passive: true });

    /* ---------- auto: section_view ---------- */
    try {
      if ("IntersectionObserver" in window) {
        var seen = {};
        var io = new IntersectionObserver(function (entries) {
          entries.forEach(function (en) {
            if (en.isIntersecting && en.target.id && !seen[en.target.id]) {
              seen[en.target.id] = 1;
              track("section_view", { id: en.target.id });
            }
          });
        }, { threshold: 0.4 });
        setTimeout(function () {
          document.querySelectorAll("section[id]").forEach(function (s) { io.observe(s); });
        }, 800);
      }
    } catch (e) {}

    /* ---------- auto: cta_click + rage_click ---------- */
    var clickTimes = [];
    document.addEventListener("click", function (e) {
      var t = e.target;
      var el = t && t.closest ? t.closest("button, a") : null;
      if (el) {
        var label = (el.innerText || el.getAttribute("aria-label") || "").trim().slice(0, 60);
        var sec = el.closest ? el.closest("section[id]") : null;
        track("cta_click", { label: label, section: sec ? sec.id : null });
      }
      // rage: 3+ clicks within 800ms
      var now = Date.now();
      clickTimes.push(now);
      clickTimes = clickTimes.filter(function (x) { return now - x < 800; });
      if (clickTimes.length >= 3) { track("rage_click", { x: e.clientX, y: e.clientY }); clickTimes = []; }
    }, true);

    /* ---------- auto: engaged time + flush on hide ---------- */
    var start = Date.now(), engaged = 0, lastTick = Date.now(), active = true;
    ["mousemove", "keydown", "scroll", "touchstart", "click"].forEach(function (ev) {
      window.addEventListener(ev, function () { active = true; }, { passive: true });
    });
    setInterval(function () {
      if (active) { engaged += Date.now() - lastTick; active = false; }
      lastTick = Date.now();
    }, 5000);
    function bye() {
      track("page_leave", { engaged_ms: engaged, total_ms: Date.now() - start });
      flush();
    }
    window.addEventListener("visibilitychange", function () { if (document.visibilityState === "hidden") bye(); });
    window.addEventListener("pagehide", bye);

    function throttle(fn, ms) {
      var last = 0, timer = null;
      return function () {
        var now = Date.now();
        if (now - last >= ms) { last = now; fn(); }
        else { clearTimeout(timer); timer = setTimeout(function () { last = Date.now(); fn(); }, ms); }
      };
    }

    /* ---------- consent banner (opt-out) ---------- */
    function showBanner() {
      if (consent()) return; // already decided
      var hu = LANG !== "en";
      var wrap = document.createElement("div");
      wrap.setAttribute("role", "dialog");
      wrap.style.cssText =
        "position:fixed;left:12px;right:12px;bottom:12px;z-index:9999;max-width:560px;margin:0 auto;" +
        "background:#14161A;color:#fff;border-radius:14px;padding:14px 16px;" +
        "box-shadow:0 18px 50px -18px rgba(0,0,0,.6);font-family:Inter,system-ui,sans-serif;" +
        "display:flex;gap:12px;align-items:center;flex-wrap:wrap;font-size:13px;line-height:1.45";
      var txt = hu
        ? "Sütiket és anonim analitikát használunk az élmény javításához és a hirdetéseink méréséhez."
        : "We use cookies and anonymous analytics to improve your experience and measure our ads.";
      var accept = hu ? "Rendben" : "Got it";
      var reject = hu ? "Elutasítom" : "Reject";
      var more = hu ? "Adatkezelés" : "Privacy";
      var PRIVACY_URL = "https://plazmacentrum.hu/adatvedelmi-nyilatkozat";
      wrap.innerHTML =
        '<span style="flex:1;min-width:200px">' + txt + ' <a href="' + PRIVACY_URL + '" target="_blank" rel="noopener" style="color:#9ec5ff;text-decoration:underline">' + more + '</a></span>' +
        '<div style="display:flex;gap:8px;flex-shrink:0">' +
        '<button data-pc="reject" style="height:36px;padding:0 14px;border-radius:9px;border:1px solid rgba(255,255,255,.25);background:transparent;color:#fff;font-size:13px;cursor:pointer">' + reject + '</button>' +
        '<button data-pc="accept" style="height:36px;padding:0 16px;border-radius:9px;border:0;background:#fff;color:#14161A;font-weight:600;font-size:13px;cursor:pointer">' + accept + '</button>' +
        '</div>';
      function close() { try { wrap.remove(); } catch (e) {} }
      wrap.addEventListener("click", function (e) {
        var b = e.target.getAttribute && e.target.getAttribute("data-pc");
        if (b === "accept") { ls("pc_consent", "accepted"); track("consent", { value: "accepted" }); close(); }
        else if (b === "reject") {
          ls("pc_consent", "rejected"); REJECTED = true;
          // stop everything; drop queue
          queue = [];
          close();
        }
        // "more" link has a real href + target=_blank → let it open the privacy policy
      });
      document.body.appendChild(wrap);
    }
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", function () { setTimeout(showBanner, 1200); });
    } else { setTimeout(showBanner, 1200); }
  } catch (err) {
    /* analytics must never break the page */
    try { console.error("analytics init failed:", err); } catch (e) {}
    window.plazmaTrack = window.plazmaTrack || function () {};
    window.plazmaIdentify = window.plazmaIdentify || function () {};
  }
})();
