// Browser-download helpers voor gegenereerde documenten. Enkel bruikbaar in
// client components (gebruikt Blob/URL/DOM).

export function downloadBlob(bestandsnaam: string, blob: Blob) {
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = bestandsnaam;
  a.click();
  URL.revokeObjectURL(url);
}

export function downloadTekst(bestandsnaam: string, inhoud: string, mime: string) {
  downloadBlob(bestandsnaam, new Blob([inhoud], { type: mime }));
}

function escapeHtml(s: string): string {
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}

/** Zet een regel met vette-tekst-markers (U+E000…U+E001) om naar veilige HTML met <b>. */
function regelNaarHtml(regel: string): string {
  return regel
    .split(/([])/)
    .reduce(
      (acc, deel) => {
        if (deel === "") return { ...acc, vet: true };
        if (deel === "") return { ...acc, vet: false };
        if (deel === "") return acc;
        const stuk = escapeHtml(deel);
        return { ...acc, html: acc.html + (acc.vet ? `<b>${stuk}</b>` : stuk) };
      },
      { html: "", vet: false }
    ).html;
}

/** Word-compatibel .doc-bestand (HTML) zodat het kantoor met track changes verder kan. */
export function downloadWord(bestandsnaam: string, titel: string, tekst: string) {
  const body = tekst
    .split("\n")
    .map((regel) => `<p>${regelNaarHtml(regel) || "&nbsp;"}</p>`)
    .join("");
  const html = `<html xmlns:w="urn:schemas-microsoft-com:office:word"><head><meta charset="utf-8"><title>${escapeHtml(
    titel
  )}</title></head><body style="font-family:Calibri,sans-serif;font-size:11pt;">${body}</body></html>`;
  downloadTekst(bestandsnaam, html, "application/msword");
}
