/**
 * Enhanced Holiday Events
 * Rich holiday events with real gameplay tradeoffs
 * New Year's resolutions with lasting effects, Valentine's Day (partnered vs single),
 * Thanksgiving multi-stage, Christmas multi-stage, seasonal flavor
 */

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

// ──────────────────────────────────────────────
// New Year's Resolution (with 30-day stat effect)
// ──────────────────────────────────────────────

export function newYearResolutionEnhanced(player: Player, _type: 'message' | 'question' = 'message'): EventResult {
  const fname = `newYearResolution_enhanced_${player.character.ageYears}`;
  const check = !player.askedQuestions.has(fname) &&
    player.date === '01-01' &&
    player.character.ageYears >= 12;

  if (!check) return null;

  player.askedQuestions.add(fname);

  return createQuestionEvent(
    fname,
    "It's a new year! Time for resolutions. Choose one to commit to for the next month. Your choice will have lasting effects on your stats.",
    player,
    true,
    {
      answerOptions: [
        createAnswerOption('Exercise every day (+health, -energy)', '', 10, 0, 0),
        createAnswerOption('Read more books (+intelligence, costs time)', '', 5, 0, 20),
        createAnswerOption('Save money aggressively (+money, -happiness)', '', 0, 0, 0),
        createAnswerOption('Be more social (+social, -energy)', '', 10, 0, 30),
        createAnswerOption('No resolutions - live free', '', 0, 0, 0),
      ],
    }
  );
}

// ──────────────────────────────────────────────
// Valentine's Day Enhanced (partnered vs single paths)
// ──────────────────────────────────────────────

export function valentinesDayEnhanced(player: Player, _type: 'message' | 'question' = 'message'): EventResult {
  const fname = `valentinesDay_enhanced_${player.character.ageYears}`;
  const check = !player.askedQuestions.has(fname) &&
    player.date === '02-14' &&
    player.character.ageYears >= 14;

  if (!check) return null;

  player.askedQuestions.add(fname);

  const hasPartner = !!player.character.partner;

  if (hasPartner) {
    return createQuestionEvent(
      fname,
      "It's Valentine's Day and you're in a relationship! How do you celebrate with your partner?",
      player,
      true,
      {
        answerOptions: [
          createAnswerOption('Fancy restaurant dinner', '', 10, 0, 150),
          createAnswerOption('Homemade dinner and movie night', '', 15, 0, 30),
          createAnswerOption('Surprise them with an expensive gift', '', 5, 10, 200),
          createAnswerOption('Exchange thoughtful handmade cards', '', 10, 0, 5),
        ],
      }
    );
  } else {
    return createQuestionEvent(
      fname,
      "It's Valentine's Day and you're flying solo this year. How do you spend the day?",
      player,
      true,
      {
        answerOptions: [
          createAnswerOption('Galentines/Palentines with friends', '', 10, 0, 40),
          createAnswerOption('Treat yourself - spa day and shopping', '', 5, 0, 100),
          createAnswerOption('Binge-watch movies and eat chocolate', '', 0, 0, 15),
          createAnswerOption('Volunteer at a local shelter', '', 15, 0, 0),
        ],
      }
    );
  }
}

// ──────────────────────────────────────────────
// Halloween Enhanced (age-gated activities)
// ──────────────────────────────────────────────

