const dimensions = {
  machiavellianism: [1, 2, 3, 4, 5, 6, 7, 8, 9],
  narcissism: [10, 11, 12, 13, 14, 15, 16, 17, 18],
  psychopathy: [19, 20, 21, 22, 23, 24, 25, 26, 27],
} as const;

const reverseItems = new Set([4, 8, 11, 15, 17, 20, 25]);

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 dimensionAverage(answers: string[], items: readonly number[]) {
  return average(items.map((item) => scoreItem(answers, item)));
}

export function calculateDarkTriadResults(answers: string[]) {
  return {
    machiavellianism: dimensionAverage(answers, dimensions.machiavellianism),
    narcissism: dimensionAverage(answers, dimensions.narcissism),
    psychopathy: dimensionAverage(answers, dimensions.psychopathy),
  };
}
