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

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;
  }
}

let pushTimer = null;
let pushAbort = 0;

function remotePut(users, companies) {
  clearTimeout(pushTimer);
  const token = ++pushAbort;
  pushTimer = setTimeout(async () => {
    if (token !== pushAbort) return;
    try {
      await fetch(REMOTE_URL, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ users, companies }),
      });
    } catch (_) {}
  }, 250);
}

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