/**
 * School Year Events
 * Specific school year milestones and experiences
 * Ported from Python events/school_year/school_year_events.py
 *
 * Events:
 * - summerReading: Summer reading assignment for school
 * - classRankReveal: Finding out class rank
 * - seniorSurvey: Yearbook survey/superlatives
 * - finalExamWeek: Stress of finals week
 * - summerJobSearch: Looking for summer employment
 * - promInvite: Being asked to prom or asking someone
 * - dormRoommate: Meeting college roommate for first time
 * - seniorSkipDay: Participating in senior skip day
 * - collegeHomesick: Homesickness in first semester
 * - changeMyMajor: Doubting chosen major
 */

import { Player } from '../../models/index.js';
import {
  createMessageEvent,
  createQuestionEvent,
  createAnswerOption,
  EventResult,
} from '../base.js';

/**
 * Summer reading assignment for school
 * Triggers during June-August for students ages 10-17
 */
export function summerReading(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option?: string }
): EventResult {
  const fname = 'summerReading';

  // Get current month from player.date (format: MM-DD)
  const currentMonth = parseInt(player.date.split('-')[0], 10);

  // Trigger during June-August (months 6-8) for students ages 10-17
  const check =
    !player.askedQuestions.has(fname) &&
    player.c.occupation === 'student' &&
    player.c.ageYears >= 10 &&
    player.c.ageYears <= 17 &&
    currentMonth >= 6 &&
    currentMonth <= 8 &&
    Math.random() < 0.1;

  const message = 'You have to read a book for summer homework. When do you do it?';
  const answerOptions = [
    createAnswerOption('Right away in June', '', 15),
    createAnswerOption('Throughout the summer'),
    createAnswerOption('Last week of summer', '', 30),
    createAnswerOption("Don't read it"),
  ];

  if (type !== 'answer' && check) {
    return createQuestionEvent(fname, message, player, check, { answerOptions });
  }

  if (type === 'answer') {
    const c = player.c;
    const choice = response?.option ?? '';

    if (choice === 'Right away in June') {
      c.energy = Math.max(0, (c.energy ?? 100) - 15);
      player.messageQueue.push(
        'You finish your summer reading right away. Now you can enjoy the rest of your summer worry-free!'
      );
      c.happiness = (c.happiness ?? 50) - 10;
      c.intelligence = Math.min(100, (c.intelligence ?? 50) + 5);
    } else if (choice === 'Throughout the summer') {
      player.messageQueue.push(
        'You pace yourself and read a little bit throughout the summer. Smart approach!'
      );
      c.intelligence = Math.min(100, (c.intelligence ?? 50) + 3);
    } else if (choice === 'Last week of summer') {
      c.energy = Math.max(0, (c.energy ?? 100) - 30);
      player.messageQueue.push(
        'You scramble to finish the book in the last week of summer. The stress was intense, but you got it done!'
      );
      c.happiness = (c.happiness ?? 50) - 20;
      c.intelligence = Math.min(100, (c.intelligence ?? 50) + 2);
    } else if (choice === "Don't read it") {
      player.messageQueue.push(
        "You decide not to read the book. The first day back to school is going to be rough..."
      );
      c.happiness = (c.happiness ?? 50) - 10;
    }

    return createMessageEvent(fname, player.messageQueue[player.messageQueue.length - 1], player, true);
  }

  return null;
}

/**
 * Finding out class rank
 * Triggers for 11th-12th graders (ages 16-17)
 */
