const reverseItems = new Set([3, 4, 5, 7, 8, 9, 12, 16, 17]);

export function calculateNeedForCognitionResults(answers: string[]) {
  const itemScores = answers.slice(0, 18).map((answer, index) => {
    const raw = Number(answer || 1);
    const item = index + 1;
    return reverseItems.has(item) ? 6 - raw : raw;
  });

  const total = itemScores.reduce((sum, score) => sum + score, 0);
  const average = total / itemScores.length;

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

  const thinkingItems = [1, 2, 6, 10, 11, 18].map(
    (item) => itemScores[item - 1],
  );
  const challengeItems = [3, 4, 5, 7, 8, 9, 12, 13, 14, 15, 16, 17].map(
    (item) => itemScores[item - 1],
  );

  return {
    itemScores,
    total,
    average,
    thinkingAverage:
      thinkingItems.reduce((sum, score) => sum + score, 0) /
      thinkingItems.length,
    challengeAverage:
      challengeItems.reduce((sum, score) => sum + score, 0) /
      challengeItems.length,
    level,
  };
}
