/**
 * Career Milestone Events (Fast Mode)
 * Major career progression events for fast-forward gameplay (ages 18+).
 * Class-based events extending BaseEvent.
 *
 * Events:
 * - PerformanceReview: Quarterly review with multi-stage outcomes
 * - PromotionOffer: Promotion negotiation with tradeoffs
 * - GotPassedOver: Passed over for promotion, morale hit
 * - LayoffNotice: Multi-stage layoff (notice -> severance -> job search)
 * - CompetitorCounterOffer: Rival company recruits you
 * - StartOwnBusiness: Multi-stage entrepreneurship
 * - WorkplaceConflict: Serious conflict requiring resolution
 */

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

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

function isEmployed(player: Player): boolean {
  return player.character.occupation === 'work' && !!player.character.job;
}

function getJobTitle(player: Player): string {
  return player.character.job?.title ?? 'your company';
}

/**
 * Schedule a follow-up message via oneTimeEvents.
 */
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 });
}

// =============================================================================
// 1. Performance Review
// =============================================================================

/**
 * Quarterly performance review. Your rating depends on recent activity.
 * Outcomes range from "exceeds expectations" to "needs improvement"
 * with salary and happiness consequences.
 */
export class PerformanceReview extends BaseEvent {
  readonly id = 'performanceReview';

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

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

  checkConditions(player: Player): boolean {
    if (player.askedQuestions.has(this.id)) return false;
    if (!isEmployed(player)) return false;
    // Quarterly: months 3, 6, 9, 12
    const month = player.monthOfYear ?? 1;
    return month === 3 || month === 6 || month === 9 || month === 12;
  }

  getQuestion(player?: Player): string {
    const job = player ? getJobTitle(player) : 'your company';
    return `It's time for your quarterly performance review at ${job}. Your manager has scheduled a one-on-one. How do you prepare?`;
  }

  getAnswerOptions(): AnswerOption[] {
    return [
      createAnswerOption('Prepare a list of accomplishments', 'prepared', 5),
      createAnswerOption('Wing it — your work speaks for itself', 'wing'),
      createAnswerOption('Ask coworkers for feedback first', 'feedback', 3),
    ];
  }

  processAnswer(player: Player, selectedOption: number): EventResult {
    const c = player.c;
    const intelligence = c.intelligence ?? 50;
    const stress = c.stress ?? 20;

    // Performance score influenced by intelligence, stress, and preparation
    let performanceScore = intelligence * 0.4 + (100 - stress) * 0.3 + Math.random() * 30;

    // Preparation bonus
    if (selectedOption === 0) {
      performanceScore += 15;
      c.energy = modifyStat(c.energy, -5);
    } else if (selectedOption === 2) {
      performanceScore += 8;
      c.energy = modifyStat(c.energy, -3);
    }

    if (performanceScore >= 80) {
      // Exceeds expectations
      const raise = Math.floor((c.salary ?? 500) * 0.05);
      c.salary = (c.salary ?? 500) + raise;
      c.happiness = modifyStat(c.happiness, 10);
      c.stress = modifyStat(c.stress, -5);

      return {
        type: 'messageEvent',
        message: `Your performance review went great! Your manager said you "exceed expectations." You got a $${raise}/month raise and are being considered for more responsibility.`,
      };
    } else if (performanceScore >= 55) {
      // Meets expectations
      c.happiness = modifyStat(c.happiness, 3);

      return {
        type: 'messageEvent',
        message: `Your performance review was solid. "Meets expectations" across the board. No raise this quarter, but you're in good standing. Your manager suggested a couple areas to grow in.`,
      };
    } else {
      // Needs improvement
      c.happiness = modifyStat(c.happiness, -8);
      c.stress = modifyStat(c.stress, 10);

      scheduleFollowUp(
        player,
        `performanceReview_pip_${player.dayOfYear}`,
        30,
        10,
        `Your manager checks in on your improvement plan from last month's review. The pressure is real — you need to show progress or face consequences.`
      );

      return {
        type: 'messageEvent',
        message: `Your performance review didn't go well. "Needs improvement" in several areas. Your manager put you on a 30-day improvement plan. This is a wake-up call.`,
      };
    }
  }
}

