(function (global) {
  "use strict";

  let csrfToken = "";

  function setCsrfToken(token) {
    csrfToken = token || "";
  }

  function requestOptions(method, body) {
    const normalized = String(method || "GET").toUpperCase();
    const options = { method: normalized, headers: {} };
    if (!["GET", "HEAD", "OPTIONS"].includes(normalized) && csrfToken) {
      options.headers["X-CSRF-Token"] = csrfToken;
    }
    if (body !== null && body !== undefined) {
      options.headers["Content-Type"] = "application/json";
      options.body = JSON.stringify(body);
    }
    return options;
  }

  async function request(url, method, body) {
    const response = await fetch(url, requestOptions(method, body));
    let payload = {};
    try {
      payload = await response.json();
    } catch (_error) {
      payload = {};
    }
    if (!response.ok || payload.error) {
      const error = new Error(payload.error || "请求失败");
      error.status = response.status;
      error.payload = payload;
      throw error;
    }
    return payload;
  }

  global.MobileAPI = { setCsrfToken, request };
})(window);
