/* Shared state via Pages function + KV, with silent failure (local-only fallback). */
const REMOTE_URL = "/api/store";

let lastSent = "";
let lastSentAt = 0;
let pushTimer = null;
let pushAbort = 0;
let retryStep = 0;
let pendingPayload = null;

async function remoteGet() {
  try {
    const r = await fetch(REMOTE_URL, { cache: "no-store" });
    if (!r.ok) return null;
    const j = await r.json();
    if (!j || !Array.isArray(j.users) || !Array.isArray(j.companies)) return null;
    if (j.users.length < 2) return null; // placeholder/test state, ignore
    return j;
  } catch (_) {
    return null;
  }
}

async function send(payload) {
  const token = ++pushAbort;
  try {
    const r = await fetch(REMOTE_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: payload,
    });
    if (!r.ok) throw new Error("HTTP " + r.status);
    if (token !== pushAbort) return;
    lastSent = payload;
    lastSentAt = Date.now();
    retryStep = 0;
    window.__remoteError = "";
  } catch (e) {
    if (token !== pushAbort) return;
    window.__remoteError = String(e.message || e);
    if (retryStep < 4) {
      const delay = 5000 * Math.pow(2, retryStep++);
      clearTimeout(pushTimer);
      pushTimer = setTimeout(() => { if (pendingPayload) send(pendingPayload); }, delay);
    }
  }
}

function remotePut(users, companies) {
  const payload = JSON.stringify({ users, companies });
  if (payload === lastSent) return;
  pendingPayload = payload;
  clearTimeout(pushTimer);
  pushTimer = setTimeout(() => send(payload), 900);
}

function recentlyPushed(ms) {
  return Date.now() - lastSentAt < (ms || 4000);
}

window.remoteGet = remoteGet;
window.remotePut = remotePut;
window.recentlyPushed = recentlyPushed;