export function halloweenEnhanced(player: Player, _type: 'message' | 'question' = 'message'): EventResult {
  const age = player.character.ageYears;
  const fname = `halloween_enhanced_${age}`;
  const check = !player.askedQuestions.has(fname) &&
    player.date === '10-31' &&
    age >= 3;

  if (!check) return null;

  player.askedQuestions.add(fname);

  if (age <= 8) {
    return createQuestionEvent(
      fname,
      "It's Halloween! Your parents are taking you trick-or-treating. What costume do you wear?",
      player,
      true,
      {
        answerOptions: [
          createAnswerOption('Superhero costume', '', 0, 0, 25),
          createAnswerOption('Scary monster', '', 0, 0, 20),
          createAnswerOption('Princess/Knight', '', 0, 0, 30),
          createAnswerOption('Homemade creative costume', '', 10, 0, 5),
        ],
      }
    );
  } else if (age <= 14) {
    return createQuestionEvent(
      fname,
      "It's Halloween! You're getting a bit old for trick-or-treating but the candy is still tempting. What's your plan?",
      player,
      true,
      {
        answerOptions: [
          createAnswerOption('Trick-or-treat one last time - maximize candy haul', '', 15, 0, 10),
          createAnswerOption('Go to a Halloween party at a friend\'s house', '', 10, 0, 20),
          createAnswerOption('Set up a haunted house in the garage', '', 20, 0, 40),
          createAnswerOption('Stay home and hand out candy', '', 0, 0, 30),
        ],
      }
    );
  } else if (age <= 25) {
    return createQuestionEvent(
      fname,
      "It's Halloween! There are some cool costume parties happening. What's your move?",
      player,
      true,
      {
        answerOptions: [
          createAnswerOption('Go all out on an elaborate costume and hit the party', '', 15, 0, 80),
          createAnswerOption('Group costume with friends', '', 10, 0, 40),
          createAnswerOption('Horror movie marathon at home', '', 5, 0, 20),
          createAnswerOption('Visit a haunted house attraction', '', 10, 0, 50),
        ],
      }
    );
  } else {
    return createQuestionEvent(
      fname,
      "It's Halloween! As an adult, how do you participate?",
      player,
      true,
      {
        answerOptions: [
          createAnswerOption('Decorate the house and hand out full-size candy bars', '', 10, 0, 75),
          createAnswerOption('Costume party with friends', '', 10, 0, 50),
          createAnswerOption('Take kids trick-or-treating', '', 15, 0, 30),
          createAnswerOption('Turn off the lights and pretend not to be home', '', 0, 0, 0),
        ],
      }
    );
  }
}

// ──────────────────────────────────────────────
// Thanksgiving (multi-stage family dinner)
// ──────────────────────────────────────────────

interface ThanksgivingDilemma extends DilemmaClass {
  dinnerChoice?: string;
}

