/**
 * Birthday Events
 * Milestone birthdays (16, 18, 21, 30, 40, 50) with multi-stage events
 * All birthdays get gifts scaled by affinity; teen/adult birthdays have party choices
 */

import { Player } from '../../models/Player';
import {
  createMessageEvent,
  createQuestionEvent,
  createAnswerOption,
  createDilemma,
  checkProbability,
  modifyStat,
  type DilemmaClass,
  type EventResult,
} from '../base';
import { deductEnergy } from '../../utils/statUtils.js';

// ──────────────────────────────────────────────
// Sweet 16 (multi-stage)
// ──────────────────────────────────────────────

interface BirthdayDilemma extends DilemmaClass {
  partyChoice?: string;
}

export function sweet16(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option?: string },
  dilemma?: BirthdayDilemma
): EventResult {
  const fname = 'sweet16';
  const check = !player.askedQuestions.has(fname) &&
    player.character.ageYears === 16 &&
    player.character.ageDays > 0 &&
    player.character.ageDays % 365 === 0;

  const answerOptions = [
    createAnswerOption('Throw a huge party with all your friends', '', 20, 0, 200),
    createAnswerOption('Small gathering with close friends and family', '', 10, 0, 75),
    createAnswerOption('Ask for driving lessons instead of a party', '', 5, 0, 150),
    createAnswerOption('Just a nice family dinner', '', 5, 0, 50),
  ];

  if (check && type !== 'answer') {
    player.askedQuestions.add(fname);
    const dilemmaObj = createDilemma(fname, answerOptions) as BirthdayDilemma;
    player.activeDilemmas.push(dilemmaObj);
    return createQuestionEvent(
      fname,
      "It's your 16th birthday! Sweet sixteen! This is a big milestone. How do you want to celebrate?",
      player,
      true,
      { answerOptions }
    );
  }

  if (type === 'answer' && player.activeDilemmas.length > 0) {
    const currentDilemma = player.activeDilemmas[player.activeDilemmas.length - 1] as BirthdayDilemma;
    currentDilemma.answer = answerOptions.find(opt => opt.option === response?.option) ?? null;
    currentDilemma.partyChoice = currentDilemma.answer?.option;
    deductEnergy(player.c, currentDilemma.answer?.energyCost ?? 0);
    player.money -= currentDilemma.answer?.moneyCost ?? 0;
  }

  if (dilemma && dilemma.step === 2 && dilemma.answer) {
    const c = player.c;
    let message = '';

    if (dilemma.answer.option === answerOptions[0].option) {
      message = "Your sweet 16 party was legendary! The music was perfect, the cake was amazing, and you got some incredible gifts. Your friends are still talking about it.";
      c.happiness = modifyStat(c.happiness, 30);
      c.social = modifyStat(c.social, 20);
      player.diamonds += 10;
    } else if (dilemma.answer.option === answerOptions[1].option) {
      message = "Your birthday gathering was intimate and meaningful. Your best friends made you feel so special, and the gifts were thoughtful. A perfect evening.";
      c.happiness = modifyStat(c.happiness, 25);
      c.social = modifyStat(c.social, 10);
      player.diamonds += 5;
    } else if (dilemma.answer.option === answerOptions[2].option) {
      message = "Instead of a party, you started driving lessons! Sitting behind the wheel for the first time was terrifying and exciting. Freedom is just around the corner.";
      c.happiness = modifyStat(c.happiness, 20);
      player.diamonds += 3;
    } else {
      message = "A quiet birthday dinner with family turned out to be really nice. Your parents gave you a heartfelt card and your favorite meal. Sometimes simple is best.";
      c.happiness = modifyStat(c.happiness, 15);
      player.diamonds += 2;
    }

    const idx = player.activeDilemmas.indexOf(dilemma);
    if (idx > -1) player.activeDilemmas.splice(idx, 1);
    return createMessageEvent(fname, message, player, true);
  }

  return null;
}

