import {pickTagEmoji} from '@crumbs/core/emojis'
import type {Crumb, CrumbPlace} from '@crumbs/core/schemas'

export const SF_DEFAULT_COORDS = {
  latitude: 37.7749,
  longitude: -122.4194,
}

// route params arrive as strings; only a pair of finite numbers is a
// usable coordinate (Number('') is 0, so blank params must not pass)
export const parseCoordParams = (
  lat: string | undefined,
  lng: string | undefined,
): {latitude: number; longitude: number} | null => {
  if (!lat || !lng) return null
  const latitude = Number(lat)
  const longitude = Number(lng)
  return Number.isFinite(latitude) && Number.isFinite(longitude)
    ? {latitude, longitude}
    : null
}

// "450 m" under a km, "1.2 km" above
export const formatDistanceKm = (km: number): string =>
  km < 1
    ? `${Math.round((km * 1000) / 10) * 10} m`
    : `${km.toFixed(1)} km`

export type LocatedCrumb = Crumb & {
  place: CrumbPlace & {latitude: number; longitude: number}
}

export const isLocated = <T extends Crumb>(
  c: T,
): c is T & LocatedCrumb =>
  c.place?.latitude != null && c.place?.longitude != null

export const crumbCoords = (c: LocatedCrumb) => ({
  latitude: c.place.latitude,
  longitude: c.place.longitude,
})

export const toMarker = (
  c: LocatedCrumb,
  tintColor: string,
  cycleIndex = 0,
) => ({
  id: c.id,
  coordinates: crumbCoords(c),
  title: c.name,
  monogram:
    c.tags.length > 0
      ? c.tags[cycleIndex % c.tags.length]!.emoji
      : pickTagEmoji(c.place.category ?? ''),
  tintColor,
})
