/**
 * Generates a clean, valid PDF 1.4 spec Blob.
 */
export function generatePdfBlob(
  title: string,
  subtitle: string | undefined,
  columns: {key: string; header: string}[],
  data: Record<string, any>[]
): Blob {
  const dateStr = new Date().toISOString().slice(0, 10);
  const cleanTitle = title.replace(/[()\\]/g, '');
  const cleanSub = (subtitle || '').replace(/[()\\]/g, '');

  let streamText = `BT /F1 16 Tf 40 750 Td (${cleanTitle}) Tj ET\n`;
  streamText += `BT /F1 10 Tf 40 730 Td (LOYALY.AI Merchant OS Report - Date: ${dateStr}) Tj ET\n`;
  if (cleanSub) {
    streamText += `BT /F1 9 Tf 40 715 Td (${cleanSub}) Tj ET\n`;
  }

  let y = 680;
  const colHeaders = columns.map((c) => c.header).join('  |  ').replace(/[()\\]/g, '');
  streamText += `BT /F1 11 Tf 40 ${y} Td (${colHeaders}) Tj ET\n`;
  y -= 20;

  data.forEach((row) => {
    if (y > 50) {
      const rowStr = columns
        .map((c) => String(row[c.key] ?? ''))
        .join('  |  ')
        .replace(/[()\\]/g, '');
      streamText += `BT /F1 9 Tf 40 ${y} Td (${rowStr}) Tj ET\n`;
      y -= 15;
    }
  });

  const pdfBody = `%PDF-1.4
1 0 obj
<< /Type /Catalog /Pages 2 0 R >>
endobj
2 0 obj
<< /Type /Pages /Kids [3 0 R] /Count 1 >>
endobj
3 0 obj
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>
endobj
4 0 obj
<< /Length ${streamText.length} >>
stream
${streamText}endstream
endobj
5 0 obj
<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>
endobj
xref
0 6
0000000000 65535 f 
0000000009 00000 n 
0000000058 00000 n 
0000000115 00000 n 
0000000244 00000 n 
0000000320 00000 n 
trailer
<< /Size 6 /Root 1 0 R >>
startxref
390
%%EOF`;

  return new Blob([pdfBody], {type: 'application/pdf'});
}
