/**
 * Workplace Events (Realtime)
 * Small daily workplace moments that make career life feel alive (ages 18+).
 * Function-based events checked each hour during realtime play.
 *
 * Events:
 * - coffeeMachineChat: Break room small talk with coworker
 * - bossStressed: Boss having a bad day, ripple effects
 * - lunchInvitation: Coworker invites you to lunch
 * - deadlinePressure: Crunch time on a project
 * - officeBirthday: Chip in for office birthday celebration
 * - coworkerAskingHelp: Colleague needs help with their work
 * - parkingLotConversation: End-of-day chat reveals office intel
 */

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

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

/** Player must be employed with an active job */
function isEmployed(player: Player): boolean {
  return (
    player.character.occupation === 'work' &&
    !!player.character.job
  );
}

/** Only fire during working hours (9-17) on weekdays */
function isDuringWorkHours(player: Player): boolean {
  return !player.weekend && player.hourOfDay >= 9 && player.hourOfDay <= 17;
}

// =============================================================================
// 1. Coffee Machine Chat
// =============================================================================

/**
 * Break room encounter. A coworker chats you up by the coffee machine.
 * Engage: energy -3, happiness +2, social +2
 * Brush off: no cost but slight social penalty
 */
export function coffeeMachineChat(player: Player, _type: string = 'check'): EventResult {
  const fname = 'coffeeMachineChat';

  const check =
    !player.events.has(fname) &&
    isEmployed(player) &&
    isDuringWorkHours(player) &&
    player.hourOfDay >= 9 && player.hourOfDay <= 11 &&
    checkProbability(6000);

  if (!check) return null;

  const topics = [
    'the weekend',
    'that new show everyone is watching',
    'the terrible office coffee',
    'the parking situation',
    'their kid\'s soccer game',
  ];
  const topic = topics[Math.floor(Math.random() * topics.length)];

  return createQuestionEvent(
    fname,
    `You run into a coworker at the coffee machine. They want to chat about ${topic}. You're kind of busy...`,
    player,
    true,
    {
      answerOptions: [
        createAnswerOption('Chat for a bit', 'chat', 3),
        createAnswerOption('Grab your coffee and go', 'go'),
      ],
    }
  );
}

// =============================================================================
// 2. Boss Stressed
// =============================================================================

/**
 * Your boss is having a bad day and it's affecting the whole office.
 * Help out: energy -8, stress +5, but boss remembers (+performance)
 * Lay low: no cost, but miss a chance to impress
 * Crack a joke: risky — either eases tension or backfires
 */
export function bossStressed(player: Player, _type: string = 'check'): EventResult {
  const fname = 'bossStressed';

  const check =
    !player.events.has(fname) &&
    isEmployed(player) &&
    isDuringWorkHours(player) &&
    checkProbability(7000);

  if (!check) return null;

  const reasons = [
    'a client complaint',
    'a missed deadline from another team',
    'budget cuts from upper management',
    'a system outage',
  ];
  const reason = reasons[Math.floor(Math.random() * reasons.length)];

  return createQuestionEvent(
    fname,
    `Your boss is visibly stressed about ${reason}. The whole office is walking on eggshells. What do you do?`,
    player,
    true,
    {
      answerOptions: [
        createAnswerOption('Offer to help with extra tasks', 'help', 8),
        createAnswerOption('Keep your head down', 'hide'),
        createAnswerOption('Try to lighten the mood', 'joke', 3),
      ],
    }
  );
}

// =============================================================================
// 3. Lunch Invitation
// =============================================================================

/**
 * A coworker invites you out for lunch instead of eating at your desk.
 * Go out: energy -5, money -$12, happiness +3, social +3
 * Pack lunch: save money, miss bonding
 * Skip lunch: save time but energy drops
 */
export function lunchInvitation(player: Player, _type: string = 'check'): EventResult {
  const fname = 'lunchInvitation';

  const check =
    !player.events.has(fname) &&
    isEmployed(player) &&
    isDuringWorkHours(player) &&
    player.hourOfDay >= 11 && player.hourOfDay <= 13 &&
    checkProbability(5000);

  if (!check) return null;

  const places = [
    'the new Thai place',
    'the burger joint around the corner',
    'the taco truck outside',
    'that Italian spot everyone raves about',
  ];
  const place = places[Math.floor(Math.random() * places.length)];

  return createQuestionEvent(
    fname,
    `A coworker swings by your desk: "A few of us are heading to ${place} for lunch. You in?"`,
    player,
    true,
    {
      answerOptions: [
        createAnswerOption(`Join them ($12)`, 'join', 5, 0, 12),
        createAnswerOption('Eat the lunch I packed', 'packed'),
        createAnswerOption('Skip lunch and keep working', 'skip', 5),
      ],
    }
  );
}

// =============================================================================
// 4. Deadline Pressure
// =============================================================================