// =============================================================================
// 2. Promotion Offer
// =============================================================================

/**
 * Your company offers you a promotion. More money but more responsibility.
 * Accept: salary +25%, stress +10, happiness +5
 * Negotiate: chance of better terms or insulting the offer
 * Decline: stay comfortable, miss the boat
 */
export class PromotionOffer extends BaseEvent {
  readonly id = 'promotionOffer';

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

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

  checkConditions(player: Player): boolean {
    if (player.askedQuestions.has(this.id)) return false;
    return isEmployed(player) && player.c.ageYears >= 22;
  }

  getQuestion(player?: Player): string {
    const job = player ? getJobTitle(player) : 'your company';
    return `Your manager at ${job} calls you into their office with good news: there's a senior position opening up and they want you for it. The role comes with a 25% raise but significantly more responsibility.`;
  }

  getAnswerOptions(): AnswerOption[] {
    return [
      createAnswerOption('Accept immediately', 'accept'),
      createAnswerOption('Negotiate for a bigger raise', 'negotiate', 5),
      createAnswerOption('Ask for time to think about it', 'think'),
      createAnswerOption('Decline — I like my current role', 'decline'),
    ];
  }

  processAnswer(player: Player, selectedOption: number): EventResult {
    const c = player.c;
    const currentSalary = c.salary ?? 500;

    if (selectedOption === 0) {
      // Accept
      const raise = Math.floor(currentSalary * 0.25);
      c.salary = currentSalary + raise;
      c.happiness = modifyStat(c.happiness, 5);
      c.stress = modifyStat(c.stress, 10);
      c.energy = modifyStat(c.energy, 10);
      player.lifecycleQueue.push({ type: 'promotion', data: { title: 'Senior Position' } });

      return {
        type: 'messageEvent',
        message: `Congratulations on the promotion! Your new salary is $${c.salary}/month. The workload is heavier but you feel validated. Time to prove yourself in the new role.`,
      };
    } else if (selectedOption === 1) {
      // Negotiate
      c.energy = modifyStat(c.energy, -5);

      if (Math.random() < 0.6) {
        // Negotiation success
        const raise = Math.floor(currentSalary * 0.35);
        c.salary = currentSalary + raise;
        c.happiness = modifyStat(c.happiness, 8);
        c.stress = modifyStat(c.stress, 8);
        player.lifecycleQueue.push({ type: 'promotion', data: { title: 'Senior Position' } });

        return {
          type: 'messageEvent',
          message: `Your negotiation paid off! They bumped the raise to 35%. New salary: $${c.salary}/month. Your manager respected that you know your worth.`,
        };
      } else {
        // Negotiation backfire — they give the original offer, take it or leave it
        const raise = Math.floor(currentSalary * 0.25);
        c.salary = currentSalary + raise;
        c.stress = modifyStat(c.stress, 12);
        player.lifecycleQueue.push({ type: 'promotion', data: { title: 'Senior Position' } });

        return {
          type: 'messageEvent',
          message: `Your negotiation didn't land well. "This is a fair offer and we'd hate to see it go to someone else." You accepted the original 25% raise. New salary: $${c.salary}/month.`,
        };
      }
    } else if (selectedOption === 2) {
      // Think about it — follow up in 3 days
      scheduleFollowUp(
        player,
        `promotionOffer_followup_${player.dayOfYear}`,
        3,
        10,
        `Your manager needs an answer about the promotion. You decide to accept. Your salary increases by 25% and you start your new role next week.`
      );
      const raise = Math.floor(currentSalary * 0.25);
      c.salary = currentSalary + raise;

      return {
        type: 'messageEvent',
        message: `You asked for a few days to think it over. Your manager seemed a little surprised but agreed. The clock is ticking.`,
      };
    } else {
      // Decline
      c.stress = modifyStat(c.stress, -5);

      scheduleFollowUp(
        player,
        `promotionOffer_regret_${player.dayOfYear}`,
        14,
        18,
        `The person who got the promotion you turned down seems to be thriving in the role. You wonder if you made the right call.`
      );

      return {
        type: 'messageEvent',
        message: `You politely declined the promotion. Your manager was surprised but respected your choice. "The offer won't stay open forever," they said.`,
      };
    }
  }
}

