const NETWORK_ERROR_MESSAGE = "Unable to reach the server. Please check your connection and try again.";

/**
 * Drop-in replacement for fetch() in "use client" components. A real network
 * failure (backend unreachable, DNS, offline) makes fetch() reject with a raw
 * TypeError — every call site in this app is written as `const res = await
 * fetch(...); if (!res.ok) { ...body?.message... }`, which never expects
 * fetch() itself to throw, so an unhandled rejection leaves the triggering
 * button/state stuck forever with no error shown.
 *
 * clientFetch() never throws: on a network failure it resolves to a
 * synthetic Response (503, JSON body with `message`) instead, so every
 * existing `!res.ok` / `body?.message` call site handles it correctly
 * without being individually rewritten.
 */
export async function clientFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
  try {
    return await fetch(input, init);
  } catch {
    return new Response(JSON.stringify({ message: NETWORK_ERROR_MESSAGE }), {
      status: 503,
      statusText: "Network Error",
      headers: { "Content-Type": "application/json" },
    });
  }
}
