/* Load GOA flow stats from bank landing stats.json (CORS on bank). */
(function () {
  var STATS_URL = "https://bank.hacktivism.ch/intro/stats.json";
  var BANK_INTRO = "https://bank.hacktivism.ch/intro/";

  function fmtCest(unix, fallback) {
    var base = "";
    if (fallback) {
      base = String(fallback).replace(/\s*(CEST|CET|UTC|Z)\s*$/i, "").trim();
    } else if (unix != null && unix !== "") {
      try {
        base = new Intl.DateTimeFormat("de-CH", {
          timeZone: "Europe/Zurich",
          year: "numeric",
          month: "2-digit",
          day: "2-digit",
          hour: "2-digit",
          minute: "2-digit",
          hour12: false
        }).format(new Date(Number(unix) * 1000));
      } catch (e) {
        base = "";
      }
    }
    return base ? base + " Europe/Zurich" : "";
  }

  function set(id, v) {
    var el = document.getElementById(id);
    if (el) el.textContent = v == null || v === "" ? "—" : String(v);
  }

  function setAmt(id, rowOrAmt, altMap) {
    var el = document.getElementById(id);
    if (!el) return;
    if (window.GoaAmount) {
      var f = GoaAmount.pick(rowOrAmt, altMap);
      el.textContent = f.display;
      if (f.title && f.title !== f.display) el.setAttribute("title", f.title);
      else el.removeAttribute("title");
    } else {
      var raw = rowOrAmt && typeof rowOrAmt === "object"
        ? (rowOrAmt.amount_alt || rowOrAmt.amount || "—")
        : (rowOrAmt == null || rowOrAmt === "" ? "—" : String(rowOrAmt));
      el.textContent = raw;
    }
  }

  function showFallback(msg) {
    var box = document.getElementById("stats");
    var foot = document.getElementById("st-foot");
    if (box) box.hidden = false;
    if (foot) {
      foot.hidden = false;
      foot.className = "stats-foot err";
      foot.innerHTML =
        (msg || "Stats offline") +
        ' · <a href="' + BANK_INTRO + '">bank.hacktivism.ch</a>';
    }
  }

  function loadStats() {
    var box = document.getElementById("stats");
    var foot = document.getElementById("st-foot");
    if (!box) return;
    box.hidden = false;

    // Same-origin first (bank landing), else public bank URL
    var urls = [];
    if (location.hostname.indexOf("bank.hacktivism") !== -1) {
      urls.push("stats.json");
    }
    urls.push(STATS_URL);

    function tryNext(i) {
      if (i >= urls.length) {
        showFallback("No stats");
        return;
      }
      fetch(urls[i], { cache: "no-store", mode: "cors" })
        .then(function (r) {
          if (!r.ok) throw new Error("HTTP " + r.status);
          return r.json();
        })
        .then(function (d) {
          if (!d || !d.ok) throw new Error("bad stats");
          if (window.GoaAmount) GoaAmount.rememberAlt(d);
          var w = d.withdraws || {};
          var h24 = w.last_24h || {};
          var h7 = w.last_7d || {};
          var ba = d.bank_accounts || {};
          var wl = d.wallets || {};
          var flow = d.flow || {};
          var fin = flow.incoming || {};
          var fwd = flow.withdraw || {};
          set("st-accounts", ba.total != null ? ba.total : "—");
          set("st-wallets", wl.unique_reserves != null ? wl.unique_reserves : "—");
          setAmt("st-incoming", fin.amount_alt ? fin : (fin.amount || flow.total_in || "—"), d.alt_unit_names);
          setAmt("st-withdraw", fwd.amount_alt ? fwd : (fwd.amount || w.total_amount || "—"), d.alt_unit_names);
          setAmt("st-24h", h24.amount_alt ? h24 : (h24.amount || "GOA:0"), d.alt_unit_names);
          setAmt("st-7d", h7.amount_alt ? h7 : (h7.amount || "GOA:0"), d.alt_unit_names);

          var list = document.getElementById("st-recent");
          if (list) {
            list.innerHTML = "";
            var rows = (d.recent_withdraws || []).slice(0, 3);
            if (!rows.length) {
              var empty = document.createElement("li");
              empty.className = "meta";
              empty.textContent = "—";
              list.appendChild(empty);
            } else {
              rows.forEach(function (row) {
                var li = document.createElement("li");
                var amt = document.createElement("span");
                amt.className = "amt";
                if (window.GoaAmount) {
                  var af = GoaAmount.pick(row, d.alt_unit_names);
                  amt.textContent = af.display;
                  if (af.title && af.title !== af.display) amt.setAttribute("title", af.title);
                } else {
                  amt.textContent = row.amount_alt || row.amount || "?";
                }
                var meta = document.createElement("span");
                meta.className = "meta";
                meta.textContent = fmtCest(row.at_unix, row.at || row.at_iso) || "";
                li.appendChild(amt);
                li.appendChild(meta);
                list.appendChild(li);
              });
            }
          }
          if (foot) {
            foot.hidden = false;
            foot.className = "stats-foot";
            foot.innerHTML =
              'Source: <a href="' + BANK_INTRO + '">bank.hacktivism.ch</a>' +
              (d.generated_at_human ? " · " + d.generated_at_human : "") +
              (d.source ? " · " + d.source : "");
          }
        })
        .catch(function () {
          tryNext(i + 1);
        });
    }
    tryNext(0);
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", loadStats);
  } else {
    loadStats();
  }
})();
