/**
 * Family Milestone Events (Multi-Stage, Class-Based)
 *
 * Major family events that unfold over time.
 * These are class-based events for fast mode gameplay.
 *
 * Class-based events:
 * - ParentGetsSick: Parent diagnosed with serious illness (3 stages)
 * - SiblingsWedding: Sibling's wedding preparation and ceremony (3 stages)
 * - ChildMilestones: Child's developmental milestones (first words, school, teen, graduation)
 * - FamilySecretRevealed: Discovery of a hidden family truth
 * - FamilyReunion: Multi-stage family reunion planning and event
 * - InheritanceDispute: Family conflict over inheritance
 */

import { Player } from '../../models/Player.js';
import { Person } from '../../models/Person.js';
import {
  BaseEvent,
  EventConfig,
  EventResult,
  AnswerOption,
  createAnswerOption,
  modifyStat,
} from '../base.js';

// =============================================================================
// Helpers
// =============================================================================

type ExtendedPerson = Person & { title?: string };

function scheduleFollowUp(
  player: Player,
  id: string,
  daysFromNow: number,
  hour: number,
  message: string
): void {
  let targetDayOfYear = (player.dayOfYear ?? 1) + daysFromNow;
  if (targetDayOfYear > 365) targetDayOfYear -= 365;

  const baseDate = new Date(2022, 0, 1);
  const targetDate = new Date(baseDate);
  targetDate.setDate(targetDate.getDate() + targetDayOfYear - 1);
  const month = String(targetDate.getMonth() + 1).padStart(2, '0');
  const day = String(targetDate.getDate()).padStart(2, '0');
  const dateStr = `${month}-${day}`;

  player.c.oneTimeEvents = player.c.oneTimeEvents ?? [];
  player.c.oneTimeEvents.push({ id, date: dateStr, hour, message });
}

function findParent(player: Player): Person | null {
  return (player.r ?? []).find((p) => {
    if (p.status !== 'alive') return false;
    const rels = p.relationships ?? [];
    const title = (p as ExtendedPerson).title?.toLowerCase() ?? '';
    return rels.includes('mother') || rels.includes('father') || title === 'mother' || title === 'father';
  }) ?? null;
}

function findSibling(player: Player): Person | null {
  return (player.r ?? []).find((p) => {
    if (p.status !== 'alive') return false;
    const rels = p.relationships ?? [];
    const title = (p as ExtendedPerson).title?.toLowerCase() ?? '';
    return rels.includes('sibling') || rels.includes('brother') || rels.includes('sister') ||
      title.includes('sibling') || title.includes('brother') || title.includes('sister');
  }) ?? null;
}

function findChild(player: Player): Person | null {
  return (player.r ?? []).find((p) => {
    if (p.status !== 'alive') return false;
    return (p.relationships ?? []).includes('child');
  }) ?? null;
}

function getParentTitle(person: Person): string {
  const rels = person.relationships ?? [];
  const title = (person as ExtendedPerson).title?.toLowerCase() ?? '';
  if (rels.includes('mother') || title === 'mother') return 'mother';
  if (rels.includes('father') || title === 'father') return 'father';
  return 'parent';
}

// =============================================================================
// ParentGetsSick - 3-stage serious illness
// =============================================================================

/**
 * Stage 1: Parent diagnosed
 * Stage 2 (14 days): Treatment begins, needs support
 * Stage 3 (60 days): Recovery or worsening
 */
export class ParentGetsSick extends BaseEvent {
  readonly id = 'parentGetsSick';

  get mode(): 'fast' { return 'fast'; }

  getConfig(): EventConfig {
    return {
      minAge: 20,
      maxAge: 80,
      baseChance: 0.0003,
      triggerType: 'conditional',
    };
  }

  checkConditions(player: Player): boolean {
    if (player.askedQuestions.has(this.id)) return false;
    return findParent(player) !== null;
  }

  getQuestion(player?: Player): string {
    const parent = findParent(player!);
    const title = parent ? getParentTitle(parent) : 'parent';
    const name = parent?.firstname ?? 'Your parent';
    return `You get a phone call that stops you in your tracks. Your ${title} ${name} has been diagnosed with a serious illness. The doctor says they need treatment and support. How do you respond?`;
  }

