// ===== Casepoint — capa de datos de doble modo =====
// Offline (preview / sin backend): la app usa localStorage como hasta ahora.
// Online (desplegada en Cloudflare con la API): datos compartidos vía D1.
// CP_API.online se decide al arrancar con GET /api/health.
(function () {
  const CP_API = { base: "/api", online: false, ready: false, user: null };

  async function post(path, body) {
    return fetch(CP_API.base + path, {
      method: "POST",
      credentials: "include",
      headers: body === undefined ? undefined : { "content-type": "application/json" },
      body: body === undefined ? undefined : JSON.stringify(body),
    });
  }

  CP_API.detect = async function () {
    try {
      const r = await fetch(CP_API.base + "/health", { credentials: "include" });
      CP_API.online = r.ok;
    } catch (e) {
      CP_API.online = false;
    }
    return CP_API.online;
  };

  CP_API.me = async function () {
    if (!CP_API.online) return null;
    try {
      const r = await fetch(CP_API.base + "/me", { credentials: "include" });
      if (!r.ok) return null;
      const j = await r.json();
      CP_API.user = j.user || null;
      return CP_API.user;
    } catch (e) {
      return null;
    }
  };

  CP_API.login = async function (username, pass) {
    const r = await post("/login", { username, pass });
    if (!r.ok) {
      const j = await r.json().catch(() => ({}));
      throw new Error(j.error || "login_failed");
    }
    const j = await r.json();
    CP_API.user = j.user;
    return j.user;
  };

  CP_API.logout = async function () {
    try { await post("/logout"); } catch (e) {}
    CP_API.user = null;
  };

  CP_API.bootstrap = async function (opts) {
    if (!CP_API.online) return null;
    try {
      const skip = opts && opts.skip ? "?skip=" + encodeURIComponent(opts.skip) : "";
      const r = await fetch(CP_API.base + "/bootstrap" + skip, { credentials: "include" });
      if (!r.ok) return null;
      return await r.json();
    } catch (e) {
      return null;
    }
  };

  CP_API.sync = async function (collection, payload) {
    if (!CP_API.online) return;
    try { await post("/sync/" + collection, payload); }
    catch (e) { console.warn("[CP_API] sync falló:", collection, e); }
  };

  CP_API.uploadPhoto = async function (blob) {
    if (!CP_API.online || !blob) return null;
    try {
      const r = await fetch(CP_API.base + "/upload", {
        method: "POST",
        credentials: "include",
        headers: { "content-type": blob.type || "image/jpeg" },
        body: blob,
      });
      if (!r.ok) return null;
      const j = await r.json();
      return j.url || null;
    } catch (e) {
      return null;
    }
  };

  CP_API.changePassword = async function (current, next) {
    const r = await post("/change-password", { current, next });
    if (!r.ok) {
      const j = await r.json().catch(() => ({}));
      throw new Error(j.error || "change_failed");
    }
    return true;
  };

  window.CP_API = CP_API;
})();