export function classRankReveal(player: Player): EventResult {
  const fname = 'classRankReveal';
  const c = player.c;

  const check =
    !player.events.has(fname) &&
    c.occupation === 'student' &&
    c.ageYears >= 16 &&
    c.ageYears <= 17 &&
    (c.education === '11th' || c.education === '12th') &&
    Math.random() < 0.05;

  if (!check) {
    return null;
  }

  // Determine message based on intelligence level (using as proxy for GPA)
  const intelligence = c.intelligence ?? 50;
  let message: string;

  if (intelligence >= 70) {
    message = "You're in the top 10% of your class! You feel proud of your academic achievement.";
    c.happiness = Math.min(100, (c.happiness ?? 50) + 15);
  } else if (intelligence >= 40) {
    message = "You're in the middle of your class. Not bad! You're doing just fine academically.";
    c.happiness = Math.min(100, (c.happiness ?? 50) + 5);
  } else {
    message = 'Your class rank is lower than you hoped. Time to study harder?';
    c.happiness = (c.happiness ?? 50) - 5;
  }

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

/**
 * Yearbook survey/superlatives
 * Triggers for seniors (ages 17-18, 12th grade)
 */
export function seniorSurvey(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option?: string }
): EventResult {
  const fname = 'seniorSurvey';
  const c = player.c;

  const check =
    !player.askedQuestions.has(fname) &&
    c.occupation === 'student' &&
    c.ageYears >= 17 &&
    c.ageYears <= 18 &&
    c.education === '12th' &&
    Math.random() < 0.1;

  const message = 'The yearbook committee wants to give you a superlative. Which fits best?';
  const answerOptions = [
    createAnswerOption('Most Likely to Succeed'),
    createAnswerOption('Class Clown'),
    createAnswerOption('Most Athletic'),
    createAnswerOption('Biggest Bookworm'),
    createAnswerOption('Most Social'),
  ];

  if (type !== 'answer' && check) {
    return createQuestionEvent(fname, message, player, check, { answerOptions });
  }

  if (type === 'answer') {
    const choice = response?.option ?? '';
    player.messageQueue.push(
      `'${choice}' - that sounds about right! You're excited to see it in the yearbook.`
    );
    c.happiness = Math.min(100, (c.happiness ?? 50) + 10);

    // Small stat boost based on choice
    if (choice === 'Most Likely to Succeed') {
      c.intelligence = Math.min(100, (c.intelligence ?? 50) + 3);
    } else if (choice === 'Class Clown') {
      c.social = Math.min(100, (c.social ?? 50) + 5);
    } else if (choice === 'Most Athletic') {
      c.energy = Math.min(100, (c.energy ?? 100) + 5);
    } else if (choice === 'Biggest Bookworm') {
      c.intelligence = Math.min(100, (c.intelligence ?? 50) + 5);
    } else if (choice === 'Most Social') {
      c.social = Math.min(100, (c.social ?? 50) + 8);
    }

    return createMessageEvent(fname, player.messageQueue[player.messageQueue.length - 1], player, true);
  }

  return null;
}

/**
 * Stress of finals week
 * Triggers in May-June or December for students ages 14-22
 */
export function finalExamWeek(player: Player): EventResult {
  const fname = 'finalExamWeek';
  const c = player.c;

  // Get current month from player.date (format: MM-DD)
  const currentMonth = parseInt(player.date.split('-')[0], 10);

  // Trigger in May-June (end of spring semester) or December (end of fall semester)
  const check =
    !player.events.has(fname) &&
    c.occupation === 'student' &&
    c.ageYears >= 14 &&
    c.ageYears <= 22 &&
    (currentMonth === 5 || currentMonth === 6 || currentMonth === 12) &&
    Math.random() < 0.15;

  if (!check) {
    return null;
  }

  const message = "It's finals week. You're surviving on coffee and stress. Almost there!";
  c.energy = Math.max(0, (c.energy ?? 100) - 20);
  c.happiness = (c.happiness ?? 50) - 10;

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

/**
 * Looking for summer employment
 * Triggers in April-May for students ages 15-21
 */
export function summerJobSearch(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option?: string }
): EventResult {
  const fname = 'summerJobSearch';
  const c = player.c;

  // Get current month from player.date (format: MM-DD)
  const currentMonth = parseInt(player.date.split('-')[0], 10);

  // Trigger in April-May for students ages 15-21
  const check =
    !player.askedQuestions.has(fname) &&
    c.occupation === 'student' &&
    c.ageYears >= 15 &&
    c.ageYears <= 21 &&
    currentMonth >= 4 &&
    currentMonth <= 5 &&
    Math.random() < 0.1;

  const message = 'Summer is coming. Do you want to get a summer job?';
  const answerOptions = [
    createAnswerOption('Yes, find a job'),
    createAnswerOption('Volunteer instead'),
    createAnswerOption('Focus on summer activities'),
    createAnswerOption('Take it easy'),
  ];

  if (type !== 'answer' && check) {
    return createQuestionEvent(fname, message, player, check, { answerOptions });
  }

  if (type === 'answer') {
    const choice = response?.option ?? '';

    if (choice === 'Yes, find a job') {
      player.messageQueue.push(
        "You decide to look for a summer job. Time to start earning some money!"
      );
      c.happiness = Math.min(100, (c.happiness ?? 50) + 5);
    } else if (choice === 'Volunteer instead') {
      player.messageQueue.push(
        'You sign up to volunteer over the summer. It feels good to give back to the community!'
      );
      c.social = Math.min(100, (c.social ?? 50) + 20);
      c.happiness = Math.min(100, (c.happiness ?? 50) + 10);
    } else if (choice === 'Focus on summer activities') {
      player.messageQueue.push(
        'You focus on summer camps and activities instead. Should be a fun summer!'
      );
      c.happiness = Math.min(100, (c.happiness ?? 50) + 15);
    } else if (choice === 'Take it easy') {
      player.messageQueue.push(
        'You decide to take it easy this summer. Rest and relaxation sounds perfect!'
      );
      c.energy = Math.min(100, (c.energy ?? 100) + 20);
    }

    return createMessageEvent(fname, player.messageQueue[player.messageQueue.length - 1], player, true);
  }

  return null;
}

