/**
 * Adolescent Social Events
 * Romance, friendships, and social development (ages 10-18)
 *
 * Events:
 * - firstCrush: First romantic crush
 * - firstKiss: First kiss
 * - dating_choice: Choosing someone to ask out
 * - romanticDate: Going on a romantic date
 * - newFriend: Making a new friend at school
 */

import {
  createQuestionEvent,
  createAnswerOption,
  checkProbability,
  type EventResult,
} from '../base.js';
import type { Player } from '../../models/Player.js';
import {
  updateRelationship,
  addFriend,
  getRandomClassmate,
} from '../../services/character/character_manager.js';

/**
 * First romantic crush (ages 10-12)
 */
export function firstCrush(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option: string; data?: string }
): EventResult {
  const fname = 'firstCrush';
  const ageYears = player.character.ageYears;

  const check =
    !player.askedQuestions.has(fname) &&
    ageYears >= 10 &&
    ageYears < 13 &&
    checkProbability(100);

  const message = 'You have a crush on someone at school, who is it?';

  if (type !== 'answer' && check) {
    // Generate crush options from relationships
    const relationships = player.relationships ?? [];
    const answerOptions: string[] = [];

    // Add friends and classmates as options
    const potentialCrushes = relationships.slice(0, 5);
    for (const person of potentialCrushes) {
      const rel = (person.relationships ?? [])[0] ?? 'Classmate';
      answerOptions.push(
        `Your ${rel}, ${person.firstname}, a ${person.ageYears} year old ${person.sex}`
      );
    }

    if (answerOptions.length === 0) {
      answerOptions.push('A classmate you admire');
    }

    return createQuestionEvent(fname, message, player, check, { answerOptions });
  } else if (type === 'answer' && response) {
    player.askedQuestions.add(fname);
    player.character.firstCrush = response.data;

    // Set sexual orientation based on crush
    const relationships = player.relationships ?? [];
    const crush = relationships.find((p) => p.id === response.data);
    if (crush) {
      if (crush.sex === player.character.sex) {
        player.character.sexualOrientation = 'homosexual';
      } else {
        player.character.sexualOrientation = 'heterosexual';
      }
    }

    // Update the crush's relationship to the player
    if (crush && player.relationships) {
      const personIndex = player.relationships.findIndex((p) => p.id === crush.id);
      const crushPerson = player.relationships[personIndex];
      if (personIndex >= 0 && crushPerson?.relationships) {
        crushPerson.relationships.push('crush');
      }
    }
  }

  return null;
}

/**
 * First kiss (ages 13+)
 */
export function firstKiss(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option: string }
): EventResult {
  const fname = 'firstKiss';
  const ageYears = player.character.ageYears;

  const check =
    !player.askedQuestions.has(fname) &&
    ageYears >= 13 &&
    checkProbability(1000);

  const message = 'Someone leans in for a kiss, how do you want to respond?';
  const answerOptions = [
    createAnswerOption('Lean in'),
    createAnswerOption("Slowly back away while their eyes are closed"),
    createAnswerOption('Let them down easy', '', 0, 5),
  ];

  if (type !== 'answer') {
    return createQuestionEvent(fname, message, player, check, {
      answerOptions: answerOptions.map((opt) => opt.option),
    });
  } else if (type === 'answer' && response) {
    player.askedQuestions.add(fname);

    if (response.option === 'Lean in') {
      player.messageQueue.push(
        "Your heart starts to beat fast and you can feel them inching closer. You squeeze your eyes shut and your lips touch. That wasn't so bad!"
      );
    } else if (response.option === "Slowly back away while their eyes are closed") {
      player.messageQueue.push(
        'Their eyes flutter open and you quickly lean to the left and dodge their puckering lips coming closer to you. Phew! Seems like you dodged a bullet. You leave them standing there feeling dejected.'
      );
    } else if (response.option === 'Let them down easy') {
      player.messageQueue.push(
        'You tell them you appreciate their gesture but you do not feel the same way and wish them best of luck in their endeavors. They respond positively and the two of you carry on as if nothing happened.'
      );
    }
  }

  return null;
}

/**
 * Choosing someone to ask out (ages 13+, not in relationship)
 */
