/**
 * DDR-style accuracy: each arrow is scored as Perfect (100%), Good (70%), or Miss (0%).
 * Letter grade is derived from the mean accuracy across all arrows.
 */

export type LetterGrade = 'S' | 'A' | 'B' | 'C' | 'D' | 'F'

export const JUDGMENT_PERCENT = {
  perfect: 100,
  good: 70,
  miss: 0,
} as const

/** Result payload when navigating from GamePage → EndOfGamePage */
export type GameEndState = {
  score: number
  perfect: number
  good: number
  miss: number
}

/**
 * Mean accuracy in percent (0–100), or `null` if there are no judgments.
 */
export function judgmentAveragePercent(perfect: number, good: number, miss: number): number | null {
  const p = Math.max(0, Math.floor(perfect))
  const g = Math.max(0, Math.floor(good))
  const m = Math.max(0, Math.floor(miss))
  const total = p + g + m
  if (total === 0) return null
  const sum = p * JUDGMENT_PERCENT.perfect + g * JUDGMENT_PERCENT.good + m * JUDGMENT_PERCENT.miss
  return sum / total
}

/**
 * Map mean accuracy to a letter grade (DDR-style tiers).
 */
export function letterGradeFromAccuracy(percent: number): LetterGrade {
  if (percent >= 95) return 'S'
  if (percent >= 90) return 'A'
  if (percent >= 80) return 'B'
  if (percent >= 70) return 'C'
  if (percent >= 60) return 'D'
  return 'F'
}

export function letterGradeFromJudgments(perfect: number, good: number, miss: number): LetterGrade {
  const avg = judgmentAveragePercent(perfect, good, miss)
  if (avg === null) return 'F'
  return letterGradeFromAccuracy(avg)
}
