const PARETO_80_PERCENT = 80

export interface ScrapDatum {
  step_id: string
  step_number: number
  station_name: string
  scrap_total: number
}

export interface ParetoRow {
  name: string
  step_id: string
  scrap: number
  cumulative_pct: number
  isVitalFew: boolean
}

export function computeParetoData(data: ScrapDatum[]): ParetoRow[] {
  const sorted = [...data]
    .filter((d) => d.scrap_total > 0)
    .sort((a, b) => b.scrap_total - a.scrap_total)
  if (sorted.length === 0) return []

  const total = sorted.reduce((acc, d) => acc + d.scrap_total, 0)
  let cumulativeBefore = 0
  return sorted.map((d) => {
    const beforePct = (cumulativeBefore / total) * 100
    cumulativeBefore += d.scrap_total
    const cumulative_pct = Number(((cumulativeBefore / total) * 100).toFixed(1))
    return {
      name: `#${d.step_number} ${d.station_name}`,
      step_id: d.step_id,
      scrap: d.scrap_total,
      cumulative_pct,
      isVitalFew: beforePct < PARETO_80_PERCENT,
    }
  })
}
