let csrf = "";
export function setCsrf(value: string) {
  csrf = value;
}
export async function api<T = any>(
  path: string,
  options: RequestInit = {},
): Promise<T> {
  const res = await fetch(path, {
    ...options,
    credentials: "same-origin",
    headers: {
      "Content-Type": "application/json",
      "X-WP-Pulse": "1",
      "X-CSRF-Token": csrf,
      ...options.headers,
    },
  });
  const data = await res.json();
  if (!res.ok) {
    if (res.status === 401 && path !== "/api/auth/login")
      window.dispatchEvent(new Event("wp-pulse-unauthorized"));
    throw new Error(data.error || `HTTP ${res.status}`);
  }
  return data;
}
