// Cloud storage adapter — talks to /api/state behind Cloudflare Access.
// Used when the app is served over https. localStorage adapter is the
// offline / file:// fallback.
//
// The store calls adapter.load() synchronously at construction, so we seed
// from a localStorage mirror first, then refresh from the cloud once the
// app boots and replace the store contents atomically.

(function () {
  const isCloud = typeof location !== "undefined" && location.protocol === "https:";
  if (!isCloud) {
    window.cloudAdapter = null;
    return;
  }

  const LS_MIRROR = "personal-calendar:cloud-mirror:v1";
  let saveTimer = null;
  let lastWritten = null;

  async function fetchFromCloud() {
    const r = await fetch("/api/state", { credentials: "include" });
    if (!r.ok) throw new Error("HTTP " + r.status);
    const j = await r.json();
    return j.events || [];
  }

  async function pushToCloud(events) {
    const body = JSON.stringify({ events });
    if (body === lastWritten) return; // nothing actually changed
    lastWritten = body;
    const r = await fetch("/api/state", {
      method: "PUT",
      credentials: "include",
      headers: { "content-type": "application/json" },
      body,
    });
    if (!r.ok) throw new Error("HTTP " + r.status);
  }

  window.cloudAdapter = {
    load() {
      try { return JSON.parse(localStorage.getItem(LS_MIRROR) || "[]"); }
      catch { return []; }
    },
    save(events) {
      // Keep a local mirror so refreshes are instant even on a flaky network.
      try { localStorage.setItem(LS_MIRROR, JSON.stringify(events)); } catch {}
      // Debounce: collapse rapid edits into a single PUT.
      if (saveTimer) clearTimeout(saveTimer);
      saveTimer = setTimeout(() => {
        pushToCloud(events).catch(e => {
          console.warn("Cloud push failed:", e.message);
          if (window.showToast) window.showToast({
            text: "Saved locally — cloud sync failed",
            variant: "error",
          });
        });
      }, 600);
    },
    // Called once at boot to replace the local mirror with the authoritative
    // cloud state. Safe to call multiple times.
    refresh: fetchFromCloud,
  };
})();
