import type { jsPDF as JsPDFType } from 'jspdf';
// Vite serves the TTF as an asset URL; the font is fetched on first use and
// the base64 result cached for subsequent exports. DejaVu Sans supports
// Latin, Latin-Extended, Cyrillic, Greek and more — enough for room names in
// any European language.
import dejaVuSansUrl from 'dejavu-fonts-ttf/ttf/DejaVuSans.ttf?url';

export const PDF_FONT_FAMILY = 'DejaVuSans';

let cachedBase64: string | null = null;
let inflight: Promise<string> | null = null;

function arrayBufferToBase64(buffer: ArrayBuffer): string {
  const bytes = new Uint8Array(buffer);
  const CHUNK = 0x8000;
  let binary = '';
  for (let i = 0; i < bytes.length; i += CHUNK) {
    binary += String.fromCharCode.apply(null, Array.from(bytes.subarray(i, i + CHUNK)));
  }
  return btoa(binary);
}

async function loadFontBase64(): Promise<string> {
  if (cachedBase64) return cachedBase64;
  if (inflight) return inflight;
  inflight = (async () => {
    const resp = await fetch(dejaVuSansUrl);
    if (!resp.ok) throw new Error(`Failed to load PDF font: ${resp.status}`);
    const buf = await resp.arrayBuffer();
    cachedBase64 = arrayBufferToBase64(buf);
    return cachedBase64;
  })();
  try {
    return await inflight;
  } finally {
    inflight = null;
  }
}

/**
 * Register a Unicode TTF font (DejaVu Sans) with a jsPDF instance and make it
 * the active font. Required for Cyrillic / non-Latin text — jsPDF's built-in
 * Helvetica is WinAnsi-only.
 */
export async function applyPdfUnicodeFont(pdf: JsPDFType): Promise<void> {
  const base64 = await loadFontBase64();
  pdf.addFileToVFS('DejaVuSans.ttf', base64);
  pdf.addFont('DejaVuSans.ttf', PDF_FONT_FAMILY, 'normal');
  pdf.setFont(PDF_FONT_FAMILY, 'normal');
}
