/**
 * Build and trigger a browser download of collection cards as CSV.
 */
export function downloadCollectionCardsCsv(cards, collectionName) {
  if (cards.length === 0) {
    alert('No cards to download');
    return;
  }

  const headers = [
    'Name',
    'Set Name',
    'Set Code',
    'Card Number',
    'Rarity',
    'Game',
    'Mana Cost',
    'CMC',
    'Type',
    'Colors',
    'Oracle Text',
    'Power',
    'Toughness',
    'Market Price',
    'Quantity',
    'Added Date',
  ];

  const csvRows = [
    headers.join(','),
    ...cards.map((card) =>
      [
        `"${(card.name || '').replace(/"/g, '""')}"`,
        `"${(card.set_name || '').replace(/"/g, '""')}"`,
        `"${card.set_code || ''}"`,
        `"${card.card_number || ''}"`,
        `"${card.rarity || ''}"`,
        `"${card.game || ''}"`,
        `"${card.mana_cost || ''}"`,
        `"${card.cmc || ''}"`,
        `"${card.card_type || ''}"`,
        `"${Array.isArray(card.colors) ? card.colors.join(', ') : card.colors || ''}"`,
        `"${(card.oracle_text || '').replace(/"/g, '""')}"`,
        `"${card.power || ''}"`,
        `"${card.toughness || ''}"`,
        `"${card.market_price || ''}"`,
        `"${card.quantity || 1}"`,
        `"${card.created_at ? new Date(card.created_at).toLocaleDateString() : ''}"`,
      ].join(',')
    ),
  ];

  const csvContent = csvRows.join('\n');
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');

  if (link.download !== undefined) {
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `${collectionName || 'collection'}_cards.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
}
