/* live-stats.js — REAL live social-proof data for the landing tickers.
 *
 * Pulls aggregated, PRIVACY-SAFE stats from the Supabase RPC `landing_live_stats`
 * (anonymized first-name monogram + centre, plus today's aggregate counters).
 *
 * Load strategy (kíméljük a terhelést):
 *  - 1 RPC call per visitor per TTL window (default 5 min), only while the tab is visible.
 *  - The fetched batch (~12-14 events) is cached in localStorage and cycled/repeated
 *    client-side, so the ticker feels live without hammering the DB.
 *  - Jitter: each event gets a randomized "perce" offset + the batch is shuffled, so the
 *    displayed order/timing does not map 1:1 to real DB rows.
 *
 * Exposes:
 *  - window.plazmaLive.messages()  -> Array<string>  (ready-to-display, localized)
 *  - window.plazmaLive.totals()    -> { today_bookings, today_donations, last_hour_bookings, per_center }
 *  - window.useLiveMessages(fallbackArray)  React hook -> string[]  (fallback until data lands)
 *  - window.useLiveTotals()                 React hook -> totals | null
 */
(function () {
  var SUPABASE_URL = "https://hoounjzhomovgvzovtyz.supabase.co";
  var ANON_KEY =
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9." +
    "eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imhvb3Vuanpob21vdmd2em92dHl6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3Nzg1MTI1MTcsImV4cCI6MjA5NDA4ODUxN30." +
    "0tvJmG_WQVT79XG4kCilN_LTbJIQa-1ITK8-zY-HItY";
  var RPC = SUPABASE_URL + "/rest/v1/rpc/landing_live_stats";
  var TTL = 5 * 60 * 1000;        // refetch window
  var CACHE_KEY = "pc_live_v1";

  var state = { data: null, messages: [], totals: null };

  function isEN() {
    try { return (document.documentElement.lang || "hu").slice(0, 2).toLowerCase() === "en"; }
    catch (e) { return false; }
  }
  function centerLabel(s) {
    return s === "nyugati" ? "Nyugati" : s === "blaha" ? "Blaha" : s === "baja" ? "Baja" : (s || "");
  }
  function randInt(a, b) { return a + Math.floor(Math.random() * (b - a + 1)); }

  // site: optional centre filter ("baja" for the single-centre landing); falsy = all centres
  function buildMessages(raw, site) {
    var hu = !isEN();
    var ev = (raw && raw.events ? raw.events : []).slice();
    if (site) ev = ev.filter(function (e) { return e.site === site; });

    // jitter: randomized display minutes + shuffle (de-link from exact DB rows)
    ev.forEach(function (e) { e._m = Math.max(1, (e.mins_ago || 0) + randInt(1, 16)); });
    for (var i = ev.length - 1; i > 0; i--) {
      var j = Math.floor(Math.random() * (i + 1));
      var t = ev[i]; ev[i] = ev[j]; ev[j] = t;
    }

    // több megfogalmazási variáns, hogy ne legyen monoton (index szerint váltogatva)
    var BOOK_HU = [
      ". épp most foglalta be az időpontját · ",
      ". épp most foglalt időpontot · ",
      ". lefoglalta a következő plazmaadását · ",
    ];
    var DONATE_HU = [
      ". épp most végzett a vérplazma-adással · ",
      ". épp most adott vérplazmát · ",
      ". sikeresen befejezte a plazmaadást · ",
    ];
    var BOOK_EN = [
      ". just booked an appointment · ",
      ". just reserved a plasma slot · ",
    ];
    var DONATE_EN = [
      ". just finished donating plasma · ",
      ". just completed a plasma donation · ",
    ];
    var msgs = ev.map(function (e, i) {
      var c = centerLabel(e.site);
      var mono = (e.mono || "").toUpperCase();
      var arr = e.kind === "donate" ? (hu ? DONATE_HU : DONATE_EN) : (hu ? BOOK_HU : BOOK_EN);
      return mono + arr[i % arr.length] + c;
    });

    var t = (raw && raw.totals) ? raw.totals : {};
    var pc = t.per_center || {};
    var bookCount = site ? (pc[site] || 0) : (t.today_bookings || 0);
    var scope = site ? centerLabel(site) : "mindhárom centrum";
    var pulses = hu ? [
      "Ma már " + bookCount + " időpontfoglalás · " + scope,
      "Ma " + (t.today_donations || 0) + " sikeres vérplazma-adás",
      "Az elmúlt órában " + (t.last_hour_bookings || 0) + " új foglalás",
    ] : [
      bookCount + " appointments booked today · " + (site ? centerLabel(site) : "all 3 centres"),
      (t.today_donations || 0) + " successful plasma donations today",
      (t.last_hour_bookings || 0) + " new bookings in the last hour",
    ];

    // weave one aggregate pulse after every 3 events
    var out = [], pi = 0;
    for (var k = 0; k < msgs.length; k++) {
      out.push(msgs[k]);
      if ((k + 1) % 3 === 0 && pi < pulses.length) out.push(pulses[pi++]);
    }
    while (pi < pulses.length) out.push(pulses[pi++]);
    return out;
  }

  var msgCache = {}; // keyed by site (or "_all") — stable jitter within a data window
  function getMessages(site) {
    if (!state.data) return [];
    var key = site || "_all";
    if (!msgCache[key]) msgCache[key] = buildMessages(state.data, site || null);
    return msgCache[key];
  }

  function apply(raw) {
    state.data = raw;
    state.totals = (raw && raw.totals) ? raw.totals : null;
    msgCache = {};
    state.messages = getMessages(null);
    try { window.dispatchEvent(new CustomEvent("plazma-live")); } catch (e) {}
  }

  function loadCache() {
    try {
      var raw = localStorage.getItem(CACHE_KEY);
      if (!raw) return null;
      var o = JSON.parse(raw);
      if (!o || !o._ts || (Date.now() - o._ts) > TTL) return null;
      return o.data;
    } catch (e) { return null; }
  }
  function saveCache(data) {
    try { localStorage.setItem(CACHE_KEY, JSON.stringify({ _ts: Date.now(), data: data })); } catch (e) {}
  }

  var inflight = false;
  function fetchNow() {
    if (inflight) return;
    inflight = true;
    fetch(RPC, {
      method: "POST",
      headers: { "Content-Type": "application/json", apikey: ANON_KEY, authorization: "Bearer " + ANON_KEY },
      body: "{}",
    })
      .then(function (r) { return r.ok ? r.json() : null; })
      .then(function (data) { if (data) { saveCache(data); apply(data); } })
      .catch(function () {})
      .then(function () { inflight = false; });
  }

  // init
  var cached = loadCache();
  if (cached) apply(cached);
  else fetchNow();

  // periodic refetch (only when visible) + refresh stale cache on focus
  setInterval(function () { if (!document.hidden) fetchNow(); }, TTL);
  document.addEventListener("visibilitychange", function () {
    if (!document.hidden && !loadCache()) fetchNow();
  });

  // imperative API
  window.plazmaLive = {
    messages: function (site) { return getMessages(site); },
    totals: function () { return state.totals; },
    raw: function () { return state.data; },
  };

  // React hooks (React is a global from the Babel-standalone setup)
  // useLiveMessages(fallback, site?) — site filters to a single centre (e.g. "baja")
  window.useLiveMessages = function (fallback, site) {
    var R = window.React;
    var st = R.useState(0);
    var set = st[1];
    R.useEffect(function () {
      function on() { set(function (n) { return n + 1; }); }
      window.addEventListener("plazma-live", on);
      return function () { window.removeEventListener("plazma-live", on); };
    }, []);
    var live = getMessages(site);
    return live && live.length ? live : (fallback || []);
  };
  window.useLiveTotals = function () {
    var R = window.React;
    var st = R.useState(state.totals);
    var val = st[0], set = st[1];
    R.useEffect(function () {
      function on() { set(state.totals); }
      on();
      window.addEventListener("plazma-live", on);
      return function () { window.removeEventListener("plazma-live", on); };
    }, []);
    return val;
  };
})();