export function thanksgivingDinner(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option?: string },
  dilemma?: ThanksgivingDilemma
): EventResult {
  const fname = `thanksgivingDinner_${player.character.ageYears}`;
  const check = !player.askedQuestions.has(fname) &&
    player.date === '11-23' &&
    player.character.ageYears >= 8;

  const answerOptions = player.character.ageYears >= 18
    ? [
        createAnswerOption('Host dinner at your place', '', 25, 0, 200),
        createAnswerOption('Go to parents\' house for dinner', '', 5, 0, 50),
        createAnswerOption('Friendsgiving with your chosen family', '', 10, 0, 100),
        createAnswerOption('Volunteer at a soup kitchen', '', 20, 0, 0),
      ]
    : [
        createAnswerOption('Help cook the turkey', '', 15, 0, 0),
        createAnswerOption('Set the table and be helpful', '', 5, 0, 0),
        createAnswerOption('Watch the parade and sneak food early', '', 0, 0, 0),
        createAnswerOption('Hide in your room until dinner is ready', '', 0, 0, 0),
      ];

  if (check && type !== 'answer') {
    player.askedQuestions.add(fname);
    const dilemmaObj = createDilemma(fname, answerOptions) as ThanksgivingDilemma;
    player.activeDilemmas.push(dilemmaObj);
    const intro = player.character.ageYears >= 18
      ? "Thanksgiving is here! The smell of turkey fills the air. Where are you spending the holiday?"
      : "Thanksgiving is here! The whole family is coming over and the kitchen is chaos. What's your role today?";
    return createQuestionEvent(fname, intro, player, true, { answerOptions });
  }

  if (type === 'answer' && player.activeDilemmas.length > 0) {
    const currentDilemma = player.activeDilemmas[player.activeDilemmas.length - 1] as ThanksgivingDilemma;
    currentDilemma.answer = answerOptions.find(opt => opt.option === response?.option) ?? null;
    currentDilemma.dinnerChoice = 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 (player.character.ageYears >= 18) {
      if (dilemma.answer.option === answerOptions[0].option) {
        // Family dilemma moment during hosting
        const politicsArg = Math.random() > 0.6;
        if (politicsArg) {
          message = "Hosting went well until Uncle brought up politics at dinner. The table got tense, but you skillfully changed the subject. The food was great though, and everyone complimented your cooking!";
          c.happiness = modifyStat(c.happiness, 10);
          c.social = modifyStat(c.social, 10);
          c.stress = modifyStat(c.stress, 10);
        } else {
          message = "Your Thanksgiving dinner was a hit! Everyone loved the turkey, the sides were perfect, and dessert was amazing. You feel proud and grateful.";
          c.happiness = modifyStat(c.happiness, 20);
          c.social = modifyStat(c.social, 15);
        }
      } else if (dilemma.answer.option === answerOptions[1].option) {
        message = "Being back at your parents' house for Thanksgiving felt nostalgic. Mom's cooking is still the best. You caught up with family and felt connected.";
        c.happiness = modifyStat(c.happiness, 15);
        c.social = modifyStat(c.social, 10);
      } else if (dilemma.answer.option === answerOptions[2].option) {
        message = "Friendsgiving was exactly what you needed. Good food, good people, no family drama. Everyone brought a dish and it felt like home.";
        c.happiness = modifyStat(c.happiness, 20);
        c.social = modifyStat(c.social, 15);
      } else {
        message = "Volunteering at the soup kitchen on Thanksgiving was humbling and rewarding. You served hundreds of meals and left feeling grateful for what you have.";
        c.happiness = modifyStat(c.happiness, 25);
        c.social = modifyStat(c.social, 20);
        player.diamonds += 5;
      }
    } else {
      if (dilemma.answer.option === answerOptions[0].option) {
        message = "You helped cook the turkey and it turned out perfectly! Your family was impressed and you felt proud of your contribution.";
        c.happiness = modifyStat(c.happiness, 15);
        c.intelligence = modifyStat(c.intelligence, 3);
      } else if (dilemma.answer.option === answerOptions[1].option) {
        message = "You set a beautiful table and helped serve everyone. Your parents bragged about how helpful you were. Extra dessert for you!";
        c.happiness = modifyStat(c.happiness, 15);
        c.social = modifyStat(c.social, 5);
      } else if (dilemma.answer.option === answerOptions[2].option) {
        message = "You watched the parade, snuck some rolls before dinner, and enjoyed the laziness. When dinner came, you were the first at the table!";
        c.happiness = modifyStat(c.happiness, 10);
      } else {
        message = "You hid in your room playing games until dinner was called. The food was great, but your parents gave you a look for not helping.";
        c.happiness = modifyStat(c.happiness, 5);
        c.social = modifyStat(c.social, -5);
      }
    }

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

  return null;
}

// ──────────────────────────────────────────────
// Christmas (multi-stage: gift buying -> exchange -> reactions)
// ──────────────────────────────────────────────

interface ChristmasDilemma extends DilemmaClass {
  giftBudget?: string;
}

export function christmasEnhanced(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option?: string },
  dilemma?: ChristmasDilemma
): EventResult {
  const fname = `christmasEnhanced_${player.character.ageYears}`;
  const check = !player.askedQuestions.has(fname) &&
    player.date === '12-25' &&
    player.character.ageYears >= 5;

  const answerOptions = player.character.ageYears >= 16
    ? [
        createAnswerOption('Go all out on gifts for everyone', '', 10, 0, 300),
        createAnswerOption('Thoughtful homemade gifts', '', 20, 0, 30),
        createAnswerOption('Reasonable budget with a few splurges', '', 5, 0, 150),
        createAnswerOption('Suggest a Secret Santa to save money', '', 0, 0, 50),
      ]
    : [
        createAnswerOption('Wake up super early and run to the tree!', '', 5, 0, 0),
        createAnswerOption('Wait patiently for everyone to get up', '', 0, 5, 0),
        createAnswerOption('Peek at presents the night before', '', 0, 0, 0),
        createAnswerOption('Make breakfast for the family first', '', 10, 0, 0),
      ];

  if (check && type !== 'answer') {
    player.askedQuestions.add(fname);
    const dilemmaObj = createDilemma(fname, answerOptions) as ChristmasDilemma;
    player.activeDilemmas.push(dilemmaObj);
    const intro = player.character.ageYears >= 16
      ? "It's Christmas morning! But first - how did your gift shopping go this year?"
      : "It's Christmas morning! The tree is lit up and presents are underneath. What do you do?";
    return createQuestionEvent(fname, intro, player, true, { answerOptions });
  }

  if (type === 'answer' && player.activeDilemmas.length > 0) {
    const currentDilemma = player.activeDilemmas[player.activeDilemmas.length - 1] as ChristmasDilemma;
    currentDilemma.answer = answerOptions.find(opt => opt.option === response?.option) ?? null;
    currentDilemma.giftBudget = 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 = '';

    // Calculate received gifts based on relationships
    let giftValue = 0;
    let diamondGifts = 0;
    for (const person of player.r) {
      if (person.status !== 'alive') continue;
      const affinity = person.affinity ?? 50;
      if (affinity >= 60) {
        giftValue += Math.floor(Math.random() * 50) + 30;
        if (Math.random() > 0.7) diamondGifts += 1;
      } else if (affinity >= 30) {
        giftValue += Math.floor(Math.random() * 20) + 10;
      }
    }
    player.money += giftValue;
    player.diamonds += diamondGifts;

    if (player.character.ageYears >= 16) {
      if (dilemma.answer.option === answerOptions[0].option) {
        message = `Christmas was magical! Everyone loved their gifts and you received $${giftValue} worth of presents in return. The generosity came full circle.`;
        c.happiness = modifyStat(c.happiness, 25);
        c.social = modifyStat(c.social, 15);
      } else if (dilemma.answer.option === answerOptions[1].option) {
        message = `Your homemade gifts were a huge hit! Everyone was touched by the personal effort. You received $${giftValue} in gifts and felt the true spirit of the holiday.`;
        c.happiness = modifyStat(c.happiness, 30);
        c.creativity = modifyStat(c.creativity, 10);
        c.social = modifyStat(c.social, 10);
      } else if (dilemma.answer.option === answerOptions[2].option) {
        message = `A balanced Christmas! Your splurge gifts were loved and the rest were appreciated. You received $${giftValue} in return. A good holiday all around.`;
        c.happiness = modifyStat(c.happiness, 20);
        c.social = modifyStat(c.social, 10);
      } else {
        message = `Secret Santa was a great idea! Less stress, less spending, and everyone got a fun surprise. You received $${giftValue} in gifts overall.`;
        c.happiness = modifyStat(c.happiness, 15);
        c.stress = modifyStat(c.stress, -10);
      }
    } else {
      if (dilemma.answer.option === answerOptions[0].option) {
        message = `You ran downstairs at dawn and tore through the wrapping paper! You got $${giftValue} worth of amazing presents! Best Christmas ever!`;
        c.happiness = modifyStat(c.happiness, 30);
      } else if (dilemma.answer.option === answerOptions[1].option) {
        message = `You waited patiently and your parents noticed. They were proud of your maturity. When you finally opened presents, you got $${giftValue} worth of great stuff!`;
        c.happiness = modifyStat(c.happiness, 25);
        c.social = modifyStat(c.social, 5);
        player.diamonds += 2;
      } else if (dilemma.answer.option === answerOptions[2].option) {
        message = `You peeked last night so the surprise was a bit spoiled, but opening them was still fun! You got $${giftValue} in presents.`;
        c.happiness = modifyStat(c.happiness, 15);
      } else {
        message = `You made pancakes for the whole family before presents! Everyone was delighted. Then you opened $${giftValue} worth of gifts. A perfect morning.`;
        c.happiness = modifyStat(c.happiness, 25);
        c.social = modifyStat(c.social, 10);
        player.diamonds += 3;
      }
    }

    const idx = player.activeDilemmas.indexOf(dilemma);
    if (idx > -1) player.activeDilemmas.splice(idx, 1);
    return createMessageEvent(fname, message, player, true, {
      moneyCost: -giftValue,
      diamondCost: -diamondGifts,
    });
  }

  return null;
}