// ──────────────────────────────────────────────
// 18th Birthday (multi-stage)
// ──────────────────────────────────────────────

export function eighteenthBirthday(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option?: string },
  dilemma?: BirthdayDilemma
): EventResult {
  const fname = 'eighteenthBirthday';
  const check = !player.askedQuestions.has(fname) &&
    player.character.ageYears === 18 &&
    player.character.ageDays > 0 &&
    player.character.ageDays % 365 === 0;

  const answerOptions = [
    createAnswerOption('Register to vote and celebrate becoming an adult', '', 5, 0, 0),
    createAnswerOption('Throw an epic party', '', 20, 0, 300),
    createAnswerOption('Get your first tattoo', '', 10, 0, 100),
    createAnswerOption('Road trip with friends', '', 15, 0, 200),
  ];

  if (check && type !== 'answer') {
    player.askedQuestions.add(fname);
    const dilemmaObj = createDilemma(fname, answerOptions) as BirthdayDilemma;
    player.activeDilemmas.push(dilemmaObj);
    return createQuestionEvent(
      fname,
      "You're officially 18 - a legal adult! The world just opened up. How do you mark this milestone?",
      player,
      true,
      { answerOptions }
    );
  }

  if (type === 'answer' && player.activeDilemmas.length > 0) {
    const currentDilemma = player.activeDilemmas[player.activeDilemmas.length - 1] as BirthdayDilemma;
    currentDilemma.answer = answerOptions.find(opt => opt.option === response?.option) ?? null;
    deductEnergy(player.c, currentDilemma.answer?.energyCost ?? 0);
    player.money -= currentDilemma.answer?.moneyCost ?? 0;
  }

  if (dilemma && dilemma.step === 2 && dilemma.answer) {
    const c = player.c;
    let message = '';

    if (dilemma.answer.option === answerOptions[0].option) {
      message = "You registered to vote on your 18th birthday. It felt empowering to officially be part of democracy. Your parents were proud and took you out for a special dinner.";
      c.happiness = modifyStat(c.happiness, 20);
      c.social = modifyStat(c.social, 5);
      player.diamonds += 8;
    } else if (dilemma.answer.option === answerOptions[1].option) {
      message = "Your 18th birthday party was one for the ages! Dancing, laughing, and celebrating with everyone you care about. You feel like anything is possible now.";
      c.happiness = modifyStat(c.happiness, 30);
      c.social = modifyStat(c.social, 15);
      player.diamonds += 10;
    } else if (dilemma.answer.option === answerOptions[2].option) {
      message = "You walked into the tattoo parlor with butterflies and walked out with ink and confidence. Your parents had mixed reactions, but it's your body now!";
      c.happiness = modifyStat(c.happiness, 15);
      c.creativity = modifyStat(c.creativity, 5);
      player.diamonds += 5;
    } else {
      message = "You and your closest friends hit the road for an unforgettable birthday adventure. New places, new experiences, and memories that will last forever.";
      c.happiness = modifyStat(c.happiness, 25);
      c.social = modifyStat(c.social, 10);
      player.diamonds += 8;
    }

    const idx = player.activeDilemmas.indexOf(dilemma);
    if (idx > -1) player.activeDilemmas.splice(idx, 1);
    return createMessageEvent(fname, message, player, true);
  }

  return null;
}

// ──────────────────────────────────────────────
// 21st Birthday (multi-stage)
// ──────────────────────────────────────────────

