// api.js — zentraler Fetch-Wrapper + Token-Handling.
// Einziges Modul, das localStorage nutzt (nur fuers Token-Feld — laut Konvention ok).

let TOKEN = localStorage.getItem("mc_token") || "";

export function getToken() { return TOKEN; }

export function setToken(t) {
  TOKEN = (t || "").trim();
  localStorage.setItem("mc_token", TOKEN);
}

export function hdr() {
  const h = { "Content-Type": "application/json" };
  if (TOKEN) h["X-MC-Token"] = TOKEN;
  return h;
}

// HuggingFace-Token (optional) — wird bei Downloads als HF_TOKEN mitgesendet.
export function getHfToken() { return localStorage.getItem("mc_hf_token") || ""; }
export function setHfToken(t) { localStorage.setItem("mc_hf_token", (t || "").trim()); }

export async function api(path, opts = {}) {
  const r = await fetch(path, { headers: hdr(), ...opts });
  const data = await r.json().catch(() => ({}));
  if (!r.ok) throw new Error(data.error || ("HTTP " + r.status));
  return data;
}