// ──────────────────────────────────────────────
// Summer Solstice / Seasonal Flavor
// ──────────────────────────────────────────────

export function summerSolstice(player: Player, _type: 'message' | 'question' = 'message'): EventResult {
  const fname = `summerSolstice_${player.character.ageYears}`;
  const check = !player.events.has(fname) &&
    player.date === '06-21' &&
    player.character.ageYears >= 5 &&
    checkProbability(3);

  if (check) {
    player.events.add(fname);
    player.c.happiness = modifyStat(player.c.happiness, 10);
    player.c.energy = modifyStat(player.c.energy, 5);
  }

  return createMessageEvent(
    fname,
    "It's the longest day of the year! The sun stays out late and the warm air feels electric with possibility. Summer is officially here!",
    player,
    check
  );
}

// ──────────────────────────────────────────────
// First Day of Autumn
// ──────────────────────────────────────────────

export function firstDayAutumn(player: Player, _type: 'message' | 'question' = 'message'): EventResult {
  const fname = `firstDayAutumn_${player.character.ageYears}`;
  const check = !player.events.has(fname) &&
    player.date === '09-22' &&
    player.character.ageYears >= 5 &&
    checkProbability(3);

  if (check) {
    player.events.add(fname);
    player.c.happiness = modifyStat(player.c.happiness, 5);
  }

  return createMessageEvent(
    fname,
    "The leaves are changing colors and there's a chill in the air. Fall is here! Time for sweaters, hot cider, and cozy evenings.",
    player,
    check
  );
}