/**
 * A big project deadline is tomorrow and you're behind.
 * Stay late: energy -20, stress +10, but performance boost
 * Ask for help: energy -10, social cost (owe a favor)
 * Wing it: risky — might be fine or might get called out
 */
export function deadlinePressure(player: Player, _type: string = 'check'): EventResult {
  const fname = 'deadlinePressure';

  const check =
    !player.events.has(fname) &&
    isEmployed(player) &&
    isDuringWorkHours(player) &&
    player.hourOfDay >= 14 && player.hourOfDay <= 17 &&
    checkProbability(8000);

  if (!check) return null;

  return createQuestionEvent(
    fname,
    "Your project deadline is tomorrow and you're way behind. Your boss just asked for a status update. What's your move?",
    player,
    true,
    {
      answerOptions: [
        createAnswerOption('Stay late and grind it out', 'grind', 20),
        createAnswerOption('Ask a coworker to help', 'help', 10),
        createAnswerOption('Submit what you have and hope for the best', 'wing'),
        createAnswerOption('Ask for a deadline extension', 'extend', 5),
      ],
    }
  );
}

// =============================================================================
// 5. Office Birthday
// =============================================================================

/**
 * It's someone's birthday at the office. Chip in for cake?
 * Chip in: money -$10, social +2, happiness +2
 * Just eat cake: social -1 (freeloader vibes)
 * Skip it: no cost, no benefit
 */
export function officeBirthday(player: Player, _type: string = 'check'): EventResult {
  const fname = 'officeBirthday';

  const check =
    !player.events.has(fname) &&
    isEmployed(player) &&
    isDuringWorkHours(player) &&
    checkProbability(5000);

  if (!check) return null;

  return createQuestionEvent(
    fname,
    "Someone's going around collecting $10 for a coworker's birthday cake and card. The whole team is signing it.",
    player,
    true,
    {
      answerOptions: [
        createAnswerOption('Chip in and sign the card ($10)', 'chip', 0, 0, 10),
        createAnswerOption('Sign the card but skip the money', 'sign'),
        createAnswerOption('Just show up for cake', 'cake'),
        createAnswerOption('Skip the party entirely', 'skip'),
      ],
    }
  );
}

// =============================================================================
// 6. Coworker Asking Help
// =============================================================================

/**
 * A coworker is stuck on something and asks you to help.
 * Help fully: energy -10, their affinity +5, your work falls behind
 * Quick pointer: energy -3, small social boost
 * Decline: no cost but reputation hit
 */
export function coworkerAskingHelp(player: Player, _type: string = 'check'): EventResult {
  const fname = 'coworkerAskingHelp';

  const check =
    !player.events.has(fname) &&
    isEmployed(player) &&
    isDuringWorkHours(player) &&
    checkProbability(6000);

  if (!check) return null;

  const tasks = [
    'a spreadsheet formula that isn\'t working',
    'a presentation that needs polishing',
    'a report they can\'t figure out',
    'an email they need help phrasing',
    'a software tool they don\'t understand',
  ];
  const task = tasks[Math.floor(Math.random() * tasks.length)];

  return createQuestionEvent(
    fname,
    `A coworker stops by looking flustered: "Hey, do you have a minute? I'm stuck on ${task}."`,
    player,
    true,
    {
      answerOptions: [
        createAnswerOption('Sure, let me take a look', 'help', 10),
        createAnswerOption('Give a quick pointer', 'quick', 3),
        createAnswerOption('Sorry, I\'m swamped right now', 'decline'),
      ],
    }
  );
}

// =============================================================================
// 7. Parking Lot Conversation
// =============================================================================

/**
 * End-of-day chat in the parking lot reveals office intel or bonding.
 * Stay and chat: energy -3, social +2, chance of useful info
 * Wave and go: nothing
 */
export function parkingLotConversation(player: Player, _type: string = 'check'): EventResult {
  const fname = 'parkingLotConversation';

  const check =
    !player.events.has(fname) &&
    isEmployed(player) &&
    !player.weekend &&
    player.hourOfDay >= 17 && player.hourOfDay <= 18 &&
    checkProbability(6000);

  if (!check) return null;

  const gossip = [
    'mentions that layoffs might be coming',
    'says the company is about to land a huge client',
    'complains about the new policy changes',
    'hints that your team lead is leaving',
    'shares a tip about an open position in a better department',
  ];
  const tidbit = gossip[Math.floor(Math.random() * gossip.length)];

  return createQuestionEvent(
    fname,
    `As you're heading to your car, a coworker catches you in the parking lot and ${tidbit}. Do you stick around?`,
    player,
    true,
    {
      answerOptions: [
        createAnswerOption('Stay and hear more', 'stay', 3),
        createAnswerOption('Wave goodbye and head home', 'go'),
      ],
    }
  );
}

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

export const workplaceEvents = {
  coffeeMachineChat,
  bossStressed,
  lunchInvitation,
  deadlinePressure,
  officeBirthday,
  coworkerAskingHelp,
  parkingLotConversation,
};
