export type SubmitFormResult = { success: true } | { success: false; error: string };

/** Shared client-side POST helper for the site's forms — converts FormData to JSON and normalizes error messages. */
export async function submitForm(endpoint: string, formData: FormData): Promise<SubmitFormResult> {
  const payload = Object.fromEntries(formData.entries());

  try {
    const res = await fetch(endpoint, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });

    const json = await res.json().catch(() => ({}) as { error?: string });

    if (!res.ok) {
      return { success: false, error: json.error ?? "Something went wrong. Please try again." };
    }

    return { success: true };
  } catch {
    return { success: false, error: "Network error. Please check your connection and try again." };
  }
}
