/**
 * Daily Disruptions and Random Events
 *
 * Random disruptions that make daily life feel varied (1-2 per week).
 * Each has real gameplay tradeoffs affecting time, money, or stats.
 *
 * Events:
 * - carWontStart: Car trouble, repair choice (money vs time)
 * - foundMoneyOnGround: Lucky find (small money gain)
 * - surpriseVisitor: Unexpected guest (energy vs social)
 * - doctorAppointment: Mandatory health check (time cost, health benefit)
 * - snowDay: School/work cancelled (happiness boost, schedule disruption)
 * - powerOutage: No electricity (productivity loss, boredom)
 * - flatTire: Tire blowout (money or energy cost)
 *
 * Sleep quality events:
 * - nightmareEvent: Bad dreams from low happiness
 * - greatSleepEvent: Restful sleep from exercise
 * - insomniaEvent: Can't sleep with high energy at bedtime
 */

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

// =============================================================================
// Random Disruptions (1-2 per week, function-based)
// =============================================================================

/**
 * Car won't start - repair choice
 * Requires driving age (16+), has car implied by canDrive
 */
export function carWontStart(player: Player, _type: string = 'check'): EventResult {
  const fname = 'carWontStart';
  const check =
    !player.events.has(fname) &&
    player.c.ageYears >= 16 &&
    player.c.canDrive &&
    checkProbability(5000);

  if (!check) return null;

  return createQuestionEvent(
    fname,
    'You turn the key and... nothing. Your car won\'t start. What do you do?',
    player,
    true,
    {
      answerOptions: [
        createAnswerOption('Call a mechanic ($120)', 'mechanic', 0, 0, 120),
        createAnswerOption('Try to fix it yourself', 'diy', 20),
        createAnswerOption('Take the bus today', 'bus', 5, 0, 3),
      ],
    }
  );
}

/**
 * Found money on ground - small lucky event
 */
export function foundMoneyGround(player: Player, _type: string = 'check'): EventResult {
  const fname = 'foundMoneyGround';
  const amount = Math.floor(Math.random() * 4 + 1) * 5; // $5-$20

  const check =
    !player.events.has(fname) &&
    player.c.ageYears >= 5 &&
    checkProbability(6000);

  if (check) {
    player.events.add(fname);
    player.money += amount;
    player.c.happiness = modifyStat(player.c.happiness, 3);
  }

  const foundMoneyVariants = [
    `You found $${amount} on the ground! It's your lucky day.`,
    `Look at that — $${amount} just lying on the sidewalk. Finders keepers!`,
    `You spotted $${amount} tucked under a bench. A small win for the day.`,
  ];

  return createMessageEvent(
    fname,
    pickVariant(foundMoneyVariants),
    player,
    check,
    { moneyCost: -amount }
  );
}

/**
 * Surprise visitor shows up
 * Social boost but energy drain
 */
export function surpriseVisitor(player: Player, _type: string = 'check'): EventResult {
  const fname = 'surpriseVisitor';
  const check =
    !player.events.has(fname) &&
    player.c.ageYears >= 10 &&
    checkProbability(6000);

  if (!check) return null;

  // Pick a random relationship as the visitor
  const visitors = (player.r ?? []).filter((p) => p.status === 'alive' && (p.affinity ?? 0) > 10);
  const visitor = visitors.length > 0
    ? visitors[Math.floor(Math.random() * visitors.length)]
    : null;

  const visitorName = visitor?.firstname ?? 'A neighbor';

  return createQuestionEvent(
    fname,
    `${visitorName} shows up at your door unexpectedly. "Hey! I was in the neighborhood and thought I'd drop by!"`,
    player,
    true,
    {
      answerOptions: [
        createAnswerOption('Welcome them in!', 'welcome', 15),
        createAnswerOption('Chat briefly at the door', 'brief', 5),
        createAnswerOption('Pretend you\'re not home', 'hide'),
      ],
      characters: visitor
        ? [{ id: visitor.id, firstname: visitor.firstname, lastname: visitor.lastname, image: visitor.image }]
        : [],
    }
  );
}

/**
 * Doctor appointment reminder
 * Time/energy cost but health benefit
 */
export function doctorAppointment(player: Player, _type: string = 'check'): EventResult {
  const fname = 'doctorAppointment';
  const check =
    !player.events.has(fname) &&
    player.c.ageYears >= 5 &&
    checkProbability(8000);

  if (!check) return null;

  return createQuestionEvent(
    fname,
    'You have a routine doctor\'s appointment today. It\'s been a while since your last check-up.',
    player,
    true,
    {
      answerOptions: [
        createAnswerOption('Go to the appointment', 'go', 10, 0, 30),
        createAnswerOption('Reschedule for later', 'reschedule'),
        createAnswerOption('Skip it entirely', 'skip'),
      ],
    }
  );
}

/**
 * Snow day - school/work cancelled
 * Only triggers in winter months
 */