export function twentyFirstBirthday(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option?: string },
  dilemma?: BirthdayDilemma
): EventResult {
  const fname = 'twentyFirstBirthday';
  const check = !player.askedQuestions.has(fname) &&
    player.character.ageYears === 21 &&
    player.character.ageDays > 0 &&
    player.character.ageDays % 365 === 0;

  const answerOptions = [
    createAnswerOption('Hit the bars with friends', '', 25, 0, 150),
    createAnswerOption('Classy dinner and champagne toast', '', 10, 0, 200),
    createAnswerOption('Vegas trip!', '', 30, 0, 500),
    createAnswerOption('Chill celebration at home', '', 5, 0, 50),
  ];

  if (check && type !== 'answer') {
    player.askedQuestions.add(fname);
    const dilemmaObj = createDilemma(fname, answerOptions) as BirthdayDilemma;
    player.activeDilemmas.push(dilemmaObj);
    return createQuestionEvent(
      fname,
      "Happy 21st! You can now legally do everything. This is THE birthday to remember. What's the plan?",
      player,
      true,
      { answerOptions }
    );
  }

  if (type === 'answer' && player.activeDilemmas.length > 0) {
    const currentDilemma = player.activeDilemmas[player.activeDilemmas.length - 1] as BirthdayDilemma;
    currentDilemma.answer = answerOptions.find(opt => opt.option === response?.option) ?? null;
    deductEnergy(player.c, currentDilemma.answer?.energyCost ?? 0);
    player.money -= currentDilemma.answer?.moneyCost ?? 0;
  }

  if (dilemma && dilemma.step === 2 && dilemma.answer) {
    const c = player.c;
    let message = '';

    if (dilemma.answer.option === answerOptions[0].option) {
      message = "You and your friends painted the town! The bartender gave you your first legal drink on the house. The night was a blur of laughter and celebration.";
      c.happiness = modifyStat(c.happiness, 25);
      c.social = modifyStat(c.social, 15);
      c.health = modifyStat(c.health, -5);
      player.diamonds += 10;
    } else if (dilemma.answer.option === answerOptions[1].option) {
      message = "A sophisticated dinner at a nice restaurant with your closest people. The champagne was perfect and you felt truly adult for the first time.";
      c.happiness = modifyStat(c.happiness, 20);
      c.social = modifyStat(c.social, 10);
      player.diamonds += 8;
    } else if (dilemma.answer.option === answerOptions[2].option) {
      const luckyRoll = Math.random();
      if (luckyRoll > 0.6) {
        message = "Vegas was WILD! You actually won $200 at the blackjack table. The shows, the food, the energy - best birthday ever!";
        c.happiness = modifyStat(c.happiness, 35);
        player.money += 200;
        player.diamonds += 15;
      } else {
        message = "Vegas was fun but expensive! You lost some money at the tables, but the experience was priceless. What happens in Vegas...";
        c.happiness = modifyStat(c.happiness, 20);
        c.health = modifyStat(c.health, -5);
        player.diamonds += 10;
      }
    } else {
      message = "A cozy birthday at home with cake and close friends. Nothing fancy, but it was exactly what you wanted. Sometimes the best celebrations are the simplest.";
      c.happiness = modifyStat(c.happiness, 15);
      player.diamonds += 5;
    }

    const idx = player.activeDilemmas.indexOf(dilemma);
    if (idx > -1) player.activeDilemmas.splice(idx, 1);
    return createMessageEvent(fname, message, player, true);
  }

  return null;
}

// ──────────────────────────────────────────────
// Decade Birthdays (30, 40, 50)
// ──────────────────────────────────────────────

