// Tiny JSON API helper used by every module.
"use strict";

export async function api(path, opts) {
    const res = await fetch(path, opts);
    if (res.status === 401) {
        // Auth cookie missing or wrong. Surface to the auth module which
        // shows the login overlay; the caller still gets an error so any
        // calling code stops cleanly.
        document.dispatchEvent(new CustomEvent("authrequired"));
        throw new Error("Unauthorized");
    }
    if (!res.ok) throw new Error(`${path} → HTTP ${res.status}`);
    return await res.json();
}

export async function apiJson(path, body, method = "POST") {
    return api(path, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body)
    });
}

export function escapeHtml(s) {
    return s.replace(/[&<>"']/g, c =>
        ({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[c]));
}
