export type LeadSubmission = {
  propertyAddress: string;
  name: string;
  phone: string;
  email?: string;
  timeline?: string;
  leadSource: string;
  consent: boolean;
};

const LEAD_ENDPOINT = "https://leads.theamericanfeed.us/api.php";

export async function submitLeadToCrm(lead: LeadSubmission) {
  const response = await fetch(LEAD_ENDPOINT, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      name: lead.name,
      phone: lead.phone,
      email: lead.email ?? "",
      address: lead.propertyAddress,
      lead_source: `V2 - ${lead.leadSource}`,
      timeline: lead.timeline ?? "",
      consent: lead.consent ? "1" : "0",
      consent_language: "Cash offer request consent accepted on V2 preview site.",
      landing_page: window.location.href,
    }),
  });
  const result = await response.json().catch(() => ({}));
  if (!response.ok || !result.ok) throw new Error(result.error || "Submission failed");
  return { success: true };
}