// ──────────────────────────────────────────────
// Fourth of July Enhanced
// ──────────────────────────────────────────────

export function fourthOfJulyEnhanced(player: Player, _type: 'message' | 'question' = 'message'): EventResult {
  const fname = `fourthOfJuly_enhanced_${player.character.ageYears}`;
  const check = !player.askedQuestions.has(fname) &&
    player.date === '07-04' &&
    player.character.ageYears >= 5;

  if (!check) return null;

  player.askedQuestions.add(fname);

  if (player.character.ageYears <= 12) {
    return createQuestionEvent(
      fname,
      "It's the Fourth of July! Fireworks, BBQ, and fun! What are you most excited about?",
      player,
      true,
      {
        answerOptions: [
          createAnswerOption('Sparklers and fireworks!', '', 5, 0, 10),
          createAnswerOption('BBQ and watermelon', '', 0, 0, 0),
          createAnswerOption('Swimming and water balloons', '', 10, 0, 5),
          createAnswerOption('The parade downtown', '', 5, 0, 0),
        ],
      }
    );
  } else {
    return createQuestionEvent(
      fname,
      "Fourth of July weekend! How do you celebrate?",
      player,
      true,
      {
        answerOptions: [
          createAnswerOption('Host a BBQ cookout', '', 15, 0, 100),
          createAnswerOption('Beach day with friends', '', 10, 0, 30),
          createAnswerOption('Find the best fireworks viewing spot', '', 5, 0, 0),
          createAnswerOption('Take a long weekend road trip', '', 10, 0, 200),
        ],
      }
    );
  }
}

/**
 * All enhanced holiday event functions
 */
export const enhancedHolidayEvents = {
  newYearResolutionEnhanced,
  valentinesDayEnhanced,
  halloweenEnhanced,
  thanksgivingDinner,
  christmasEnhanced,
  summerSolstice,
  firstDayAutumn,
  fourthOfJulyEnhanced,
};