// =============================================================================
// 3. Got Passed Over
// =============================================================================

/**
 * Someone else got the promotion you deserved.
 * Confront: risky, could help or hurt
 * Refocus: channel frustration into performance
 * Start looking: open to new opportunities
 */
export class GotPassedOver extends BaseEvent {
  readonly id = 'gotPassedOver';

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

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

  checkConditions(player: Player): boolean {
    if (player.askedQuestions.has(this.id)) return false;
    return isEmployed(player) && player.c.ageYears >= 25;
  }

  getQuestion(player?: Player): string {
    const job = player ? getJobTitle(player) : 'your company';
    return `A coworker who started after you just got promoted to the position you've been eyeing at ${job}. You feel a sting of resentment. How do you handle it?`;
  }

  getAnswerOptions(): AnswerOption[] {
    return [
      createAnswerOption('Talk to your manager about it', 'confront', 5),
      createAnswerOption('Channel it into working harder', 'grind', 10),
      createAnswerOption('Start quietly job hunting', 'search'),
      createAnswerOption('Accept it and move on', 'accept'),
    ];
  }

  processAnswer(player: Player, selectedOption: number): EventResult {
    const c = player.c;

    if (selectedOption === 0) {
      // Confront manager
      c.energy = modifyStat(c.energy, -5);

      if (Math.random() < 0.5) {
        c.happiness = modifyStat(c.happiness, 3);
        return {
          type: 'messageEvent',
          message: `Your manager appreciated the honest conversation. They said you're next in line and outlined what you need to do. It felt good to advocate for yourself.`,
        };
      } else {
        c.happiness = modifyStat(c.happiness, -5);
        c.stress = modifyStat(c.stress, 8);
        return {
          type: 'messageEvent',
          message: `Your manager got defensive and said the decision was final. "Trust the process." You left the meeting feeling worse than before.`,
        };
      }
    } else if (selectedOption === 1) {
      // Grind harder
      c.energy = modifyStat(c.energy, -10);
      c.stress = modifyStat(c.stress, 8);
      c.intelligence = modifyStat(c.intelligence, 3);

      scheduleFollowUp(
        player,
        `passedOver_grind_${player.dayOfYear}`,
        30,
        10,
        `Your extra effort at work is getting noticed. Your manager mentioned you as a "top performer" in the last team meeting. The grind is paying off.`
      );

      return {
        type: 'messageEvent',
        message: `You channeled your frustration into your work. Extra hours, better output, visible results. It's exhausting but you're determined to make them regret passing you over.`,
        energyCost: 10,
      };
    } else if (selectedOption === 2) {
      // Job hunt
      c.happiness = modifyStat(c.happiness, -3);

      scheduleFollowUp(
        player,
        `passedOver_search_${player.dayOfYear}`,
        21,
        19,
        `Your job search is picking up. You've had a couple of phone interviews and one company wants to bring you in for a final round. Things are looking up.`
      );

      return {
        type: 'messageEvent',
        message: `You updated your resume and started browsing job listings. It feels scary but also exciting. Maybe it's time for a fresh start somewhere that values you.`,
      };
    } else {
      // Accept
      c.happiness = modifyStat(c.happiness, -5);

      return {
        type: 'messageEvent',
        message: `You swallowed your pride and congratulated your coworker. It stung, but sometimes that's how it goes. You'll get your chance.`,
      };
    }
  }
}

// =============================================================================
// 4. Layoff Notice
// =============================================================================