  getAnswerOptions(): AnswerOption[] {
    return [
      createAnswerOption('Drop everything and go to them', 'rush', 20, 0, 500),
      createAnswerOption('Start researching the best doctors', 'research', 15, 0, 200),
      createAnswerOption('Call them and offer support', 'call', 10),
      createAnswerOption('Send a text, you\'ll visit when you can', 'text'),
    ];
  }

  processAnswer(player: Player, selectedOption: number): EventResult {
    const parent = findParent(player);
    if (!parent) {
      return { type: 'messageEvent', message: 'The news was difficult to process.' };
    }

    const title = getParentTitle(parent);
    const name = parent.firstname;

    player.c.happiness = modifyStat(player.c.happiness, -15);
    player.c.stress = modifyStat(player.c.stress, 20);

    if (selectedOption === 0) {
      // Rush to them
      player.c.energy = modifyStat(player.c.energy, -20);
      player.money = Math.max(0, player.money - 500);
      parent.affinity = modifyStat(parent.affinity, 10, -100, 100);

      scheduleFollowUp(
        player,
        `parentSick_stage2_${parent.id}`,
        14,
        10,
        `Two weeks of being by your ${title}'s side. ${name} started treatment and you've been driving them to appointments, making meals, and keeping their spirits up. It's exhausting but they squeeze your hand and say "Thank you for being here." It means everything.`
      );
    } else if (selectedOption === 1) {
      // Research
      player.c.energy = modifyStat(player.c.energy, -15);
      player.money = Math.max(0, player.money - 200);
      parent.affinity = modifyStat(parent.affinity, 5, -100, 100);

      scheduleFollowUp(
        player,
        `parentSick_stage2_${parent.id}`,
        14,
        10,
        `Your research paid off. You found a specialist for your ${title} ${name} and they're optimistic about the treatment plan. ${name} says having you in their corner makes all the difference.`
      );
    } else if (selectedOption === 2) {
      // Call
      player.c.energy = modifyStat(player.c.energy, -10);
      parent.affinity = modifyStat(parent.affinity, 3, -100, 100);

      scheduleFollowUp(
        player,
        `parentSick_stage2_${parent.id}`,
        14,
        10,
        `Your ${title} ${name} has started treatment. You've been calling regularly but haven't been able to visit yet. They say they understand but you can hear the loneliness in their voice.`
      );
    } else {
      // Text
      parent.affinity = modifyStat(parent.affinity, -5, -100, 100);

      scheduleFollowUp(
        player,
        `parentSick_stage2_${parent.id}`,
        14,
        10,
        `Your ${title} ${name} is going through treatment mostly alone. A sibling mentioned that ${name} was hurt you didn't come. The guilt is starting to weigh on you.`
      );
    }

    // Stage 3: outcome (60 days)
    const recovers = Math.random() < 0.7;
    if (recovers) {
      scheduleFollowUp(
        player,
        `parentSick_stage3_${parent.id}`,
        60,
        14,
        `After two months, your ${title} ${name} is showing real improvement. The treatment is working and the color is coming back to their face. They're not out of the woods yet, but the worst seems to be over. The family lets out a collective sigh of relief.`
      );
    } else {
      scheduleFollowUp(
        player,
        `parentSick_stage3_${parent.id}`,
        60,
        14,
        `The treatment for your ${title} ${name} hasn't gone as hoped. The doctors are adjusting the plan but it's clear this will be a longer battle. ${name} is putting on a brave face, but you can see the toll it's taking. The family is pulling together.`
      );
    }

    const responses = [
      `You dropped everything and drove straight to your ${title}. When ${name} opened the door, the relief on their face was overwhelming. You held them tight and promised to be there through this.`,
      `You spent the evening researching specialists and treatment options for your ${title}. Knowledge is power, and you want ${name} to have the best care possible. You called with a plan.`,
      `You called your ${title} ${name} immediately. The conversation was hard. They tried to be strong but their voice cracked. You promised to visit soon and check in every day.`,
      `You sent a supportive text to your ${title} ${name}. You meant to call but couldn't find the words. Life feels overwhelming right now.`,
    ];

    return {
      type: 'messageEvent',
      message: responses[selectedOption] ?? responses[0],
      moneyCost: selectedOption === 0 ? 500 : selectedOption === 1 ? 200 : 0,
      energyCost: selectedOption === 0 ? 20 : selectedOption === 1 ? 15 : 10,
    };
  }
}

