/* global */
// Lichtgewicht fetch-wrapper. Slaat de JWT op in localStorage onder "kwist.token".
// Plaatst zichzelf op window.kwistApi zodat andere .jsx-bestanden hem kunnen gebruiken
// zonder modules-systeem.

const TOKEN_KEY = "kwist.token";

function getToken() {
  try { return localStorage.getItem(TOKEN_KEY) || null; } catch { return null; }
}
function setToken(t) {
  try {
    if (t) localStorage.setItem(TOKEN_KEY, t);
    else localStorage.removeItem(TOKEN_KEY);
  } catch { /* ignore */ }
}

async function request(method, path, body) {
  const headers = {};
  if (body !== undefined) headers["content-type"] = "application/json";
  const t = getToken();
  if (t) headers.authorization = `Bearer ${t}`;
  const res = await fetch(path, {
    method,
    headers,
    body: body !== undefined ? JSON.stringify(body) : undefined,
  });
  let data = null;
  if (res.status !== 204) {
    const text = await res.text();
    try { data = text ? JSON.parse(text) : null; } catch { data = text; }
  }
  if (res.status === 401 && t) {
    // Token is verlopen of niet meer geldig — gooi 'm weg en laat app.jsx
    // beslissen wat er gebeurt (event-listener) zonder de huidige call te
    // breken voor de caller.
    setToken(null);
    window.dispatchEvent(new CustomEvent("kwist:unauthorized"));
  }
  if (!res.ok) {
    const err = new Error((data && data.error) || `HTTP ${res.status}`);
    err.status = res.status;
    err.data = data;
    throw err;
  }
  return data;
}

const api = {
  get: (p) => request("GET", p),
  post: (p, b) => request("POST", p, b),
  put: (p, b) => request("PUT", p, b),
  patch: (p, b) => request("PATCH", p, b),
  del: (p) => request("DELETE", p),
  getToken, setToken,

  // Convenience helpers
  login: (email, password) => request("POST", "/api/auth/login", { email, password }),
  signup: (email, password, name) => request("POST", "/api/auth/signup", { email, password, name }),
  me: () => request("GET", "/api/auth/me"),
  siteSettings: () => request("GET", "/api/site-settings"),
  features: () => request("GET", "/api/features"),
};

window.kwistApi = api;
