/**
 * Generates an Excel-compatible XML Spreadsheet Blob (.xlsx / .xls).
 */
export function generateExcelBlob(
  title: string,
  columns: {key: string; header: string}[],
  data: Record<string, any>[]
): Blob {
  const headerCells = columns
    .map((c) => `<Cell><Data ss:Type="String">${c.header}</Data></Cell>`)
    .join('');

  const rowXML = data
    .map(
      (row) =>
        `<Row>` +
        columns
          .map((col) => {
            const val = row[col.key];
            const isNum = typeof val === 'number';
            const strVal = val === null || val === undefined ? '' : String(val);
            return `<Cell><Data ss:Type="${isNum ? 'Number' : 'String'}">${strVal}</Data></Cell>`;
          })
          .join('') +
        `</Row>`
    )
    .join('\n');

  const xmlContent = `<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
 <Worksheet ss:Name="${title.slice(0, 30)}">
  <Table>
   <Row>${headerCells}</Row>
   ${rowXML}
  </Table>
 </Worksheet>
</Workbook>`;

  return new Blob([xmlContent], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8;',
  });
}