// =============================================================================
// SiblingsWedding - Sibling's wedding (3 stages)
// =============================================================================

export class SiblingsWedding extends BaseEvent {
  readonly id = 'siblingsWedding';

  get mode(): 'fast' { return 'fast'; }

  getConfig(): EventConfig {
    return {
      minAge: 18,
      maxAge: 80,
      baseChance: 0.0003,
      triggerType: 'conditional',
    };
  }

  checkConditions(player: Player): boolean {
    if (player.askedQuestions.has(this.id)) return false;
    const sibling = findSibling(player);
    return sibling !== null && (sibling.ageYears ?? 0) >= 20;
  }

  getQuestion(player?: Player): string {
    const sibling = findSibling(player!);
    const name = sibling?.firstname ?? 'Your sibling';
    return `${name} is getting married! They called to share the news and want you to be in the wedding party. The wedding is in a few months. How do you feel about it?`;
  }

  getAnswerOptions(): AnswerOption[] {
    return [
      createAnswerOption('Thrilled! I\'ll go all out ($500)', 'allout', 10, 0, 500),
      createAnswerOption('Happy for them, attend normally ($200)', 'attend', 5, 0, 200),
      createAnswerOption('Attend but keep it minimal ($100)', 'minimal', 0, 0, 100),
      createAnswerOption('Skip the wedding', 'skip'),
    ];
  }

  processAnswer(player: Player, selectedOption: number): EventResult {
    const sibling = findSibling(player);
    if (!sibling) {
      return { type: 'messageEvent', message: 'The wedding invitation arrived.' };
    }

    const name = sibling.firstname;

    if (selectedOption === 3) {
      // Skip the wedding
      sibling.affinity = modifyStat(sibling.affinity, -20, -100, 100);
      player.c.happiness = modifyStat(player.c.happiness, -10);

      scheduleFollowUp(
        player,
        `siblingsWedding_aftermath_${sibling.id}`,
        90,
        18,
        `It's been three months since you skipped ${name}'s wedding. They haven't called. The rest of the family is giving you the cold shoulder. You're starting to wonder if you made a mistake.`
      );

      return {
        type: 'messageEvent',
        message: `You told ${name} you can't make it to the wedding. The silence on the other end of the phone said everything.`,
        affinityChange: -20,
      };
    }

    const costs = [500, 200, 100];
    const cost = costs[selectedOption] ?? 200;
    player.money = Math.max(0, player.money - cost);

    // Stage 2: Wedding prep (30 days)
    scheduleFollowUp(
      player,
      `siblingsWedding_prep_${sibling.id}`,
      30,
      14,
      selectedOption === 0
        ? `Wedding prep for ${name}'s big day is in full swing. You helped organize the bachelor/bachelorette party and it was legendary. ${name} keeps saying how much it means to have you involved.`
        : `${name}'s wedding is coming up soon. You picked out your outfit and RSVP'd. The family group chat is buzzing with excitement.`
    );

    // Stage 3: Wedding day (90 days)
    scheduleFollowUp(
      player,
      `siblingsWedding_day_${sibling.id}`,
      90,
      16,
      `${name}'s wedding day. The ceremony was beautiful. When ${name} looked at their partner and said "I do," you couldn't help but tear up. The reception was incredible — you danced, laughed, and made a toast that had everyone crying. Your ${name === sibling.firstname ? 'sibling' : 'family'} is starting a new chapter, and you're happy for them.`
    );

    sibling.affinity = modifyStat(sibling.affinity, selectedOption === 0 ? 10 : 5, -100, 100);
    player.c.happiness = modifyStat(player.c.happiness, selectedOption === 0 ? 10 : 5);

    const messages = [
      `You're going all out for ${name}'s wedding! You already volunteered for the planning committee and started shopping for the perfect gift. This is going to be amazing.`,
      `You're happy for ${name} and looking forward to the wedding. You RSVP'd and marked the date. It'll be a great celebration.`,
      `You'll attend ${name}'s wedding but keep things simple. A card, a modest gift, and your presence. That should be enough.`,
    ];

    return {
      type: 'messageEvent',
      message: messages[selectedOption] ?? messages[1],
      moneyCost: cost,
    };
  }
}

