/* ============================================================
   IRONLOG — Front-end API client.
   Thin wrapper over fetch. Same-origin; the session cookie is
   httpOnly and sent automatically. Exposed on window.API.
   The design never talks to Mongo or the AI directly — only here.
   ============================================================ */
const API = (function () {
  async function req(method, path, body) {
    const opts = { method, credentials: "same-origin", headers: {} };
    if (body !== undefined) {
      opts.headers["Content-Type"] = "application/json";
      opts.body = JSON.stringify(body);
    }
    const res = await fetch("/api" + path, opts);
    const ct = res.headers.get("content-type") || "";
    const data = ct.includes("application/json") ? await res.json().catch(() => ({})) : await res.text();
    if (!res.ok) {
      const msg = (data && data.error) || ("Request failed (" + res.status + ")");
      const err = new Error(msg);
      err.status = res.status;
      throw err;
    }
    return data;
  }

  return {
    // auth
    me: () => req("GET", "/me"),
    login: (password) => req("POST", "/login", { password }),
    logout: () => req("POST", "/logout"),

    // content
    getProfile: () => req("GET", "/profile"),
    saveProfile: (patch) => req("PUT", "/profile", patch),

    // prs
    getPRs: () => req("GET", "/prs"),
    addPR: (pr) => req("POST", "/prs", pr),
    savePR: (id, pr) => req("PUT", "/prs/" + id, pr),
    deletePR: (id) => req("DELETE", "/prs/" + id),
    prSummary: (id) => req("GET", "/prs/" + id + "/summary?n=" + Date.now()),

    // foods (food calendar)
    getFoods: () => req("GET", "/foods"),
    getFood: (date) => req("GET", "/foods/" + date),
    saveFood: (date, entry) => req("POST", "/foods", { date, ...entry }),
    deleteFood: (date) => req("DELETE", "/foods/" + date),
    estimateCalories: (items) => req("POST", "/foods/estimate", { items }),

    // posts + comments (daily wall)
    getPosts: () => req("GET", "/posts"),
    addPost: (p) => req("POST", "/posts", p),
    savePost: (id, p) => req("PUT", "/posts/" + id, p),
    deletePost: (id) => req("DELETE", "/posts/" + id),
    addComment: (scope, text, name) => req("POST", "/comments", { scope, text, name }),
    getComments: (scope) => req("GET", "/comments?scope=" + encodeURIComponent(scope)),

    // video
    getVideo: () => req("GET", "/video"),
    saveVideo: (v) => req("PUT", "/video", v),

    // profile photos
    deleteProfilePhoto: (which, imageId) => req("DELETE", "/profile/photo", { which, imageId }),

    // visit telemetry (server resolves city/device/source + notifies owner)
    visit: (referrer) => req("POST", "/visit", { referrer }),

    // sessions
    getSessions: () => req("GET", "/sessions"),
    saveSession: (date, entry) => req("POST", "/sessions", { date, ...entry }),
    deleteSession: (date) => req("DELETE", "/sessions/" + date),

    // supplements
    getSupplements: () => req("GET", "/supplements"),
    addSupplement: (s) => req("POST", "/supplements", s),
    saveSupplement: (id, s) => req("PUT", "/supplements/" + id, s),
    deleteSupplement: (id) => req("DELETE", "/supplements/" + id),

    // blocks (journey wall)
    getBlocks: () => req("GET", "/blocks"),
    addBlock: (b) => req("POST", "/blocks", b),
    saveBlock: (id, b) => req("PUT", "/blocks/" + id, b),
    deleteBlock: (id) => req("DELETE", "/blocks/" + id),

    // images
    upload: (dataUrl, extra) => req("POST", "/upload", { dataUrl, ...(extra || {}) }),

    // chat
    chat: (message, images, history) => req("POST", "/chat", { message, images, history }),

    // export (returns a Blob so we can handle auth errors + filename)
    async exportSessions() {
      const res = await fetch("/api/export", { credentials: "same-origin" });
      if (!res.ok) throw new Error("Export failed (" + res.status + ")");
      const blob = await res.blob();
      const dispo = res.headers.get("content-disposition") || "";
      const m = dispo.match(/filename="?([^"]+)"?/);
      const name = m ? m[1] : "ironlog-sessions.txt";
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url; a.download = name;
      document.body.appendChild(a); a.click(); a.remove();
      setTimeout(() => URL.revokeObjectURL(url), 1000);
    },
  };
})();

/* ---------- Image file picker -> data URL (for uploads) ---------- */
function pickImageFile() {
  return new Promise((resolve) => {
    const input = document.createElement("input");
    input.type = "file";
    input.accept = "image/png,image/jpeg,image/webp,image/gif";
    input.onchange = () => {
      const file = input.files && input.files[0];
      if (!file) return resolve(null);
      if (file.size > 8 * 1024 * 1024) {
        alert("That image is over 8MB — please pick a smaller one.");
        return resolve(null);
      }
      const reader = new FileReader();
      reader.onload = () => resolve({ dataUrl: reader.result, name: file.name });
      reader.onerror = () => resolve(null);
      reader.readAsDataURL(file);
    };
    input.click();
  });
}

window.API = API;
window.pickImageFile = pickImageFile;