export function dating_choice(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option: string; data?: string }
): EventResult {
  const fname = 'dating_choice';
  const ageYears = player.character.ageYears;

  // Find potential partners with high affinity
  const relationships = player.relationships ?? [];
  const potentialDates = relationships.filter(
    (p) =>
      (p.affinity ?? 0) > 50 &&
      Math.abs(ageYears - (p.ageYears ?? 0)) <= 5 &&
      // Content safety: romantic partners are adults only (18+). Never offer an
      // under-18 NPC as a dating option, even if within the age window.
      (p.ageYears ?? 0) >= 18 &&
      (p.familyLevel ?? 0) === 0 &&
      p.sex !== player.character.sex
  );

  const check =
    !player.askedQuestions.has(fname) &&
    !player.character.partner &&
    potentialDates.length > 0 &&
    // Content safety: romantic relationships are adults only (18+).
    ageYears >= 18 &&
    checkProbability(100);

  const message = 'Who would you like to ask out?';

  if (type !== 'answer' && check) {
    const answerOptions: string[] = [];
    for (const person of potentialDates.slice(0, 5)) {
      const rel = (person.relationships ?? [])[0] ?? 'Friend';
      answerOptions.push(`Your ${rel}, ${person.firstname} ${person.lastname}`);
    }

    if (answerOptions.length === 0) {
      player.askedQuestions.add(fname);
      player.messageQueue.push('No one likes you enough to date you!');
      return null;
    }

    return createQuestionEvent(fname, message, player, check, { answerOptions });
  } else if (type === 'answer' && response) {
    player.askedQuestions.add(fname);

    // Find the person from relationships
    const person = relationships.find((p) =>
      response.option.includes(p.firstname ?? '')
    );

    if (person) {
      // Success chance based on affinity
      const affinityRatio = (person.affinity ?? 0) / 100;
      if (Math.random() < affinityRatio) {
        player.character.partner = person.id;
        // Update the person's relationship to partner
        if (person.relationships) {
          person.relationships.push('partner');
        }
        player.lifecycleQueue.push({ type: 'dating' });
        player.messageQueue.push(`${person.firstname} said yes!`);
      } else {
        player.messageQueue.push('They said no!');
      }
    }
  }

  return null;
}

/**
 * Going on a romantic date (ages 16-18)
 */
export function romanticDate(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option: string }
): EventResult {
  const fname = 'romanticDate';
  const ageYears = player.character.ageYears;

  const check =
    !player.askedQuestions.has(fname) &&
    ageYears >= 16 &&
    ageYears <= 18 &&
    checkProbability(100);

  const message = "Love is in the air! It's your turn to pick date night. What would you like to do?";
  const answerOptions = [
    createAnswerOption('Have a candlelit dinner at a fancy restaurant', '', 0, 0, 50),
    createAnswerOption('Go for a scenic walk in the park', '', 10),
    createAnswerOption('Watch a movie under the stars at a drive-in theater', '', 5, 0, 30),
  ];

  if (type !== 'answer') {
    return createQuestionEvent(fname, message, player, check, {
      answerOptions: answerOptions.map((opt) => opt.option),
    });
  } else if (type === 'answer' && response) {
    player.askedQuestions.add(fname);

    if (response.option === 'Have a candlelit dinner at a fancy restaurant') {
      player.messageQueue.push(
        'You had a magical candlelit dinner at a fancy restaurant. It was a night to remember!'
      );
    } else if (response.option === 'Go for a scenic walk in the park') {
      player.messageQueue.push(
        "You enjoyed a long walk in the park, hand in hand, as the sun set. It was beautiful (but you're both a little tired!)"
      );
    } else if (response.option === 'Watch a movie under the stars at a drive-in theater') {
      player.messageQueue.push(
        'You cuddled up in the car, watching a movie under the starry sky at the drive-in theater. It was a perfect date night!'
      );
    }
  }

  return null;
}

/**
 * Making a new friend at school (ages 4-21, at school)
 */
export function newFriend(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option: string }
): EventResult {
  const fname = 'newFriend';
  const ageYears = player.character.ageYears;

  const check =
    player.character.location === 'school' &&
    player.character.occupation === 'student' &&
    ageYears >= 4 &&
    ageYears < 22 &&
    checkProbability(1000);

  // Get or generate a classmate
  const classmate = getRandomClassmate(player);
  const classmateFirstname = classmate?.firstname ?? 'Alex';
  const classmateLastname = classmate?.lastname ?? 'Johnson';

  const message = `You have met ${classmateFirstname} ${classmateLastname} at school, would you like to be friends?`;
  const answerOptions = ['Yes', 'No'];

  if (type !== 'answer') {
    return createQuestionEvent(fname, message, player, check, { answerOptions });
  } else if (type === 'answer' && response) {
    if (response.option === 'Yes') {
      // If we had a classmate, upgrade them to friend; otherwise create a new friend
      if (classmate) {
        classmate.relationships.push('friend');
        classmate.affinity = Math.min(100, (classmate.affinity ?? 50) + 20);
      } else {
        // Create a new friend with similar age
        addFriend(player, player.character.sex === 'Male' ? 'Female' : 'Male', 'similar');
      }
      player.character.social = (player.character.social ?? 0) + 10;
      player.lifecycleQueue.push({ type: 'friend_made' });
      player.messageQueue.push('You have made a new friend!');
    } else {
      player.character.social = (player.character.social ?? 0) - 10;
      player.messageQueue.push('You have not made a new friend.');
    }
  }

  return null;
}
