const reverseItems = new Set([2, 3, 5, 6, 7, 8, 10, 11, 12]);

export function calculateSelfControlResults(answers: string[]) {
  const itemScores = answers.slice(0, 13).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 impulseItems = [1, 2, 5, 10, 11].map((item) => itemScores[item - 1]);
  const executionItems = [3, 4, 6, 7, 8, 9, 12, 13].map(
    (item) => itemScores[item - 1],
  );

  return {
    itemScores,
    total,
    average,
    impulseAverage:
      impulseItems.reduce((sum, score) => sum + score, 0) / impulseItems.length,
    executionAverage:
      executionItems.reduce((sum, score) => sum + score, 0) /
      executionItems.length,
    level,
  };
}
