/**
 * Small CSV-export helper. No new dependency.
 *
 * Build a CSV string from an array of objects + a header list, wrap it
 * in a Blob, and trigger a download.
 *
 * Usage:
 *   exportToCsv('attendance-history-2026.csv', rows, [
 *     { key: 'date',    label: 'Date'    },
 *     { key: 'status',  label: 'Status'  },
 *     ...
 *   ]);
 */

export interface CsvColumn<T> {
  key: keyof T | string;
  label: string;
  format?: (row: T) => string | number | null | undefined;
}

const escape = (v: unknown): string => {
  if (v === null || v === undefined) return '';
  const s = String(v);
  // escape double-quotes and wrap in quotes if the value contains
  // comma, newline, or quote
  if (/[",\n\r]/.test(s)) {
    return `"${s.replace(/"/g, '""')}"`;
  }
  return s;
};

export function buildCsv<T>(rows: T[], columns: CsvColumn<T>[]): string {
  const header = columns.map(c => escape(c.label)).join(',');
  const body = rows.map(row =>
    columns
      .map(c => {
        const raw = c.format ? c.format(row) : (row as any)[c.key];
        return escape(raw);
      })
      .join(',')
  );
  return [header, ...body].join('\r\n');
}

export function exportToCsv<T>(filename: string, rows: T[], columns: CsvColumn<T>[]): void {
  if (typeof window === 'undefined') return;
  const csv = buildCsv(rows, columns);
  // BOM so Excel opens it as UTF-8
  const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  setTimeout(() => {
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  }, 0);
}
