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

// view filter shared by the map screen and the place sheet so a pin's
// count always matches the list you see when you tap it

export type MapFilter =
  | {kind: 'all'}
  | {kind: 'tag'; tag: string}
  | {kind: 'status'; status: 'planned' | 'done'}

export const matchesFilter = (
  crumb: Crumb,
  filter: MapFilter,
): boolean => {
  if (filter.kind === 'all') return true
  if (filter.kind === 'tag')
    return crumb.tags.some((t) => t.name === filter.tag)
  return crumb.status === filter.status
}

export const encodeFilter = (filter: MapFilter): string => {
  if (filter.kind === 'tag') return `tag:${filter.tag}`
  if (filter.kind === 'status') return `status:${filter.status}`
  return 'all'
}

export const decodeFilter = (raw?: string): MapFilter => {
  if (!raw) return {kind: 'all'}
  const [kind, ...rest] = raw.split(':')
  const value = rest.join(':')
  if (kind === 'tag' && value) return {kind: 'tag', tag: value}
  if (kind === 'status' && (value === 'planned' || value === 'done'))
    return {kind: 'status', status: value}
  return {kind: 'all'}
}

// a synthetic id distinguishes group pins from single-crumb pins in
// onMarkerClick without a parallel lookup table

const PLACE_MARKER_PREFIX = 'place:'

export const placeMarkerId = (placeId: string): string =>
  `${PLACE_MARKER_PREFIX}${placeId}`

export const parsePlaceMarkerId = (
  markerId?: string,
): string | null =>
  markerId?.startsWith(PLACE_MARKER_PREFIX)
    ? markerId.slice(PLACE_MARKER_PREFIX.length)
    : null

// one pin per place; a multi-crumb place shows its count, a single-crumb
// place its category emoji (per-crumb tags aren't in the aggregate)
export const placeMarker = (
  point: MapPlacePoint,
  tintColor: string,
) => ({
  id: placeMarkerId(point.placeId),
  coordinates: {
    latitude: point.latitude,
    longitude: point.longitude,
  },
  title: point.name,
  monogram:
    point.crumbCount > 1
      ? String(point.crumbCount)
      : pickTagEmoji(point.category ?? ''),
  tintColor,
})
