// API wrapper — always sends auth cookie + surfaces HTTP errors.

async function request(url, opts = {}) {
  const res = await fetch(url, { credentials: 'same-origin', ...opts });
  const text = await res.text();
  const json = text ? (() => { try { return JSON.parse(text); } catch { return { error: text }; } })() : {};
  if (!res.ok) {
    const err = new Error(json.error || `HTTP ${res.status}`);
    err.status = res.status;
    err.body = json;
    throw err;
  }
  return json;
}

const jsonHeaders = { 'Content-Type': 'application/json' };

const api = {
  get:  (url)       => request(url),
  post: (url, body) => request(url, { method: 'POST', headers: jsonHeaders, body: JSON.stringify(body) }),
  put:  (url, body) => request(url, { method: 'PUT',  headers: jsonHeaders, body: JSON.stringify(body) }),
  del:  (url)       => request(url, { method: 'DELETE' }),
  // Tolerant variants that return null instead of throwing — used for polling
  tryGet: async (url) => { try { return await request(url); } catch { return null; } },
};

Object.assign(window, { api });