// =============================================================================
// ChildMilestones - Child developmental milestones
// =============================================================================

export class ChildMilestones extends BaseEvent {
  readonly id = 'childMilestones';

  get mode(): 'fast' { return 'fast'; }

  getConfig(): EventConfig {
    return {
      minAge: 20,
      maxAge: 70,
      baseChance: 0.0005,
      triggerType: 'conditional',
    };
  }

  checkConditions(player: Player): boolean {
    if (player.askedQuestions.has(this.id)) return false;
    return findChild(player) !== null;
  }

  getQuestion(player?: Player): string {
    const child = findChild(player!);
    const name = child?.firstname ?? 'Your child';
    const age = child?.ageYears ?? 3;

    if (age <= 2) return `${name} just said their first word! It sounded like "dada" or maybe "baba." Either way, your heart is melting.`;
    if (age <= 5) return `${name}'s first day of school is here. They're clutching your hand at the school gate, eyes wide, looking up at you. This is a big moment.`;
    if (age <= 12) return `${name} came home from school beaming. They won an award for their science project! They're so proud and want to show you.`;
    if (age <= 16) return `${name} is becoming a teenager and the attitude is real. They slammed their door after you asked about homework. What do you do?`;
    return `${name} is graduating! The ceremony is next week and they asked you to be there. You can't believe how fast time went.`;
  }

  getAnswerOptions(): AnswerOption[] {
    return [
      createAnswerOption('Celebrate this moment fully', 'celebrate', 5, 0, 50),
      createAnswerOption('Acknowledge it warmly', 'warm'),
      createAnswerOption('Note it, but you\'re preoccupied', 'busy'),
    ];
  }

  processAnswer(player: Player, selectedOption: number): EventResult {
    const child = findChild(player);
    if (!child) {
      return { type: 'messageEvent', message: 'A milestone passed.' };
    }

    const name = child.firstname;
    const age = child.ageYears ?? 3;

    if (selectedOption === 0) {
      // Celebrate
      player.c.happiness = modifyStat(player.c.happiness, 15);
      player.money = Math.max(0, player.money - 50);
      child.affinity = modifyStat(child.affinity, 8, -100, 100);

      if (age <= 2) return { type: 'messageEvent', message: `You recorded ${name}'s first word and sent it to the entire family. You played it back twenty times. This might be the best moment of your life so far.`, moneyCost: 50 };
      if (age <= 5) return { type: 'messageEvent', message: `You walked ${name} to their classroom, met the teacher, and snuck a photo. You only cried a little in the car afterward. They're growing up so fast.`, moneyCost: 50 };
      if (age <= 12) return { type: 'messageEvent', message: `You took ${name} out for ice cream to celebrate their award. They talked excitedly about their project the whole time. You're so proud.`, moneyCost: 50 };
      if (age <= 16) return { type: 'messageEvent', message: `Instead of escalating, you waited and then knocked on ${name}'s door. "Can we talk?" The conversation that followed was real, honest, and important. Being a parent isn't easy, but moments like these matter.` };
      return { type: 'messageEvent', message: `You sat in the front row at ${name}'s graduation, camera ready. When they walked across that stage, you were the loudest one cheering. The whole family went out to dinner to celebrate.`, moneyCost: 50 };
    } else if (selectedOption === 1) {
      // Warm
      player.c.happiness = modifyStat(player.c.happiness, 8);
      child.affinity = modifyStat(child.affinity, 5, -100, 100);
      return { type: 'messageEvent', message: `You acknowledged ${name}'s milestone with genuine warmth. A hug, kind words, and your full attention for a moment. Sometimes that's all a kid needs.` };
    } else {
      // Busy
      player.c.happiness = modifyStat(player.c.happiness, -5);
      child.affinity = modifyStat(child.affinity, -3, -100, 100);
      return { type: 'messageEvent', message: `You were distracted when ${name}'s milestone happened. You said "that's nice" without really looking up. ${name}'s face fell just a little. You'll remember this later and wish you'd been more present.` };
    }
  }
}

