const avoidanceItems = [1, 2, 3, 4, 5, 6];
const anxietyItems = [7, 8, 9];
const reverseAvoidanceItems = new Set([1, 2, 3, 4]);

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

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

export function calculateAttachmentResults(answers: string[]) {
  const avoidance = average(avoidanceItems.map((item) => scoreItem(answers, item)));
  const anxiety = average(anxietyItems.map((item) => Number(answers[item - 1] || 1)));

  let pattern:
    | 'secure'
    | 'preoccupied'
    | 'dismissive'
    | 'fearful' = 'secure';

  const highAvoidance = avoidance >= 4;
  const highAnxiety = anxiety >= 4;

  if (highAvoidance && highAnxiety) {
    pattern = 'fearful';
  } else if (highAvoidance) {
    pattern = 'dismissive';
  } else if (highAnxiety) {
    pattern = 'preoccupied';
  }

  return {
    avoidance,
    anxiety,
    pattern,
  };
}
