const DEFAULT_API_BASE = "/v1";

/**
 * API origin for fetch(): root-relative prefix (e.g. /v1) or absolute URL (https://host/v1).
 * Root-relative values are forced to start with "/" so requests work from any SPA route
 * (e.g. /support); otherwise "v1/support" would resolve under the current path and 404.
 */
function normalizeApiBase(raw) {
  const s = String(raw ?? "").trim();
  const base = s || DEFAULT_API_BASE;

  if (/^https?:\/\//i.test(base)) {
    return base.replace(/\/+$/, "") || DEFAULT_API_BASE;
  }

  const path = base.startsWith("/") ? base : `/${base}`;
  return path.replace(/\/+$/, "") || DEFAULT_API_BASE;
}

export const API_BASE = normalizeApiBase(import.meta.env.VITE_API_BASE);
