/**
 * CSV Export Utilities
 * Converts annotation data into a semicolon-delimited CSV file with a BOM so it
 * opens cleanly in spreadsheet tools that expect Central European defaults.
 */
export const exportToCSV = (data, t, lang, fileName, orderedTraitIds, schema) => {
  let rawItems = Array.isArray(data) ? data : (data.annotations || [data]);

  const traitLabels = new Map();
  const schemaTraitIdsByAtlas = new Map();

  (schema || []).forEach(section => {
    const atlasId = section.atlas_id || section.atlasId || null;
    const sectionTraitIds = section.znaky?.map(z => {
      traitLabels.set(z.id, lang === 'cs' ? z.label_cs : z.label_en);
      return z.id;
    }) || [];

    if (atlasId) {
      const existing = schemaTraitIdsByAtlas.get(atlasId) || [];
      schemaTraitIdsByAtlas.set(atlasId, [...existing, ...sectionTraitIds]);
    }
  });

  const getCheckerName = (item) => {
    if (!item || typeof item !== 'object') return "";
    return item.checkerName || item.checker_name || item.checkedBy || item.checked_by || "";
  };

  const isMixedExport = rawItems.length > 1;

  const allTraitsInParsedData = new Set();
  const exportedAtlasIds = new Set();

  rawItems.forEach(item => {
    if (item?.atlasId) exportedAtlasIds.add(item.atlasId);

    const vals = typeof item.values === 'string' ? JSON.parse(item.values) : (item.values || {});
    Object.keys(vals).forEach(tid => allTraitsInParsedData.add(tid));
  });

  const schemaTraitIdsForExport = exportedAtlasIds.size === 0
    ? (orderedTraitIds || [])
    : Array.from(exportedAtlasIds).flatMap(atlasId => schemaTraitIdsByAtlas.get(atlasId) || []);

  let finalTraitIds = Array.from(new Set([...(schemaTraitIdsForExport || []), ...allTraitsInParsedData]));

  if (!isMixedExport && finalTraitIds.length === 0) {
    finalTraitIds = orderedTraitIds || [];
  }

  const headers = [
    t('headerAnnotationId'),
    t('headerModelId'),
    t('headerAnnotator'),
    t('headerFileHash'),
    t('headerSaveDate'),
    t('headerAtlas'),
    t('headerCheckedBy'),
    ...finalTraitIds.map(tid => {
      return traitLabels.get(tid) || tid;
    })
  ];

  const rows = rawItems.map((item) => {
    const values = typeof item.values === 'string' ? JSON.parse(item.values) : (item.values || {});
    const dateLocale = lang === 'cs' ? 'cs-CZ' : 'en-US';

    const row = [
      item.annotationId || item.id || "",
      item.modelLabel || item.modelId || "N/A",
      item.annotator || item.annotatorName || t('valueNotSpecified'),
      item.fileHash || "N/A",
      item.lastUpdated ? new Date(item.lastUpdated).toLocaleString(dateLocale) : "N/A",
      (lang === 'cs' ? item.atlasNameCs : item.atlasNameEn) || item.atlasName || item.atlasId || "N/A",
      getCheckerName(item),
      
      ...finalTraitIds.map(tid => values[tid] || "")
    ];

    return row.map(v => `"${String(v).replace(/"/g, '""')}"`).join(";");
  });

  const csvContent = "\uFEFF" + headers.join(";") + "\n" + rows.join("\n");
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.setAttribute("href", url);
  link.setAttribute("download", fileName || 'export.csv');
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};