/**
 * Multi-stage layoff event.
 * Stage 1: You hear rumors, then get called to HR.
 * Outcome varies by choice: negotiate severance, fight it, or accept gracefully.
 * Follow-up: job search consequences 2 weeks later.
 */
export class LayoffNotice extends BaseEvent {
  readonly id = 'layoffNotice';

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

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

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

  getQuestion(player?: Player): string {
    const job = player ? getJobTitle(player) : 'your company';
    return `HR just called you into a meeting at ${job}. "Due to restructuring, your position is being eliminated." Your stomach drops. How do you respond?`;
  }

  getAnswerOptions(): AnswerOption[] {
    return [
      createAnswerOption('Negotiate a severance package', 'negotiate', 5),
      createAnswerOption('Ask if there are other positions available', 'internal'),
      createAnswerOption('Accept it gracefully', 'accept'),
      createAnswerOption('Fight it — this isn\'t fair', 'fight', 10),
    ];
  }

  processAnswer(player: Player, selectedOption: number): EventResult {
    const c = player.c;
    const salary = c.salary ?? 500;

    // Everyone loses their job
    c.occupation = 'unemployed';
    c.job = undefined;
    c.happiness = modifyStat(c.happiness, -15);
    c.stress = modifyStat(c.stress, 20);
    player.lifecycleQueue.push({ type: 'fired' });

    if (selectedOption === 0) {
      // Negotiate severance
      const severance = salary * 3;
      player.money += severance;
      c.energy = modifyStat(c.energy, -5);

      scheduleFollowUp(
        player,
        `layoff_search_${player.dayOfYear}`,
        14,
        10,
        `Two weeks after the layoff, you've started applying for jobs. The severance gives you breathing room, but the rejection emails are piling up. Stay strong.`
      );

      return {
        type: 'messageEvent',
        message: `You negotiated a 3-month severance package worth $${severance}. It's not much comfort, but it buys you time to find something new.`,
      };
    } else if (selectedOption === 1) {
      // Look for internal transfer
      if (Math.random() < 0.3) {
        // Lucky — found an internal spot
        c.occupation = 'work';
        c.happiness = modifyStat(c.happiness, 10); // partial recovery
        c.stress = modifyStat(c.stress, -10);
        const newSalary = Math.floor(salary * 0.85);
        c.salary = newSalary;
        c.job = { ...player.character.job, title: 'Internal Transfer' };

        return {
          type: 'messageEvent',
          message: `HR found an opening in another department. It's a lateral move with a small pay cut to $${newSalary}/month, but at least you still have a job. It feels like a second chance.`,
        };
      } else {
        scheduleFollowUp(
          player,
          `layoff_search_${player.dayOfYear}`,
          14,
          10,
          `No internal positions opened up. You're officially job hunting now. It's a humbling experience but you're determined.`
        );

        return {
          type: 'messageEvent',
          message: `HR checked but there are no internal openings right now. They gave you a standard two-week severance and wished you well. The search begins.`,
        };
      }
    } else if (selectedOption === 2) {
      // Accept gracefully
      const severance = salary * 2;
      player.money += severance;

      scheduleFollowUp(
        player,
        `layoff_search_${player.dayOfYear}`,
        14,
        10,
        `Two weeks out from the layoff. You've gotten a couple of interviews lined up. Your former coworkers have been sharing your resume around — your graceful exit made an impression.`
      );

      return {
        type: 'messageEvent',
        message: `You shook hands, packed your desk, and left with dignity. The standard severance of $${severance} will help. Your coworkers were sad to see you go.`,
      };
    } else {
      // Fight it
      c.energy = modifyStat(c.energy, -10);
      c.stress = modifyStat(c.stress, 10);
      const severance = Math.floor(salary * 1.5);
      player.money += severance;

      scheduleFollowUp(
        player,
        `layoff_search_${player.dayOfYear}`,
        14,
        10,
        `The fight didn't change anything. You're job hunting now, and the experience left a bad taste. But you've been reaching out to your network and a few leads are promising.`
      );

      return {
        type: 'messageEvent',
        message: `You argued your case but the decision was made above your manager's head. After a tense exchange, you got a smaller severance of $${severance} and a cold goodbye.`,
        energyCost: 10,
      };
    }
  }
}

