import type { Location, Address, SupportLevel } from '@/types/api';
import { SUPPORT_LEVEL_COLORS } from '@/types/api';

export const NO_LEVEL_COLOR = '#3498db';

export function getMarkerColor(level: SupportLevel | null): string {
  if (!level) return NO_LEVEL_COLOR;
  return SUPPORT_LEVEL_COLORS[level] ?? NO_LEVEL_COLOR;
}

// Location with addresses for map display
export interface GroupableLocation extends Location {
  addresses: Address[];
}

// Get the dominant support level from all addresses in a location
function getDominantSupportLevel(addresses: Address[]): SupportLevel | null {
  if (addresses.length === 0) return null;

  const levelCounts: Record<string, number> = {};
  for (const addr of addresses) {
    const level = addr.supportLevel || 'NONE';
    levelCounts[level] = (levelCounts[level] || 0) + 1;
  }

  let dominant: SupportLevel | null = null;
  let maxCount = 0;
  for (const [level, count] of Object.entries(levelCounts)) {
    if (count > maxCount) {
      maxCount = count;
      dominant = level === 'NONE' ? null : (level as SupportLevel);
    }
  }

  return dominant;
}

export interface LocationGroup {
  latitude: number;
  longitude: number;
  location: GroupableLocation;
  isMultiUnit: boolean;
  dominantLevel: SupportLevel | null;
}

export function groupLocations(locations: GroupableLocation[]): LocationGroup[] {
  return locations
    .filter(loc => loc.latitude != null && loc.longitude != null)
    .map(loc => {
      const lat = typeof loc.latitude === 'string' ? parseFloat(loc.latitude) : loc.latitude!;
      const lng = typeof loc.longitude === 'string' ? parseFloat(loc.longitude) : loc.longitude!;

      // Defensive: ensure addresses array exists
      const addresses = Array.isArray(loc.addresses) ? loc.addresses : [];

      return {
        latitude: lat,
        longitude: lng,
        location: loc,
        isMultiUnit: addresses.length > 1,
        dominantLevel: getDominantSupportLevel(addresses),
      };
    });
}
