/* Netlify Forms bridge.
   Netlify detects forms at deploy time by parsing STATIC HTML — it cannot see
   React-rendered markup. So index.html carries a hidden static <form> for each
   name below (that is what registers them), and the live React forms POST here.

   Submissions land in Netlify dashboard → Forms. Add email notifications there:
   Site configuration → Forms → Form notifications.

   On a non-Netlify preview this POST has nowhere to go; we log a warning and let
   the UI continue so the design stays reviewable. */

const NETLIFY_FORMS = ["subscribe", "download", "letter", "survey", "story"];

async function submitToNetlify(formName, data) {
  const body = new URLSearchParams({ "form-name": formName });
  Object.entries(data || {}).forEach(([k, v]) => body.append(k, v == null ? "" : String(v)));
  try {
    const res = await fetch("/", {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: body.toString(),
    });
    if (!res.ok) throw new Error("HTTP " + res.status);
    return { ok: true };
  } catch (e) {
    console.warn(`[forms] "${formName}" not delivered (expected outside Netlify):`, e.message);
    return { ok: false, error: e.message };
  }
}

Object.assign(window, { submitToNetlify, NETLIFY_FORMS });