// =============================================================================
// 5. Competitor Counter-Offer
// =============================================================================

/**
 * A competing company reaches out with an offer.
 * Jump ship: new job, higher salary, but risk (new environment)
 * Use it as leverage: negotiate raise at current job
 * Decline: loyalty, but is it rewarded?
 */
export class CompetitorCounterOffer extends BaseEvent {
  readonly id = 'competitorCounterOffer';

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

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

  checkConditions(player: Player): boolean {
    if (player.askedQuestions.has(this.id)) return false;
    return isEmployed(player) && player.c.ageYears >= 25;
  }

  getQuestion(player?: Player): string {
    const salary = player?.c.salary ?? 500;
    const offerAmount = Math.floor(salary * 1.3);
    return `A recruiter from a competitor reaches out on LinkedIn: "We'd love to have you. We're offering $${offerAmount}/month — 30% more than what you're making." What do you do?`;
  }

  getAnswerOptions(): AnswerOption[] {
    return [
      createAnswerOption('Take the new job', 'jump'),
      createAnswerOption('Use it to negotiate a raise here', 'leverage', 5),
      createAnswerOption('Decline — I\'m happy where I am', 'stay'),
    ];
  }

  processAnswer(player: Player, selectedOption: number): EventResult {
    const c = player.c;
    const currentSalary = c.salary ?? 500;

    if (selectedOption === 0) {
      // Jump ship
      const newSalary = Math.floor(currentSalary * 1.3);
      c.salary = newSalary;
      c.happiness = modifyStat(c.happiness, 5);
      c.stress = modifyStat(c.stress, 15); // new job stress
      player.lifecycleQueue.push({ type: 'job_obtained' });

      scheduleFollowUp(
        player,
        `newJob_adjust_${player.dayOfYear}`,
        30,
        12,
        `A month into your new job. The pay is better but you're still finding your footing. The team is different, the culture is different. Give it time.`
      );

      return {
        type: 'messageEvent',
        message: `You accepted the offer and put in your two weeks. Your old boss was disappointed. New salary: $${newSalary}/month. Fresh start, fresh challenges.`,
      };
    } else if (selectedOption === 1) {
      // Use as leverage
      c.energy = modifyStat(c.energy, -5);

      if (Math.random() < 0.55) {
        // Raise!
        const raise = Math.floor(currentSalary * 0.2);
        c.salary = currentSalary + raise;
        c.happiness = modifyStat(c.happiness, 5);

        return {
          type: 'messageEvent',
          message: `You told your manager about the offer. After some back and forth, they matched with a 20% raise to $${c.salary}/month. "We don't want to lose you."`,
        };
      } else {
        // Backfire
        c.stress = modifyStat(c.stress, 10);

        return {
          type: 'messageEvent',
          message: `Your manager didn't take it well. "If you want to leave, we won't stop you." No raise, and now there's tension. You decide to stay for now, but the relationship is strained.`,
        };
      }
    } else {
      // Stay loyal
      c.happiness = modifyStat(c.happiness, 2);

      return {
        type: 'messageEvent',
        message: `You politely declined the recruiter. You're happy where you are and the grass isn't always greener. Sometimes stability is worth more than a bigger paycheck.`,
      };
    }
  }
}

// =============================================================================
// 6. Start Own Business
// =============================================================================

/**
 * Multi-stage entrepreneurship event.
 * Stage 1: The idea — quit your job and pursue it?
 * Follow-up: Business outcome (success/struggle) after 60 days.
 */
export class StartOwnBusiness extends BaseEvent {
  readonly id = 'startOwnBusiness';

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

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