export function snowDay(player: Player, _type: string = 'check'): EventResult {
  const fname = 'snowDay';
  const weather = (player as any).weather as string | undefined;

  const check =
    !player.events.has(fname) &&
    player.season === 'winter' &&
    (weather === 'snowy' || weather === 'stormy') &&
    checkProbability(3000);

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

  const isStudent = player.c.occupation === 'student';
  const studentSnowDayVariants = [
    'Snow day! School is cancelled due to heavy snowfall. Time to build a snowman!',
    'No school today! The snow is too deep for buses. You rush to get dressed for the snow.',
    'The school called — classes are cancelled! You peer out the window at a winter wonderland.',
  ];
  const adultSnowDayVariants = [
    'Heavy snowfall means many businesses are closed. You get an unexpected day off!',
    'The roads are impassable. Your boss texts: "Work from home today, stay safe."',
    'Everything is shut down by the snow. You get a rare, unplanned day to yourself.',
  ];
  const message = pickVariant(isStudent ? studentSnowDayVariants : adultSnowDayVariants);

  return createMessageEvent(fname, message, player, check);
}

/**
 * Power outage
 * Boredom and productivity loss, but chance for family bonding
 */
export function powerOutage(player: Player, _type: string = 'check'): EventResult {
  const fname = 'powerOutage';
  const check =
    !player.events.has(fname) &&
    player.c.ageYears >= 5 &&
    checkProbability(7000);

  if (!check) return null;

  return createQuestionEvent(
    fname,
    'The power just went out! Looks like it might be a while before it comes back. What do you do?',
    player,
    true,
    {
      answerOptions: [
        createAnswerOption('Light candles and read a book', 'read'),
        createAnswerOption('Play board games with the family', 'games', 10),
        createAnswerOption('Just go to bed early', 'sleep'),
        createAnswerOption('Go out somewhere with power', 'leave', 10, 0, 15),
      ],
    }
  );
}

/**
 * Flat tire event
 * Money or energy cost depending on choice
 */
export function flatTire(player: Player, _type: string = 'check'): EventResult {
  const fname = 'flatTire';
  const check =
    !player.events.has(fname) &&
    player.c.ageYears >= 16 &&
    player.c.canDrive &&
    checkProbability(7000);

  if (!check) return null;

  return createQuestionEvent(
    fname,
    'You hear a loud pop and your car starts pulling to one side. You\'ve got a flat tire!',
    player,
    true,
    {
      answerOptions: [
        createAnswerOption('Change it yourself', 'diy', 20),
        createAnswerOption('Call roadside assistance ($60)', 'call', 0, 0, 60),
        createAnswerOption('Call a friend for help', 'friend', 5),
      ],
    }
  );
}

// =============================================================================
// Sleep Quality Events
// =============================================================================

/**
 * Nightmare event - triggered by low happiness
 * Reduces energy restoration overnight
 */
export function nightmareEvent(player: Player, _type: string = 'check'): EventResult {
  const fname = 'nightmareEvent';
  const check =
    !player.events.has(fname) &&
    player.c.ageYears >= 3 &&
    (player.c.happiness ?? 50) < 30 &&
    player.hourOfDay >= 22 &&
    checkProbability(3000);

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

  const nightmareVariants = [
    'You had a terrible nightmare and woke up in a cold sweat. You couldn\'t fall back asleep for hours.',
    'You jolted awake from a vivid nightmare. Your heart was pounding and sleep wouldn\'t come back.',
    'A bad dream startled you awake in the middle of the night. You lay there staring at the ceiling for hours.',
  ];

  return createMessageEvent(
    fname,
    pickVariant(nightmareVariants),
    player,
    check,
    { energyCost: 10 }
  );
}

/**
 * Great sleep event - triggered when recently exercised
 * Bonus energy restoration
 */
export function greatSleepEvent(player: Player, _type: string = 'check'): EventResult {
  const fname = 'greatSleepEvent';

  // Check if player has physical activities (implies exercise)
  const hasExercise = (player.c.activities ?? []).some(
    (a: any) => a.type === 'physical' || a.type === 'extracurricular'
  );

  const check =
    !player.events.has(fname) &&
    hasExercise &&
    player.hourOfDay >= 6 && player.hourOfDay <= 8 &&
    checkProbability(4000);

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

  const greatSleepVariants = [
    'You slept amazingly well last night! Must be all that exercise paying off. You feel refreshed and ready to take on the day.',
    'You woke up feeling fantastic — deeply rested and full of energy. That workout really helped.',
    'Best sleep in weeks! You practically bounced out of bed this morning.',
  ];

  return createMessageEvent(
    fname,
    pickVariant(greatSleepVariants),
    player,
    check,
    { energyCost: -15 }
  );
}

/**
 * Insomnia event - triggered by high energy at bedtime
 */
export function insomniaEvent(player: Player, _type: string = 'check'): EventResult {
  const fname = 'insomniaEvent';
  const check =
    !player.events.has(fname) &&
    player.c.ageYears >= 10 &&
    (player.c.energy ?? 100) > 80 &&
    (player.c.stress ?? 0) > 40 &&
    player.hourOfDay >= 23 &&
    checkProbability(3000);

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

  const insomniaVariants = [
    'You tossed and turned all night. Your mind just wouldn\'t shut off. You\'re exhausted but couldn\'t sleep.',
    'Your brain wouldn\'t stop racing. You watched the hours tick by until dawn.',
    'Sleep was impossible — you lay awake replaying the day over and over.',
  ];

  return createMessageEvent(
    fname,
    pickVariant(insomniaVariants),
    player,
    check,
    { energyCost: 15 }
  );
}

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

export const dailyDisruptionEvents = {
  carWontStart,
  foundMoneyGround,
  surpriseVisitor,
  doctorAppointment,
  snowDay,
  powerOutage,
  flatTire,
  nightmareEvent,
  greatSleepEvent,
  insomniaEvent,
};