/**
 * Being asked to prom or asking someone
 * Triggers in March-April for 11th-12th graders (ages 16-18)
 */
export function promInvite(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option?: string }
): EventResult {
  const fname = 'promInvite';
  const c = player.c;

  // Get current month from player.date (format: MM-DD)
  const currentMonth = parseInt(player.date.split('-')[0], 10);

  // Trigger in March-April for 11th-12th graders (ages 16-18)
  const check =
    !player.askedQuestions.has(fname) &&
    c.occupation === 'student' &&
    c.ageYears >= 16 &&
    c.ageYears <= 18 &&
    (c.education === '11th' || c.education === '12th') &&
    currentMonth >= 3 &&
    currentMonth <= 4 &&
    Math.random() < 0.15;

  const message = "Prom is coming up! What's your plan?";

  // Check if player has a partner
  const hasPartner = c.partner !== undefined && c.partner !== '';

  let answerOptions;
  if (hasPartner) {
    answerOptions = [
      createAnswerOption('Go with partner', '', 0, 0, 200),
      createAnswerOption('Skip it'),
    ];
  } else {
    answerOptions = [
      createAnswerOption('Ask someone you like', '', 0, 5),
      createAnswerOption('Go with friends', '', 0, 0, 150),
      createAnswerOption('Skip it'),
    ];
  }

  if (type !== 'answer' && check) {
    return createQuestionEvent(fname, message, player, check, { answerOptions });
  }

  if (type === 'answer') {
    const choice = response?.option ?? '';

    if (choice.includes('Go with partner')) {
      c.money = Math.max(0, (c.money ?? 0) - 200);
      if ((c.money ?? 0) < 0) {
        c.stress = (c.stress ?? 0) + 10;
      }
      player.messageQueue.push(
        "You and your partner have an amazing time at prom! It's a night you'll never forget."
      );
      c.happiness = Math.min(100, (c.happiness ?? 50) + 20);
    } else if (choice.includes('Ask someone you like')) {
      c.diamonds = Math.max(0, (c.diamonds ?? 0) - 5);
      // Random chance they say yes (70%)
      if (Math.random() < 0.7) {
        player.messageQueue.push("They said yes! You're so excited for prom night.");
        c.happiness = Math.min(100, (c.happiness ?? 50) + 25);
        c.social = Math.min(100, (c.social ?? 50) + 10);
      } else {
        player.messageQueue.push(
          "They politely decline. It stings, but you'll get through it."
        );
        c.happiness = (c.happiness ?? 50) - 15;
      }
    } else if (choice.includes('Go with friends')) {
      c.money = Math.max(0, (c.money ?? 0) - 150);
      if ((c.money ?? 0) < 0) {
        c.stress = (c.stress ?? 0) + 10;
      }
      player.messageQueue.push(
        'You and your friends have a blast at prom! Who needs a date anyway?'
      );
      c.happiness = Math.min(100, (c.happiness ?? 50) + 18);
      c.social = Math.min(100, (c.social ?? 50) + 15);
    } else if (choice.includes('Skip it')) {
      player.messageQueue.push(
        "You decide to skip prom. Maybe you'll regret it someday, or maybe not."
      );
      c.happiness = (c.happiness ?? 50) - 5;
    }

    return createMessageEvent(fname, player.messageQueue[player.messageQueue.length - 1], player, true);
  }

  return null;
}

