// Dashboard API client — HTTP helpers and configuration.
// Loaded as a <script> before panel.jsx; exposes globals.
// Uses lazy access to APP_CONFIG so the async /config fetch has time to complete.

function _api()  { return window.APP_CONFIG?.api_url || "http://localhost:4000"; }
function _key()  { return window.APP_CONFIG?.api_key || "sk-proxy-local-dev"; }
function _debug(){ return window.APP_CONFIG?.debug || false; }

function _headers() { return { Authorization: `Bearer ${_key()}`, "Content-Type": "application/json" }; }
const _parseBody = async (r) => {
  const ct = r.headers.get("content-type") || "";
  if (ct.includes("application/json")) return await r.json();
  return await r.text();
};

const get = (path) => fetch(`${_api()}${path}`, { headers: _headers() })
  .then(async r => {
    const body = await _parseBody(r);
    if (r.ok) return body;
    return { ok: false, status: r.status, body };
  })
  .catch((e) => ({ ok: false, status: 0, body: String(e) }));

const post = (path, body) => fetch(`${_api()}${path}`, { method: "POST", headers: _headers(), body: JSON.stringify(body) })
  .then(async r => {
    const payload = await _parseBody(r);
    if (r.ok) return payload;
    return { ok: false, status: r.status, body: payload };
  })
  .catch((e) => ({ ok: false, status: 0, body: String(e) }));