// =============================================================================
// FamilySecretRevealed - Discovery of a hidden family truth
// =============================================================================

export class FamilySecretRevealed extends BaseEvent {
  readonly id = 'familySecretRevealed';

  get mode(): 'fast' { return 'fast'; }

  getConfig(): EventConfig {
    return {
      minAge: 16,
      maxAge: 80,
      baseChance: 0.0002,
      triggerType: 'random',
    };
  }

  checkConditions(player: Player): boolean {
    return !player.askedQuestions.has(this.id);
  }

  getQuestion(_player?: Player): string {
    const secrets = [
      "While going through old family documents, you discover that you have a half-sibling nobody ever told you about.",
      "Your parent let something slip at dinner that revealed a long-hidden family secret about your grandparents.",
      "You found old letters in the attic that reveal a family member had a completely different life before the family knew them.",
      "A distant relative reached out on social media with information that changes how you see your family history.",
    ];
    return secrets[Math.floor(Math.random() * secrets.length)] + " How do you handle this?";
  }

  getAnswerOptions(): AnswerOption[] {
    return [
      createAnswerOption('Confront the family about it', 'confront', 15),
      createAnswerOption('Investigate quietly on your own', 'investigate', 10),
      createAnswerOption('Talk to one trusted family member', 'confide', 5),
      createAnswerOption('Let it go and move on', 'ignore'),
    ];
  }

  processAnswer(player: Player, selectedOption: number): EventResult {
    player.c.stress = modifyStat(player.c.stress, 15);

    if (selectedOption === 0) {
      player.c.energy = modifyStat(player.c.energy, -15);
      player.c.happiness = modifyStat(player.c.happiness, -10);

      scheduleFollowUp(
        player,
        `familySecret_aftermath`,
        14,
        18,
        "The family confrontation about the secret was intense. Some members were angry, others relieved it was finally out. Things are different now, but at least there are no more lies."
      );

      return { type: 'messageEvent', message: "You brought it up at the next family gathering. The room went silent. Then everyone started talking at once. The truth is out now, for better or worse.", energyCost: 15 };
    } else if (selectedOption === 1) {
      player.c.energy = modifyStat(player.c.energy, -10);

      scheduleFollowUp(
        player,
        `familySecret_investigation`,
        21,
        14,
        "Your quiet investigation into the family secret uncovered more than you expected. The truth is complicated, but understanding it helps you make sense of things that never quite added up."
      );

      return { type: 'messageEvent', message: "You decided to dig deeper on your own. There's something unsettling about learning your family isn't quite what you thought. But you need to know the full story.", energyCost: 10 };
    } else if (selectedOption === 2) {
      player.c.energy = modifyStat(player.c.energy, -5);

      return { type: 'messageEvent', message: "You confided in one family member you trust. They listened, shared what they knew, and together you decided how to move forward. Having an ally in this makes it easier." };
    } else {
      player.c.happiness = modifyStat(player.c.happiness, -5);
      return { type: 'messageEvent', message: "You decided some things are better left in the past. The secret stays buried, but a small part of you will always wonder." };
    }
  }
}

// =============================================================================
// FamilyReunion - Multi-stage family reunion
// =============================================================================

export class FamilyReunion extends BaseEvent {
  readonly id = 'familyReunion';

  get mode(): 'fast' { return 'fast'; }

  getConfig(): EventConfig {
    return {
      minAge: 12,
      maxAge: 100,
      baseChance: 0.0003,
      triggerType: 'random',
    };
  }

  checkConditions(player: Player): boolean {
    if (player.askedQuestions.has(this.id)) return false;
    const familyCount = (player.r ?? []).filter((p) => {
      if (p.status !== 'alive') return false;
      const rels = p.relationships ?? [];
      return rels.includes('mother') || rels.includes('father') ||
        rels.includes('sibling') || rels.includes('brother') || rels.includes('sister');
    }).length;
    return familyCount >= 2;
  }

  getQuestion(_player?: Player): string {
    return "Your family is organizing a big family reunion this summer. Aunts, uncles, cousins, the whole extended family. Everyone is expected to contribute. Are you going?";
  }

