/**
 * Family Life Transitions Events
 * Events related to life transitions and changes in family dynamics
 *
 * Events:
 * - agingParent: Parent needs more help with daily tasks (ages 35-60)
 * - extendedFamily: Extended family member upset about being ignored (all ages)
 * - collegeMissHome: College freshman missing home (college yr 1)
 * - adultMissFriends: Working adult missing old friends (working adults)
 */

import { Player } from '../../models/Player.js';
import { Person } from '../../models/Person.js';
import {
  createMessageEvent,
  createQuestionEvent,
  createAnswerOption,
  checkProbability,
  type EventResult,
} from '../base.js';
import { getRelationship, getPerson } from './activities.js';

// ============================================================================
// Life Transition Events
// ============================================================================

/**
 * Aging Parent - Parent needs more help with daily tasks
 * Ages 35-60, requires at least one living parent
 */
export function agingParent(
  player: Player,
  _type: 'message' | 'question' = 'message'
): EventResult {
  const fname = 'agingParent';
  const ageYears = player.c.ageYears;

  // Check if player has living parents
  const mother = getRelationship(player, 'mother');
  const father = getRelationship(player, 'father');
  const hasParent =
    (mother !== null && mother.status !== 'dead') ||
    (father !== null && father.status !== 'dead');

  const check =
    !player.askedQuestions.has(fname) &&
    ageYears >= 35 &&
    ageYears <= 60 &&
    hasParent &&
    checkProbability(5000);

  if (check) {
    player.askedQuestions.add(fname);
  }

  return createQuestionEvent(
    fname,
    'Your parent is getting older and needs help. How do you support them?',
    player,
    check,
    {
      answerOptions: [
        createAnswerOption('Visit more often', '', 10, 0, 0),
        createAnswerOption('Hire outside help', '', 0, 0, 500),
        createAnswerOption('Move them in with you', '', 20, 0, 200),
        createAnswerOption('Encourage siblings to help', '', 0, 5, 0),
      ],
    }
  );
}

/**
 * Process aging parent answer
 */
export function agingParentAnswer(
  player: Player,
  response: { option: string }
): void {
  const mother = getRelationship(player, 'mother');
  const father = getRelationship(player, 'father');
  const parent =
    (mother !== null && mother.status !== 'dead' ? mother : null) ??
    (father !== null && father.status !== 'dead' ? father : null);

  if (response.option === 'Visit more often') {
    player.c.energy = Math.max(0, player.c.energy - 10);
    player.c.happiness = Math.min(100, (player.c.happiness ?? 50) + 5);

    // Increase parent affinity
    if (parent) {
      parent.affinity = Math.min(100, (parent.affinity ?? 50) + 10);
    }

    player.messageQueue.push(
      "You start visiting your parent more often. It's tiring but you're glad to spend time together."
    );
  } else if (response.option === 'Hire outside help') {
    player.c.money = (player.c.money ?? 0) - 500;
    player.c.happiness = Math.min(100, (player.c.happiness ?? 50) + 10);

    player.messageQueue.push(
      "You hire a home care aide for your parent. It's expensive but gives everyone peace of mind."
    );
  } else if (response.option === 'Move them in with you') {
    player.c.energy = Math.max(0, player.c.energy - 20);
    player.c.money = (player.c.money ?? 0) - 200;
    player.c.happiness = Math.max(0, (player.c.happiness ?? 50) - 10);

    // Increase parent affinity significantly
    if (parent) {
      parent.affinity = Math.min(100, (parent.affinity ?? 50) + 20);
    }

    player.messageQueue.push(
      "Your parent moves in with you. It's a big adjustment for everyone, but you're there for each other."
    );
  } else {
    player.c.diamonds = Math.max(0, (player.c.diamonds ?? 0) - 5);
    player.c.happiness = Math.min(100, (player.c.happiness ?? 50) + 15);

    player.messageQueue.push(
      'You coordinate with your siblings to share the caregiving. Teamwork makes it easier for everyone.'
    );
  }
}

/**
 * Extended Family - Extended family member upset about being ignored
 * Triggers when familyLevel 2 relatives have affinity < -50
 */
