/**
 * ExportButton.jsx
 * Downloads ranked results as a CSV file.
 */
import { Download } from 'lucide-react';

function toCSV(candidates, jobTitle) {
  const headers = [
    'Rank', 'Name', 'File', 'Status', 'Final Score', 'Match %',
    'Skills Score', 'Experience Score', 'Education Score', 'Certs Score',
    'Projects Score', 'Bonus Score', 'TF-IDF Similarity %',
    'Matched Skills', 'Missing Skills', 'Experience Years',
    'Education', 'Certifications', 'Location', 'Languages'
  ];

  const rows = candidates.map(c => [
    c.rank,
    `"${c.name}"`,
    `"${c.filename}"`,
    c.status,
    c.final_score,
    c.match_percent,
    c.skills_score,
    c.experience_score,
    c.education_score,
    c.certs_score,
    c.projects_score,
    c.bonus_score,
    c.tfidf_similarity,
    `"${c.matched_skills.join('; ')}"`,
    `"${c.missing_skills.join('; ')}"`,
    c.experience_years,
    `"${c.education_degree} - ${c.education_field}"`,
    `"${c.certifications.join('; ')}"`,
    `"${c.location}"`,
    `"${c.languages.join('; ')}"`,
  ]);

  return [headers.join(','), ...rows.map(r => r.join(','))].join('\n');
}

export default function ExportButton({ candidates, jobTitle }) {
  const handleExport = () => {
    const csv = toCSV(candidates, jobTitle);
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `HireIQ_${jobTitle.replace(/\s+/g, '_')}_results.csv`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  return (
    <button
      id="export-csv-btn"
      onClick={handleExport}
      className="btn-secondary flex items-center gap-2 text-sm"
    >
      <Download size={16} />
      Export CSV
    </button>
  );
}
