import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

// Function to format CSV data to match our schema
export function formatCsvData(data: Array<any>): any[] {
  return data.map(item => ({
    jumpNumber: parseInt(item['Jump Number'], 10) || 0,
    jumpType: item['Type of Jump'] || '',
    dropzone: item['DZ'] || '',
    altitude: item['Altitude'] || '',
    aircraft: item['Aircraft'] || '',
    equipment: item['Equipment'] || '',
    notes: item['Notes'] || ''
  }));
}

// Generate CSV template
export function generateCsvTemplate() {
  return 'Jump Number,Type of Jump,DZ,Altitude,Aircraft,Equipment,Notes\n';
}

// Function to download a file
export function downloadFile(content: string, fileName: string, contentType: string) {
  const a = document.createElement("a");
  const file = new Blob([content], { type: contentType });
  a.href = URL.createObjectURL(file);
  a.download = fileName;
  a.click();
  URL.revokeObjectURL(a.href);
}

// Format statistics
export function formatAltitude(altitude: string): string {
  // Clean the altitude string and ensure it has proper format
  if (!altitude) return '';
  
  const numericValue = parseInt(altitude.replace(/[^\d]/g, ''), 10);
  if (isNaN(numericValue)) return altitude;
  
  // Format with comma for thousands
  return numericValue.toLocaleString() + ' ft';
}

// Extract chart data from jumps
export function extractChartData(jumps: any[], property: string) {
  const counts: Record<string, number> = {};
  
  jumps.forEach(jump => {
    const value = jump[property];
    if (value) {
      if (counts[value]) {
        counts[value]++;
      } else {
        counts[value] = 1;
      }
    }
  });
  
  return {
    labels: Object.keys(counts),
    data: Object.values(counts)
  };
}
