// === Utility functions ===

// Speaker colors - 10 distinct high-contrast colors for dark theme
export const SPEAKER_COLORS = [
  '#3B82F6', // blue
  '#10B981', // emerald
  '#F59E0B', // amber
  '#EF4444', // red
  '#8B5CF6', // violet
  '#EC4899', // pink
  '#06B6D4', // cyan
  '#F97316', // orange
  '#84CC16', // lime
  '#6366F1', // indigo
];

/**
 * Get color for a speaker by name (consistent hashing)
 */
export function getSpeakerColor(speaker: string): string {
  // Extract speaker index if format is SPEAKER_XX or SPK_XX
  const match = speaker.match(/(?:SPEAKER_|SPK_)(\d+)/);
  if (match) {
    const idx = parseInt(match[1], 10);
    return SPEAKER_COLORS[idx % SPEAKER_COLORS.length];
  }
  // Fallback: hash the string
  let hash = 0;
  for (let i = 0; i < speaker.length; i++) {
    hash = ((hash << 5) - hash) + speaker.charCodeAt(i);
    hash |= 0;
  }
  return SPEAKER_COLORS[Math.abs(hash) % SPEAKER_COLORS.length];
}

/**
 * Format seconds to HH:MM:SS.mmm
 */
export function formatTime(seconds: number, showMs = false): string {
  const hrs = Math.floor(seconds / 3600);
  const mins = Math.floor((seconds % 3600) / 60);
  const secs = Math.floor(seconds % 60);
  const ms = Math.floor((seconds % 1) * 1000);
  
  let result = '';
  if (hrs > 0) {
    result = `${hrs}:${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  } else {
    result = `${mins}:${secs.toString().padStart(2, '0')}`;
  }
  
  if (showMs) {
    result += `.${ms.toString().padStart(3, '0')}`;
  }
  
  return result;
}

/**
 * Format duration to human readable (e.g., "1h 23m" or "5m 30s")
 */
export function formatDuration(seconds: number): string {
  if (seconds < 60) {
    return `${seconds.toFixed(1)}s`;
  }
  const hrs = Math.floor(seconds / 3600);
  const mins = Math.floor((seconds % 3600) / 60);
  const secs = Math.floor(seconds % 60);
  
  if (hrs > 0) {
    return `${hrs}h ${mins}m`;
  }
  return `${mins}m ${secs}s`;
}

/**
 * Format percentage
 */
export function formatPercent(value: number): string {
  return `${(value * 100).toFixed(1)}%`;
}

/**
 * Format date to locale string
 */
export function formatDate(dateStr: string | null): string {
  if (!dateStr) return 'Unknown';
  const date = new Date(dateStr);
  return date.toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
}

/**
 * Clamp value between min and max
 */
export function clamp(value: number, min: number, max: number): number {
  return Math.min(Math.max(value, min), max);
}

/**
 * Tailwind class merge helper (simple version)
 */
export function cn(...classes: (string | undefined | null | false)[]): string {
  return classes.filter(Boolean).join(' ');
}