/**
 * Meeting college roommate for first time
 * Triggers in late August for college year 1, age 18
 */
export function dormRoommate(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option?: string }
): EventResult {
  const fname = 'dormRoommate';
  const c = player.c;

  // Get current month from player.date (format: MM-DD)
  const currentMonth = parseInt(player.date.split('-')[0], 10);

  // Trigger in late August for college year 1, age 18
  const check =
    !player.askedQuestions.has(fname) &&
    c.occupation === 'student' &&
    c.ageYears === 18 &&
    c.education === 'college yr 1' &&
    currentMonth === 8 &&
    Math.random() < 0.2;

  const message =
    'You meet your randomly assigned college roommate for the first time. First impressions?';
  const answerOptions = [
    createAnswerOption('They seem cool!'),
    createAnswerOption('Seems awkward...'),
    createAnswerOption('Request a room change', '', 0, 0, 100),
  ];

  if (type !== 'answer' && check) {
    return createQuestionEvent(fname, message, player, check, { answerOptions });
  }

  if (type === 'answer') {
    const choice = response?.option ?? '';

    if (choice === 'They seem cool!') {
      player.messageQueue.push(
        "Your roommate seems really cool! You think you're going to get along great."
      );
      c.happiness = Math.min(100, (c.happiness ?? 50) + 10);
      c.social = Math.min(100, (c.social ?? 50) + 15);
    } else if (choice === 'Seems awkward...') {
      player.messageQueue.push(
        "The first meeting is a bit awkward, but maybe it'll get better with time."
      );
      c.happiness = (c.happiness ?? 50) - 5;
      c.social = Math.min(100, (c.social ?? 50) + 5);
    } else if (choice === 'Request a room change') {
      c.money = Math.max(0, (c.money ?? 0) - 100);
      if ((c.money ?? 0) < 0) {
        c.stress = (c.stress ?? 0) + 10;
      }
      player.messageQueue.push(
        "You request a room change. The housing office says they'll see what they can do."
      );
      c.happiness = (c.happiness ?? 50) - 10;
    }

    return createMessageEvent(fname, player.messageQueue[player.messageQueue.length - 1], player, true);
  }

  return null;
}

/**
 * Participating in senior skip day
 * Triggers in spring (March-May) for seniors (ages 17-18, 12th grade)
 */
export function seniorSkipDay(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option?: string }
): EventResult {
  const fname = 'seniorSkipDay';
  const c = player.c;

  // Get current month from player.date (format: MM-DD)
  const currentMonth = parseInt(player.date.split('-')[0], 10);

  // Trigger in spring (March-May) for seniors
  const check =
    !player.askedQuestions.has(fname) &&
    c.occupation === 'student' &&
    c.ageYears >= 17 &&
    c.ageYears <= 18 &&
    c.education === '12th' &&
    currentMonth >= 3 &&
    currentMonth <= 5 &&
    Math.random() < 0.1;

  const message = "It's the unofficial senior skip day. Do you skip?";
  const answerOptions = [
    createAnswerOption('Yes, skip with friends!'),
    createAnswerOption('No, perfect attendance'),
    createAnswerOption('Half day compromise'),
  ];

  if (type !== 'answer' && check) {
    return createQuestionEvent(fname, message, player, check, { answerOptions });
  }

  if (type === 'answer') {
    const choice = response?.option ?? '';

    if (choice === 'Yes, skip with friends!') {
      player.messageQueue.push(
        'You skip school with your friends and have an amazing day! Senior year memories!'
      );
      c.happiness = Math.min(100, (c.happiness ?? 50) + 15);
      c.social = Math.min(100, (c.social ?? 50) + 20);
    } else if (choice === 'No, perfect attendance') {
      player.messageQueue.push(
        "You go to school while most of your class is absent. The teachers appreciate your dedication, but you feel a bit lame."
      );
      c.happiness = (c.happiness ?? 50) - 10;
      c.social = (c.social ?? 50) - 15;
      c.intelligence = Math.min(100, (c.intelligence ?? 50) + 5);
    } else if (choice === 'Half day compromise') {
      player.messageQueue.push(
        'You attend morning classes then leave early. A reasonable compromise!'
      );
      c.happiness = Math.min(100, (c.happiness ?? 50) + 5);
      c.social = Math.min(100, (c.social ?? 50) + 10);
    }

    return createMessageEvent(fname, player.messageQueue[player.messageQueue.length - 1], player, true);
  }

  return null;
}