  checkConditions(player: Player): boolean {
    if (player.askedQuestions.has(this.id)) return false;
    if (player.c.ownsBusiness) return false;
    return isEmployed(player) && player.money >= 5000 && player.c.ageYears >= 25;
  }

  getQuestion(_player?: Player): string {
    return `You've had a business idea brewing for months. You've done the research, the numbers look promising, but it would mean quitting your stable job and investing your savings. Are you ready to take the leap?`;
  }

  getAnswerOptions(): AnswerOption[] {
    return [
      createAnswerOption('Quit and go all in ($10,000)', 'allin', 10, 0, 10000),
      createAnswerOption('Start it as a side hustle first', 'side', 15),
      createAnswerOption('Too risky — keep the day job', 'stay'),
    ];
  }

  processAnswer(player: Player, selectedOption: number): EventResult {
    const c = player.c;

    if (selectedOption === 0) {
      // All in
      player.money = Math.max(0, player.money - 10000);
      c.occupation = 'work';
      c.ownsBusiness = true;
      c.job = { id: 'own_business', title: 'Business Owner', levels: [{ level: 'Founder', salary: 0 }], requirements: 'none' };
      c.salary = 0; // No salary initially
      c.happiness = modifyStat(c.happiness, 5);
      c.stress = modifyStat(c.stress, 20);
      c.energy = modifyStat(c.energy, -10);

      // Business outcome in ~60 days
      const succeeds = Math.random() < 0.4;
      if (succeeds) {
        scheduleFollowUp(
          player,
          `business_outcome_${player.dayOfYear}`,
          60,
          10,
          `Your business is turning a profit! After two grueling months, customers are coming in and revenue is growing. You set your salary to $800/month. The risk is paying off.`
        );
      } else {
        scheduleFollowUp(
          player,
          `business_outcome_${player.dayOfYear}`,
          60,
          10,
          `Your business is struggling. Costs are higher than expected and customers are slow to arrive. You're burning through savings. You might need to find additional income or cut costs drastically.`
        );
      }

      return {
        type: 'messageEvent',
        message: `You handed in your resignation and invested $10,000 into your dream. No safety net. The first month will be the hardest, but you've never felt more alive — or more terrified.`,
        moneyCost: 10000,
        energyCost: 10,
      };
    } else if (selectedOption === 1) {
      // Side hustle
      c.energy = modifyStat(c.energy, -15);
      c.stress = modifyStat(c.stress, 10);

      scheduleFollowUp(
        player,
        `sidehustle_progress_${player.dayOfYear}`,
        45,
        19,
        `Your side hustle is making a little money — about $200/month. It's not enough to quit your day job, but it's real. The question is whether you can sustain both.`
      );

      return {
        type: 'messageEvent',
        message: `You decided to build it on the side. Nights and weekends are now dedicated to your business while keeping the safety of a paycheck. It's exhausting, but smart.`,
        energyCost: 15,
      };
    } else {
      // Stay safe
      c.stress = modifyStat(c.stress, -3);

      return {
        type: 'messageEvent',
        message: `You shelved the idea for now. The timing isn't right, and there's nothing wrong with a steady paycheck. Maybe someday.`,
      };
    }
  }
}

// =============================================================================
// 7. Workplace Conflict
// =============================================================================

/**
 * A serious conflict with a coworker escalates.
 * Mediate: diplomatic, restores peace
 * Escalate to HR: formal route, mixed outcomes
 * Ignore it: conflict festers
 */
export class WorkplaceConflict extends BaseEvent {
  readonly id = 'workplaceConflict';

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

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

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

  getQuestion(_player?: Player): string {
    const causes = [
      'A coworker took credit for your work in a big presentation.',
      'A coworker has been making snide comments about you in meetings.',
      'You caught a coworker throwing you under the bus in an email to the boss.',
      'A coworker keeps undermining your decisions in front of the team.',
    ];
    return causes[Math.floor(Math.random() * causes.length)] + ' How do you handle it?';
  }

