import { headers, BASE } from "./client";

export async function exportPptx(token, markdown, title) {
  const res = await fetch(`${BASE}/export/pptx`, {
    method: "POST", headers: headers(token),
    body: JSON.stringify({ markdown, title }),
  });
  if (!res.ok) throw new Error("Export failed");
  const blob = await res.blob();
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a"); a.href = url;
  a.download = `${(title || "presentation").replace(/[^\w\s-]/g, "").trim().replace(/\s+/g, "-").slice(0, 60) || "presentation"}.pptx`;
  a.click(); URL.revokeObjectURL(url);
}

export async function exportDocx(token, markdown, title) {
  const res = await fetch(`${BASE}/export/docx`, {
    method: "POST", headers: headers(token),
    body: JSON.stringify({ markdown, title }),
  });
  if (!res.ok) throw new Error("Export failed");
  const blob = await res.blob();
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a"); a.href = url;
  a.download = `${(title || "document").replace(/[^\w\s-]/g, "").trim().replace(/\s+/g, "-").slice(0, 60) || "document"}.docx`;
  a.click(); URL.revokeObjectURL(url);
}

export async function downloadZip(token, markdown, title) {
  const res = await fetch(`${BASE}/files/download-zip`, {
    method: "POST", headers: headers(token),
    body: JSON.stringify({ markdown, title }),
  });
  if (!res.ok) throw new Error("Download failed");
  const ct = res.headers.get("content-type") || "";
  if (ct.includes("application/zip")) {
    const blob = await res.blob();
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "son-of-anton-code.zip";
    a.click();
    URL.revokeObjectURL(url);
  } else {
    const data = await res.json();
    if (data.error) throw new Error(data.error);
  }
}