export function extendedFamily(
  player: Player,
  _type: 'message' | 'question' = 'message'
): EventResult {
  const fname = 'extendedFamily';

  // Find extended family members (familyLevel 2) with low affinity
  const found: Person[] = [];
  for (const r of player.r ?? []) {
    if (r.familyLevel === 2) {
      if ((r.affinity ?? 50) < -50) {
        found.push(r);
      }
    }
  }

  // 1 in 5 chance when there are upset extended family members
  if (found.length === 0 || !checkProbability(5)) {
    return null;
  }

  // Pick a random upset family member
  const relative = found[Math.floor(Math.random() * found.length)];

  // Store relative ID for answer processing
  (player as unknown as { _temp_relative_id: string })._temp_relative_id =
    relative.id;

  const message = `${relative.firstname} is upset you've been ignoring them, you should have a chat with them!`;

  return createQuestionEvent(fname, message, player, true, {
    answerOptions: [
      createAnswerOption(
        "I'll set some time aside to talk to them",
        relative.id
      ),
      createAnswerOption("I'm ignoring them for a reason!", relative.id),
    ],
    characters: [relative],
  });
}

/**
 * Process extended family answer
 */
export function extendedFamilyAnswer(
  player: Player,
  response: { option: string; data?: string }
): void {
  const relativeId =
    response.data ??
    (player as unknown as { _temp_relative_id?: string })._temp_relative_id;
  const relative = getPerson(player, relativeId ?? null);

  if (relative) {
    if (response.option === "I'll set some time aside to talk to them") {
      relative.affinity = Math.min(100, (relative.affinity ?? 50) + 20);
      player.c.energy = Math.max(0, player.c.energy - 20);
      player.messageQueue.push(
        `You had a nice chat with ${relative.firstname}. Things are better between you now.`
      );
    } else {
      relative.affinity = Math.max(-100, (relative.affinity ?? 50) - 10);
      player.messageQueue.push(
        `You continue to ignore ${relative.firstname}. They seem even more upset.`
      );
    }
  }

  // Clean up temp variable
  delete (player as unknown as { _temp_relative_id?: string })._temp_relative_id;
}

/**
 * College Miss Home - College freshman missing home
 * Triggers for college yr 1 students with low social stat
 */
export function collegeMissHome(
  player: Player,
  _type: 'message' | 'question' = 'message'
): EventResult {
  const fname = 'collegeMissHome';

  const check =
    !player.events.has(fname) &&
    player.c.education === 'college yr 1' &&
    (player.c.social ?? 50) < 50 &&
    Math.random() < 0.01;

  const message =
    'You miss home, and your family misses you. You should call them.';

  if (check) {
    player.events.add(fname);
    player.c.happiness = Math.max(0, (player.c.happiness ?? 50) - 10);

    // Increase affinity with family members when player acknowledges missing them
    const mother = getRelationship(player, 'mother');
    const father = getRelationship(player, 'father');

    if (mother) {
      mother.affinity = Math.min(100, (mother.affinity ?? 50) + 5);
    }
    if (father) {
      father.affinity = Math.min(100, (father.affinity ?? 50) + 5);
    }
  }

  return createMessageEvent(fname, message, player, check);
}

/**
 * Adult Miss Friends - Working adult missing old friends
 * Triggers for working adults, reminds them to reconnect with friends
 */
export function adultMissFriends(
  player: Player,
  _type: 'message' | 'question' = 'message'
): EventResult {
  const fname = 'adultMissFriends';

  // Check for working adults with friends who have high affinity but low familiarity
  const friends = (player.r ?? []).filter(
    (person: Person) =>
      (person.affinity ?? 0) > 50 && (person.familiarity ?? 0) < 50
  );

  const check =
    !player.events.has(fname) &&
    player.c.occupation === 'work' &&
    friends.length > 0 &&
    Math.random() < 0.01;

  if (!check) {
    return null;
  }

  player.events.add(fname);

  // Pick a random friend to reference
  const friend = friends[Math.floor(Math.random() * friends.length)];

  const message = `You realize you haven't talked to ${friend.firstname} in a while. Life has been so busy with work. Maybe you should reach out.`;

  player.c.happiness = Math.max(0, (player.c.happiness ?? 50) - 5);
  player.c.social = Math.max(0, (player.c.social ?? 50) - 5);

  return createMessageEvent(fname, message, player, true, {
    characters: [friend],
  });
}