  getAnswerOptions(): AnswerOption[] {
    return [
      createAnswerOption('Yes, I\'ll help organize! ($200)', 'organize', 15, 0, 200),
      createAnswerOption('I\'ll attend and bring a dish ($50)', 'attend', 5, 0, 50),
      createAnswerOption('Show up briefly', 'brief'),
      createAnswerOption('Skip it this year', 'skip'),
    ];
  }

  processAnswer(player: Player, selectedOption: number): EventResult {
    if (selectedOption === 3) {
      player.c.happiness = modifyStat(player.c.happiness, -5);
      // Decrease affinity with all family
      for (const p of player.r ?? []) {
        const rels = p.relationships ?? [];
        if (p.status === 'alive' && (rels.includes('mother') || rels.includes('father') || rels.includes('sibling'))) {
          p.affinity = modifyStat(p.affinity, -3, -100, 100);
        }
      }
      return { type: 'messageEvent', message: "You skipped the family reunion. Photos on social media show everyone having a great time. Your absence was noticed and mentioned more than once." };
    }

    const costs = [200, 50, 0];
    const cost = costs[selectedOption] ?? 0;
    player.money = Math.max(0, player.money - cost);

    // Stage 2: Reunion day (30 days)
    if (selectedOption === 0) {
      scheduleFollowUp(
        player,
        `familyReunion_day`,
        30,
        12,
        "The family reunion you helped organize was a huge success! Your aunt's potato salad was legendary, the kids played in the yard all day, and your uncle told the same story he tells every year. But there was also a moment when everyone sat together, all generations, and it just felt right. Your cousins said this was the best reunion in years — thanks to you."
      );
      player.c.happiness = modifyStat(player.c.happiness, 10);
      player.c.energy = modifyStat(player.c.energy, 10);
    } else if (selectedOption === 1) {
      scheduleFollowUp(
        player,
        `familyReunion_day`,
        30,
        12,
        "The family reunion was wonderful. Your dish was a hit. You reconnected with cousins you hadn't seen in years and met some new additions to the family. Your grandmother held your hand and said she was glad you came."
      );
      player.c.happiness = modifyStat(player.c.happiness, 8);
    } else {
      scheduleFollowUp(
        player,
        `familyReunion_day`,
        30,
        12,
        "You stopped by the family reunion briefly. It was nice to see everyone, even if you couldn't stay long. Your relatives gave you the 'we miss you' look."
      );
      player.c.happiness = modifyStat(player.c.happiness, 3);
    }

    // Boost family affinity
    for (const p of player.r ?? []) {
      const rels = p.relationships ?? [];
      if (p.status === 'alive' && (rels.includes('mother') || rels.includes('father') || rels.includes('sibling'))) {
        const boost = selectedOption === 0 ? 5 : selectedOption === 1 ? 3 : 1;
        p.affinity = modifyStat(p.affinity, boost, -100, 100);
      }
    }

    const messages = [
      `You threw yourself into organizing the family reunion. You reserved the pavilion, coordinated the potluck list, and even made a family trivia game. It's going to be great.`,
      `You RSVP'd for the family reunion and signed up to bring a dish. Looking forward to seeing everyone.`,
      `You told the family you'd stop by the reunion, but can't stay the whole time. At least you'll make an appearance.`,
    ];

    return {
      type: 'messageEvent',
      message: messages[selectedOption] ?? messages[1],
      moneyCost: cost,
    };
  }
}

// =============================================================================
// InheritanceDispute - Family conflict over inheritance
// =============================================================================

export class InheritanceDispute extends BaseEvent {
  readonly id = 'inheritanceDispute';

  get mode(): 'fast' { return 'fast'; }

  getConfig(): EventConfig {
    return {
      minAge: 25,
      maxAge: 80,
      baseChance: 0.0002,
      triggerType: 'conditional',
    };
  }

  checkConditions(player: Player): boolean {
    if (player.askedQuestions.has(this.id)) return false;
    // Check if any family member has died (grandparent or parent)
    return (player.r ?? []).some((p) => {
      const rels = p.relationships ?? [];
      const title = (p as ExtendedPerson).title?.toLowerCase() ?? '';
      const isFamily = rels.includes('mother') || rels.includes('father') ||
        title.includes('grand') || title.includes('uncle') || title.includes('aunt');
      return isFamily && p.status === 'dead';
    });
  }

