export type StackCounts<T extends string> = ReadonlyMap<T, number>

export function createStackCounts<T extends string>(items: readonly T[]): StackCounts<T> {
  const counts = new Map<T, number>()
  items.forEach((item) => counts.set(item, (counts.get(item) ?? 0) + 1))
  return counts
}

export function stackCount<T extends string>(counts: StackCounts<T>, id: T) {
  return counts.get(id) ?? 0
}

export function summarizeStackCounts<T extends string, TChoice extends { id: T; name: string }>(
  counts: StackCounts<T>,
  catalog: readonly TChoice[],
  emptyLabel = '',
) {
  const summary = Array.from(counts.entries())
    .map(([id, count]) => {
      const label = catalog.find((choice) => choice.id === id)?.name ?? id
      return count > 1 ? `${label} x${count}` : label
    })
    .join(', ')
  return summary || emptyLabel
}
