const API_BASE = "https://api.jb26.co.za/modules/";

async function api(endpoint, method = "GET", data = null) {
  const options = {
    method,
    headers: {
      "Content-Type": "application/json",
      "Accept": "application/json"
    },
    credentials: "same-origin"
  };

  if (data) {
    options.body = JSON.stringify(data);
  }

  const response = await fetch(API_BASE + endpoint, options);
  const text = await response.text();

  let json;
  try {
    json = JSON.parse(text);
  } catch (e) {
    throw new Error("Invalid JSON from server");
  }

  // ❗ DO NOT throw on 401 / 403 — return payload
  if (!response.ok) {
    return json;
  }

  return json;
}
