import type { GovernmentLevel, Representative } from '@/types/api';

export function mapRepSetToLevel(repSetName: string | null): GovernmentLevel | null {
  if (!repSetName) return null;
  const lower = repSetName.toLowerCase();
  if (lower.includes('house of commons') || lower.includes('senate')) return 'FEDERAL';
  if (lower.includes('legislative') || lower.includes('national assembly') || lower.includes('provincial')) return 'PROVINCIAL';
  if (lower.includes('council') || lower.includes('city') || lower.includes('municipal') || lower.includes('mayor')) return 'MUNICIPAL';
  if (lower.includes('school') || lower.includes('board') || lower.includes('trustee')) return 'SCHOOL_BOARD';
  if (lower.includes('mp') || lower.includes('federal')) return 'FEDERAL';
  if (lower.includes('mpp') || lower.includes('mla') || lower.includes('mna')) return 'PROVINCIAL';
  return null;
}

export function groupRepsByLevel(reps: Representative[]): Record<string, Representative[]> {
  const groups: Record<string, Representative[]> = {};
  const levelOrder: GovernmentLevel[] = ['FEDERAL', 'PROVINCIAL', 'MUNICIPAL', 'SCHOOL_BOARD'];

  for (const rep of reps) {
    const level = mapRepSetToLevel(rep.representativeSetName) || 'OTHER';
    if (!groups[level]) groups[level] = [];
    groups[level].push(rep);
  }

  // Sort by level order
  const sorted: Record<string, Representative[]> = {};
  for (const level of levelOrder) {
    if (groups[level]) sorted[level] = groups[level];
  }
  if (groups['OTHER']) sorted['OTHER'] = groups['OTHER'];
  return sorted;
}

/**
 * Maps Ant Design tag color names to actual hex colors for use in inline styles.
 */
export const GOVERNMENT_LEVEL_DISPLAY_COLORS: Record<string, string> = {
  FEDERAL: '#3b82f6',
  PROVINCIAL: '#a855f7',
  MUNICIPAL: '#22c55e',
  SCHOOL_BOARD: '#f97316',
  OTHER: '#94a3b8',
};