/**
 * Homesickness in first semester
 * Triggers in September-October for college year 1, age 18
 */
export function collegeHomesick(player: Player): EventResult {
  const fname = 'collegeHomesick';
  const c = player.c;

  // Get current month from player.date (format: MM-DD)
  const currentMonth = parseInt(player.date.split('-')[0], 10);

  // Trigger in September-October for college year 1, age 18
  const check =
    !player.events.has(fname) &&
    c.occupation === 'student' &&
    c.ageYears === 18 &&
    c.education === 'college yr 1' &&
    currentMonth >= 9 &&
    currentMonth <= 10 &&
    Math.random() < 0.15;

  if (!check) {
    return null;
  }

  const message =
    "You're homesick. You miss your family, your room, even your old school. You call home and feel a little better.";
  c.happiness = (c.happiness ?? 50) - 10;

  // Slight affinity boost with family members
  const family = player.r.filter((p) => (p.familyLevel ?? 0) > 0 && p.status === 'alive');
  if (family.length > 0) {
    const familyMember = family[Math.floor(Math.random() * family.length)];
    familyMember.affinity = Math.min(100, (familyMember.affinity ?? 50) + 5);
  }

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

/**
 * Doubting chosen major
 * Triggers during college years 1-2 (ages 18-20)
 */
export function changeMyMajor(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option?: string }
): EventResult {
  const fname = 'changeMyMajor';
  const c = player.c;

  // Trigger during college years 1-2 (ages 18-20)
  const check =
    !player.askedQuestions.has(fname) &&
    c.occupation === 'student' &&
    c.ageYears >= 18 &&
    c.ageYears <= 20 &&
    (c.education === 'college yr 1' || c.education === 'college yr 2') &&
    c.major !== undefined &&
    c.major !== '' &&
    Math.random() < 0.08;

  const message = "You're not sure about your major anymore. Change it?";
  const answerOptions = [
    createAnswerOption('Yes, switch majors'),
    createAnswerOption('No, stick with it'),
    createAnswerOption('Add a double major', '', 40, 10),
    createAnswerOption('Take time to decide'),
  ];

  if (type !== 'answer' && check) {
    return createQuestionEvent(fname, message, player, check, { answerOptions });
  }

  if (type === 'answer') {
    const choice = response?.option ?? '';

    if (choice === 'Yes, switch majors') {
      player.messageQueue.push(
        "You decide to switch your major. It might add time to your degree, but you feel much better about your choice!"
      );
      c.happiness = Math.min(100, (c.happiness ?? 50) + 15);
      // Mark that they're reconsidering major
      (c as unknown as Record<string, boolean>).changingMajor = true;
    } else if (choice === 'No, stick with it') {
      player.messageQueue.push(
        'You decide to stick with your current major. Sometimes you just have to push through the doubt.'
      );
      c.happiness = (c.happiness ?? 50) - 5;
    } else if (choice === 'Add a double major') {
      c.energy = Math.max(0, (c.energy ?? 100) - 40);
      c.diamonds = Math.max(0, (c.diamonds ?? 0) - 10);
      if ((c.diamonds ?? 0) < 0) {
        c.stress = (c.stress ?? 0) + 10;
      }
      player.messageQueue.push(
        "You add a double major! It's going to be a lot of work, but you're excited about the challenge."
      );
      c.happiness = Math.min(100, (c.happiness ?? 50) + 10);
      (c as unknown as Record<string, boolean>).doubleMajor = true;
    } else if (choice === 'Take time to decide') {
      player.messageQueue.push(
        'You give yourself time to think it over. No need to rush such an important decision.'
      );
      c.happiness = Math.min(100, (c.happiness ?? 50) + 5);
    }

    return createMessageEvent(fname, player.messageQueue[player.messageQueue.length - 1], player, true);
  }

  return null;
}

/**
 * All school year event functions
 */
export const schoolYearEvents = {
  summerReading,
  classRankReveal,
  seniorSurvey,
  finalExamWeek,
  summerJobSearch,
  promInvite,
  dormRoommate,
  seniorSkipDay,
  collegeHomesick,
  changeMyMajor,
};
