const subscales = {
  perspectiveTaking: [1, 2, 3, 4, 5, 6, 7],
  empathicConcern: [8, 9, 10, 11, 12, 13, 14],
  personalDistress: [15, 16, 17, 18, 19, 20, 21],
  fantasy: [22, 23, 24, 25, 26, 27, 28],
} as const;

const reverseItems = new Set([2, 4, 6, 10, 13, 17, 20, 24, 26, 28]);

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

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

function subscaleAverage(answers: string[], items: readonly number[]) {
  return average(items.map((item) => scoreItem(answers, item)));
}

export function calculateEmpathyResults(answers: string[]) {
  return {
    perspectiveTaking: subscaleAverage(answers, subscales.perspectiveTaking),
    empathicConcern: subscaleAverage(answers, subscales.empathicConcern),
    personalDistress: subscaleAverage(answers, subscales.personalDistress),
    fantasy: subscaleAverage(answers, subscales.fantasy),
  };
}
