/**
 * Generates a clean UTF-8 CSV Blob.
 */
export function generateCsvBlob(
  columns: {key: string; header: string}[],
  data: Record<string, any>[]
): Blob {
  const headers = columns.map((c) => `"${c.header.replace(/"/g, '""')}"`).join(',');

  const rows = data.map((row) =>
    columns
      .map((col) => {
        const val = row[col.key];
        const strVal = val === null || val === undefined ? '' : String(val);
        return `"${strVal.replace(/"/g, '""')}"`;
      })
      .join(',')
  );

  const csvContent = [headers, ...rows].join('\r\n');
  return new Blob(['\uFEFF' + csvContent], {type: 'text/csv;charset=utf-8;'});
}