  getQuestion(_player?: Player): string {
    return "After a family member's passing, their estate needs to be settled. However, the will is vague and family members are starting to argue about who gets what. The tension is rising. How do you handle this?";
  }

  getAnswerOptions(): AnswerOption[] {
    return [
      createAnswerOption('Suggest hiring a mediator ($1000)', 'mediator', 10, 0, 1000),
      createAnswerOption('Try to broker peace yourself', 'broker', 15),
      createAnswerOption('Step back and let them sort it out', 'step_back'),
      createAnswerOption('Fight for what you believe is fair', 'fight', 10),
    ];
  }

  processAnswer(player: Player, selectedOption: number): EventResult {
    player.c.stress = modifyStat(player.c.stress, 20);

    if (selectedOption === 0) {
      // Mediator - fairest outcome
      player.money = Math.max(0, player.money - 1000);
      player.c.energy = modifyStat(player.c.energy, -10);

      scheduleFollowUp(
        player,
        `inheritanceDispute_resolution`,
        30,
        14,
        "The mediator helped the family reach a fair agreement. Not everyone got what they wanted, but the process was respectful. More importantly, the family is still speaking to each other."
      );

      return { type: 'messageEvent', message: "You suggested hiring a professional mediator. Some family members grumbled about the cost, but agreed it was better than destroying relationships over money.", moneyCost: 1000 };
    } else if (selectedOption === 1) {
      // Broker peace
      player.c.energy = modifyStat(player.c.energy, -15);

      const succeeds = Math.random() < 0.5;
      if (succeeds) {
        scheduleFollowUp(player, `inheritanceDispute_resolution`, 14, 14,
          "Your efforts to mediate the inheritance dispute paid off. You found compromises that everyone could live with. The family respects you for stepping up.");
      } else {
        scheduleFollowUp(player, `inheritanceDispute_resolution`, 14, 14,
          "Despite your best efforts, the inheritance dispute got ugly. Some family members said things they can't take back. It might be a while before everyone is on speaking terms.");
      }

      return { type: 'messageEvent', message: "You stepped in to mediate between family members. It's emotionally draining but someone has to be the voice of reason.", energyCost: 15 };
    } else if (selectedOption === 2) {
      // Step back
      scheduleFollowUp(player, `inheritanceDispute_resolution`, 30, 14,
        "The inheritance dispute resolved itself eventually, but not without casualties. Some family relationships are strained, possibly permanently. You wonder if you should have intervened.");

      return { type: 'messageEvent', message: "You decided to stay out of the inheritance dispute. It's not worth damaging relationships over money. At least, that's what you tell yourself." };
    } else {
      // Fight
      player.c.energy = modifyStat(player.c.energy, -10);

      // Might gain money but lose family
      for (const p of player.r ?? []) {
        const rels = p.relationships ?? [];
        if (p.status === 'alive' && (rels.includes('sibling') || rels.includes('brother') || rels.includes('sister'))) {
          p.affinity = modifyStat(p.affinity, -10, -100, 100);
        }
      }

      player.money += 5000;

      scheduleFollowUp(player, `inheritanceDispute_resolution`, 30, 14,
        "You got your share of the inheritance, but at a cost. Your siblings barely speak to you now. Money came, but the family dinner seat might stay empty for a while.");

      return { type: 'messageEvent', message: "You fought for what you believed was your fair share. The arguments were ugly, voices were raised, and some things were said that can't be unsaid. You inherited $5000." };
    }
  }
}

// =============================================================================
// Exports
// =============================================================================

export const parentGetsSickInstance = new ParentGetsSick();
export const siblingsWeddingInstance = new SiblingsWedding();
export const childMilestonesInstance = new ChildMilestones();
export const familySecretRevealedInstance = new FamilySecretRevealed();
export const familyReunionInstance = new FamilyReunion();
export const inheritanceDisputeInstance = new InheritanceDispute();

export const familyMilestoneClassEvents = [
  parentGetsSickInstance,
  siblingsWeddingInstance,
  childMilestonesInstance,
  familySecretRevealedInstance,
  familyReunionInstance,
  inheritanceDisputeInstance,
];
