const reverseItems = new Set([1, 3, 5, 6]);
const perseveranceItems = [2, 4, 7, 8];
const consistencyItems = [1, 3, 5, 6];

function scoreItem(answers: string[], item: number) {
  const raw = Number(answers[item - 1] || 1);
  return reverseItems.has(item) ? 6 - raw : raw;
}

function average(values: number[]) {
  return values.reduce((sum, value) => sum + value, 0) / values.length;
}

export function calculateGritResults(answers: string[]) {
  const itemScores = Array.from({ length: 8 }, (_, index) =>
    scoreItem(answers, index + 1),
  );
  const totalAverage = average(itemScores);
  const perseveranceAverage = average(
    perseveranceItems.map((item) => scoreItem(answers, item)),
  );
  const consistencyAverage = average(
    consistencyItems.map((item) => scoreItem(answers, item)),
  );

  let level: 'low' | 'moderate' | 'high' = 'moderate';
  if (totalAverage < 3) {
    level = 'low';
  } else if (totalAverage >= 4) {
    level = 'high';
  }

  return {
    itemScores,
    totalAverage,
    perseveranceAverage,
    consistencyAverage,
    level,
  };
}
