/* api.jsx — fetch wrapper for the Cloudflare Pages Functions API.
   Stores the session token in localStorage and attaches it as a Bearer header. */
const API = {
  token: localStorage.getItem("wh_token") || null,
  setToken(t) {
    this.token = t || null;
    if (t) localStorage.setItem("wh_token", t);
    else localStorage.removeItem("wh_token");
  },
  async call(method, path, bodyObj) {
    const headers = {};
    if (this.token) headers["Authorization"] = "Bearer " + this.token;
    if (bodyObj) headers["content-type"] = "application/json";
    let res;
    try {
      res = await fetch("/api/" + path, {
        method,
        headers,
        body: bodyObj ? JSON.stringify(bodyObj) : undefined,
      });
    } catch (e) {
      return { ok: false, status: 0, data: { error: "เชื่อมต่อเซิร์ฟเวอร์ไม่ได้" } };
    }
    let data = {};
    try { data = await res.json(); } catch (e) {}
    return { ok: res.ok, status: res.status, data: data || {} };
  },
  get(path) { return this.call("GET", path); },
  post(path, body) { return this.call("POST", path, body); },
  del(path) { return this.call("DELETE", path); },
};
window.API = API;
