export const API_BASE = (process.env.NEXT_PUBLIC_API_BASE_URL || "").replace(/\/$/, ""); export function apiUrl(path: string): string { if (/^https?:\/\//i.test(path)) return path; const normalizedPath = path.startsWith("/") ? path : `/${path}`; if (API_BASE.endsWith("/api") && normalizedPath.startsWith("/api/")) { return `${API_BASE}${normalizedPath.slice(4)}`; } return `${API_BASE}${normalizedPath}`; } export async function apiFetch( path: string, init?: RequestInit ): Promise { const res = await fetch(apiUrl(path), { credentials: "include", ...init, headers: init?.body instanceof FormData ? init.headers : { "Content-Type": "application/json", ...(init?.headers || {}), }, }); const data = await res.json().catch(() => ({})); if (!res.ok) { throw new Error(data?.detail || data?.error || `HTTP ${res.status}`); } return data as T; }