const API_BASE =
  process.env.NEXT_PUBLIC_API_URL ||
  process.env.API_URL ||
  "https://api.adblast.com.bd/api";

/* =========================
   PROJECTS
========================= */
export async function getProjects() {
  const res = await fetch(`${API_BASE}/projects`, { cache: "no-store" });
  if (!res.ok) {
    const text = await res.text();
    throw new Error(`Failed to load projects: ${res.status}\n${text}`);
  }
  return res.json();
}

export async function getProject(slug: string) {
  const res = await fetch(`${API_BASE}/projects/${slug}`, {
    cache: "no-store",
  });
  if (!res.ok) {
    const text = await res.text();
    throw new Error(`Failed to load project ${slug}: ${res.status}\n${text}`);
  }
  return res.json();
}

/* =========================
   CONTACT / LEADS
========================= */
export async function submitLead(
  data: {
    name: string;
    email?: string;
    phone?: string;
    message?: string;
    company?: string;
    project_type?: string;
    timeline?: string;
  },
  signal?: AbortSignal
) {
  const res = await fetch(`${API_BASE}/leads`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
    },
    body: JSON.stringify(data),
    signal, // ✅ supports abort/timeout
  });

  const text = await res.text();

  // ✅ Handle non-JSON response safely
  if (!res.ok) {
    throw new Error(`Lead submit failed: ${res.status}\n${text}`);
  }

  try {
    return JSON.parse(text);
  } catch {
    // if server returns empty or plain text
    return { ok: true };
  }
}