  getAnswerOptions(): AnswerOption[] {
    return [
      createAnswerOption('Talk to them privately', 'private', 5),
      createAnswerOption('Escalate to HR', 'hr', 3),
      createAnswerOption('Let it go this time', 'ignore'),
      createAnswerOption('Confront them publicly', 'public', 8),
    ];
  }

  processAnswer(player: Player, selectedOption: number): EventResult {
    const c = player.c;

    if (selectedOption === 0) {
      // Private conversation
      c.energy = modifyStat(c.energy, -5);

      if (Math.random() < 0.65) {
        c.happiness = modifyStat(c.happiness, 3);
        c.social = modifyStat(c.social, 3);
        return {
          type: 'messageEvent',
          message: `The private conversation went better than expected. They apologized and admitted they were stressed. You set boundaries and the air feels cleared.`,
          energyCost: 5,
        };
      } else {
        c.stress = modifyStat(c.stress, 8);
        return {
          type: 'messageEvent',
          message: `The conversation got heated. They denied everything and accused you of being too sensitive. The tension at work just got worse.`,
          energyCost: 5,
        };
      }
    } else if (selectedOption === 1) {
      // HR route
      c.energy = modifyStat(c.energy, -3);
      c.stress = modifyStat(c.stress, 5);

      scheduleFollowUp(
        player,
        `hrConflict_outcome_${player.dayOfYear}`,
        7,
        14,
        `HR concluded their investigation. The coworker received a formal warning. Things are awkward now, but at least there's a paper trail. Your manager thanked you for handling it properly.`
      );

      return {
        type: 'messageEvent',
        message: `You filed a formal complaint with HR. They're taking it seriously and scheduling mediation. It feels official and a bit scary, but sometimes you need to go through channels.`,
        energyCost: 3,
      };
    } else if (selectedOption === 2) {
      // Ignore
      c.happiness = modifyStat(c.happiness, -5);
      c.stress = modifyStat(c.stress, 8);

      scheduleFollowUp(
        player,
        `conflict_festers_${player.dayOfYear}`,
        14,
        16,
        `The situation with your coworker hasn't improved. In fact, it's gotten worse. Other people are starting to notice the tension. You might need to address it soon.`
      );

      return {
        type: 'messageEvent',
        message: `You decided to let it go and focus on your work. But every time you see them in a meeting, the resentment builds a little more.`,
      };
    } else {
      // Public confrontation
      c.energy = modifyStat(c.energy, -8);

      if (Math.random() < 0.3) {
        // Bold move pays off
        c.happiness = modifyStat(c.happiness, 5);
        return {
          type: 'messageEvent',
          message: `You called them out in the meeting. Bold move. The room went silent, then your manager backed you up. The coworker was embarrassed but got the message.`,
          energyCost: 8,
        };
      } else {
        // Looks bad
        c.happiness = modifyStat(c.happiness, -8);
        c.social = modifyStat(c.social, -5);
        c.stress = modifyStat(c.stress, 10);
        return {
          type: 'messageEvent',
          message: `You confronted them in front of everyone. It got ugly fast. Your manager pulled you aside afterward and said you need to "handle things more professionally." Not your best moment.`,
          energyCost: 8,
        };
      }
    }
  }
}

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

export const performanceReviewInstance = new PerformanceReview();
export const promotionOfferInstance = new PromotionOffer();
export const gotPassedOverInstance = new GotPassedOver();
export const layoffNoticeInstance = new LayoffNotice();
export const competitorCounterOfferInstance = new CompetitorCounterOffer();
export const startOwnBusinessInstance = new StartOwnBusiness();
export const workplaceConflictInstance = new WorkplaceConflict();

export const careerMilestoneClassEvents = [
  performanceReviewInstance,
  promotionOfferInstance,
  gotPassedOverInstance,
  layoffNoticeInstance,
  competitorCounterOfferInstance,
  startOwnBusinessInstance,
  workplaceConflictInstance,
];
