/* ===========================================================
   Reiktable — optional shared-backend sync layer
   Safe no-op when no backend is present (standalone / sandbox).
   Activates only if /api/campaign answers with header x-reiktable-api:1
   (i.e. when deployed on the Cloudflare Worker). Last-write-wins.
   =========================================================== */
(function () {
  const API = "/api/campaign";
  const ID = "default";
  let localRev = 0, dirtyAt = 0, active = false, saving = false, applyingRemote = false, timer = null;

  function applyRemote(stateObj, rev) {
    applyingRemote = true;
    try { window.Store.set(stateObj); } finally { applyingRemote = false; }
    localRev = rev;
  }

  async function push(initial) {
    if (saving) return;
    saving = true;
    try {
      const res = await fetch(`${API}?id=${ID}`, {
        method: "PUT", headers: { "content-type": "application/json" },
        body: JSON.stringify({ data: JSON.stringify(window.Store.get()), rev: localRev }),
      });
      if (res.ok) { const j = await res.json(); localRev = j.rev; }
    } catch (e) {} finally { saving = false; }
  }

  function scheduleSave() {
    if (!active || applyingRemote) return;
    dirtyAt = Date.now();
    clearTimeout(timer);
    timer = setTimeout(() => push(false), 1200);
  }

  async function poll() {
    if (!active || saving) return;
    if (Date.now() - dirtyAt < 4000) return; // let local edits settle before pulling
    try {
      const res = await fetch(`${API}?id=${ID}`, { headers: { accept: "application/json" } });
      if (res.status === 200) {
        const j = await res.json();
        if (j && j.rev > localRev) applyRemote(JSON.parse(j.data), j.rev);
      }
    } catch (e) {}
  }

  async function probe() {
    try {
      const res = await fetch(`${API}?id=${ID}`, { headers: { accept: "application/json" } });
      if (res.headers.get("x-reiktable-api") !== "1") return false; // no backend here
      if (res.status === 200) {
        const j = await res.json();
        if (j && j.data) applyRemote(JSON.parse(j.data), j.rev || 0);
        return true;
      }
      if (res.status === 404) { await push(true); return true; } // first run: seed the row
      return false;
    } catch (e) { return false; }
  }

  (async () => {
    const ok = await probe();
    if (!ok) return; // standalone mode — stays purely local (localStorage)
    active = true;
    window.__reiktableSync = true;
    window.Store.subscribe(scheduleSave);
    setInterval(poll, 12000);
    if (window.toast) window.toast("Connected · campaign syncing to the group", "grn");
  })();
})();