export function decadeBirthday(player: Player, _type: 'message' | 'question' = 'message'): EventResult {
  const age = player.character.ageYears;
  const isDecade = age === 30 || age === 40 || age === 50;
  const fname = `decadeBirthday_${age}`;
  const check = !player.askedQuestions.has(fname) &&
    isDecade &&
    player.character.ageDays > 0 &&
    player.character.ageDays % 365 === 0;

  if (!check) return null;

  player.askedQuestions.add(fname);

  let question: string;
  let options: ReturnType<typeof createAnswerOption>[];

  if (age === 30) {
    question = "The big 3-0! You're officially not a kid anymore (for real this time). How do you feel about entering a new decade?";
    options = [
      createAnswerOption('Throw a \"dirty thirty\" bash', '', 15, 0, 250),
      createAnswerOption('Reflect and set goals for the decade', '', 5, 0, 0),
      createAnswerOption('Treat yourself to something you always wanted', '', 0, 0, 500),
      createAnswerOption('Crisis mode - am I old now?', '', 10, 0, 100),
    ];
  } else if (age === 40) {
    question = "You hit 40! Some call it 'over the hill,' but you're just getting started. How do you celebrate?";
    options = [
      createAnswerOption('Buy yourself something extravagant', '', 0, 0, 1000),
      createAnswerOption('Throw a big party with a \"40 and fabulous\" theme', '', 15, 0, 400),
      createAnswerOption('Take a solo trip for self-discovery', '', 10, 0, 600),
      createAnswerOption('Quiet dinner and pretend it is not happening', '', 5, 0, 100),
    ];
  } else {
    question = "Half a century! 50 years on this planet. You've seen things, done things, and learned a lot. How do you mark the occasion?";
    options = [
      createAnswerOption('Bucket list trip', '', 10, 0, 2000),
      createAnswerOption('Surprise party thrown by family', '', 5, 0, 0),
      createAnswerOption('Donate to charity in celebration', '', 0, 0, 500),
      createAnswerOption('Renew your outlook on life', '', 5, 0, 0),
    ];
  }

  return createQuestionEvent(fname, question, player, true, { answerOptions: options });
}

// ──────────────────────────────────────────────
// Birthday Gift (triggered every birthday, gift scaled by relationships)
// ──────────────────────────────────────────────

export function birthdayGifts(player: Player, _type: 'message' | 'question' = 'message'): EventResult {
  const age = player.character.ageYears;
  const fname = `birthdayGifts_${age}`;
  const check = !player.events.has(fname) &&
    age >= 1 &&
    player.character.ageDays > 0 &&
    player.character.ageDays % 365 === 0;

  if (!check) return null;

  player.events.add(fname);
  player.lifecycleQueue.push({ type: 'birthday', data: { age } });

  // Calculate gifts based on relationships and their affinity
  let totalGiftMoney = 0;
  let totalGiftDiamonds = 0;
  let giftGivers = 0;

  for (const person of player.r) {
    if (person.status !== 'alive') continue;
    const affinity = person.affinity ?? 50;
    if (affinity < 20) continue; // Low affinity = no gift

    giftGivers++;
    // Higher affinity = better gifts
    if (affinity >= 80) {
      totalGiftMoney += Math.floor(Math.random() * 50) + 50;
      totalGiftDiamonds += Math.floor(Math.random() * 3) + 1;
    } else if (affinity >= 50) {
      totalGiftMoney += Math.floor(Math.random() * 30) + 20;
      totalGiftDiamonds += Math.random() > 0.5 ? 1 : 0;
    } else {
      totalGiftMoney += Math.floor(Math.random() * 15) + 5;
    }
  }

  if (giftGivers === 0) {
    return createMessageEvent(
      fname,
      "It's your birthday but nobody got you a gift this year. Maybe next year will be different.",
      player,
      true,
    );
  }

  player.money += totalGiftMoney;
  player.diamonds += totalGiftDiamonds;
  player.c.happiness = modifyStat(player.c.happiness, Math.min(giftGivers * 3, 20));

  const diamondMsg = totalGiftDiamonds > 0 ? ` and ${totalGiftDiamonds} diamonds` : '';
  return createMessageEvent(
    fname,
    `Happy birthday! ${giftGivers} people gave you gifts worth $${totalGiftMoney}${diamondMsg}!`,
    player,
    true,
    { moneyCost: -totalGiftMoney, diamondCost: -totalGiftDiamonds }
  );
}

/**
 * All birthday event functions
 */
export const birthdayEvents = {
  sweet16,
  eighteenthBirthday,
  twentyFirstBirthday,
  decadeBirthday,
  birthdayGifts,
};
