/**
 * Health & Medical Narrative Events
 *
 * Gives storytelling weight to existing health conditions and wellness.
 * 13 health conditions exist mechanically but had zero narrative events.
 *
 * Realtime events (function-based, checked each hour):
 * - feelingTiredWarning: Low energy warning with coping choices
 * - annualCheckupReminder: Proactive health maintenance
 * - greatWorkout: Post-exercise mood boost
 * - stressWarning: Stress threshold alert with intervention choices
 * - healthyEatingChoice: Nutrition decision point
 * - gymBuddyInvite: Social fitness invitation from a friend
 *
 * Fast mode events (function-based):
 * - injuryFromActivity: Gets hurt during physical activity
 * - mentalHealthCrisis: Serious mental health episode
 * - addictionWarning: Habit escalation into addiction territory
 */

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

// =============================================================================
// Helper: find a friend for social health events
// =============================================================================

function findHealthBuddy(player: Player): Person | null {
  const friends = (player.r ?? []).filter(
    (p) =>
      p.status === 'alive' &&
      ((p.relationships ?? []).includes('friend') || (p.affinity ?? 0) > 25) &&
      (p.ageYears ?? 0) >= 14
  );
  if (friends.length === 0) return null;
  return friends[Math.floor(Math.random() * friends.length)];
}

// =============================================================================
// Realtime Events (function-based)
// =============================================================================

/**
 * Feeling tired warning - triggers when energy is low during daytime
 * Take a nap: energy +15, lose 2 hours | Coffee: energy +8, stress +5 | Push through: energy -5
 */
export function feelingTiredWarning(player: Player, _type: string = 'check'): EventResult {
  const fname = 'feelingTiredWarning';

  const check =
    !player.events.has(fname) &&
    player.c.ageYears >= 12 &&
    (player.c.energy ?? 100) < 25 &&
    (player.c.energy ?? 100) > 5 &&
    player.hourOfDay >= 10 &&
    player.hourOfDay <= 16 &&
    checkProbability(3000);

  if (!check) return null;

  return createQuestionEvent(
    fname,
    "You can barely keep your eyes open. Your body is telling you it needs rest. What do you do?",
    player,
    true,
    {
      answerOptions: [
        createAnswerOption('Take a quick nap', 'nap'),
        createAnswerOption('Grab some coffee', 'coffee', 0, 0, 5),
        createAnswerOption('Push through it', 'push', 5),
      ],
    }
  );
}

/**
 * Annual checkup reminder - proactive health maintenance
 * Go: money -$100, small health boost | Skip: risk missing something
 */
export function annualCheckupReminder(player: Player, _type: string = 'check'): EventResult {
  const fname = 'annualCheckupReminder';

  const check =
    !player.events.has(fname) &&
    player.c.ageYears >= 18 &&
    player.monthOfYear === 1 &&
    checkProbability(5000);

  if (!check) return null;

  return createQuestionEvent(
    fname,
    "It's the start of a new year. Your doctor's office called to remind you about your annual physical. Do you schedule it?",
    player,
    true,
    {
      answerOptions: [
        createAnswerOption('Yes, schedule it this week', 'yes', 5, 0, 100),
        createAnswerOption('Maybe later this month', 'later'),
        createAnswerOption('Skip it, I feel fine', 'skip'),
      ],
    }
  );
}

/**
 * Great workout - post-exercise mood and health boost
 * Triggers when player has good energy and is active
 */
export function greatWorkout(player: Player, _type: string = 'check'): EventResult {
  const fname = 'greatWorkout';

  const check =
    !player.events.has(fname) &&
    player.c.ageYears >= 10 &&
    (player.c.energy ?? 100) >= 40 &&
    (player.c.health ?? 100) >= 40 &&
    checkProbability(6000);

  if (!check) return null;

  player.c.happiness = modifyStat(player.c.happiness, 5);
  player.c.health = modifyStat(player.c.health, 3);
  player.c.energy = modifyStat(player.c.energy, 5);

  return createMessageEvent(
    fname,
    "You had an amazing workout today. Your muscles ache in the best way possible and you feel energized despite the effort. The endorphins are real.",
    player,
    true
  );
}

/**
 * Stress warning - triggers when stress is high
 * Take action or let it build
 */
export function stressWarning(player: Player, _type: string = 'check'): EventResult {
  const fname = 'stressWarning';

  const check =
    !player.events.has(fname) &&
    player.c.ageYears >= 14 &&
    (player.c.stress ?? 0) > 70 &&
    checkProbability(4000);

  if (!check) return null;

  return createQuestionEvent(
    fname,
    "You've been clenching your jaw all day and your shoulders are up by your ears. The stress is getting to you. How do you deal with it?",
    player,
    true,
    {
      answerOptions: [
        createAnswerOption('Go for a walk to clear your head', 'walk', 10),
        createAnswerOption('Call someone you trust', 'call', 5),
        createAnswerOption('Take a long bath and relax', 'bath', 5),
        createAnswerOption('Ignore it and keep going', 'ignore'),
      ],
    }
  );
}

/**
 * Healthy eating choice - nutrition decision point
 * Choose between fast food, healthy meal, or cooking at home
 */
export function healthyEatingChoice(player: Player, _type: string = 'check'): EventResult {
  const fname = 'healthyEatingChoice';

  const check =
    !player.events.has(fname) &&
    player.c.ageYears >= 16 &&
    player.hourOfDay >= 11 &&
    player.hourOfDay <= 14 &&
    checkProbability(5000);

  if (!check) return null;

  return createQuestionEvent(
    fname,
    "Lunchtime. Your stomach is growling and you're trying to decide what to eat. The fast food place is right there, but you know you should eat better.",
    player,
    true,
    {
      answerOptions: [
        createAnswerOption('Cook a healthy meal at home', 'healthy', 10),
        createAnswerOption('Get a salad from the deli ($12)', 'salad', 0, 0, 12),
        createAnswerOption('Fast food, no regrets ($8)', 'fastfood', 0, 0, 8),
        createAnswerOption('Skip lunch, too busy', 'skip'),
      ],
    }
  );
}

/**
 * Gym buddy invite - friend invites you to work out together
 * Social fitness bonding event
 */
export function gymBuddyInvite(player: Player, _type: string = 'check'): EventResult {
  const fname = 'gymBuddyInvite';
  const friend = findHealthBuddy(player);

  const check =
    !player.events.has(fname) &&
    player.c.ageYears >= 14 &&
    friend !== null &&
    (player.c.energy ?? 100) >= 30 &&
    checkProbability(6000);

  if (!check || !friend) return null;

  return createQuestionEvent(
    fname,
    `${friend.firstname} texts you: "Want to hit the gym together? I could use a workout buddy to keep me accountable."`,
    player,
    true,
    {
      answerOptions: [
        createAnswerOption("Let's do it!", 'yes', 15),
        createAnswerOption('Maybe next time', 'no'),
      ],
      characters: [{ id: friend.id, firstname: friend.firstname, lastname: friend.lastname, image: friend.image }],
    }
  );
}

// =============================================================================
// Fast Mode Events (function-based)
// =============================================================================

/**
 * Injury from activity - gets hurt during physical activity
 * Costs energy and health, choice about medical care
 */
export function injuryFromActivityHealth(player: Player, _type: string = 'check'): EventResult {
  const fname = 'injuryFromActivityHealth';

  const check =
    !player.askedQuestions.has(fname) &&
    player.c.ageYears >= 10 &&
    checkProbability(80000);

  if (!check) return null;

  player.askedQuestions.add(fname);

  const injuries = [
    { desc: 'twisted your knee while running', treatment: 'physical therapy', cost: 300 },
    { desc: 'pulled a muscle lifting weights', treatment: 'rest and ice', cost: 50 },
    { desc: 'got a concussion playing sports', treatment: 'medical evaluation', cost: 800 },
    { desc: 'dislocated your shoulder', treatment: 'emergency room visit', cost: 2000 },
    { desc: 'fractured your wrist in a fall', treatment: 'casting and follow-up', cost: 1500 },
  ];
  const injury = injuries[Math.floor(Math.random() * injuries.length)];

  player.c.health = modifyStat(player.c.health, -10);
  player.c.energy = modifyStat(player.c.energy, -20);

  return createQuestionEvent(
    fname,
    `You ${injury.desc}. The pain is significant. You might need ${injury.treatment}. What do you do?`,
    player,
    true,
    {
      answerOptions: [
        createAnswerOption(`Get ${injury.treatment} ($${injury.cost})`, 'treat', 0, 0, injury.cost),
        createAnswerOption('Rest at home and hope it heals', 'rest'),
        createAnswerOption('Ignore it and keep going', 'ignore'),
      ],
    }
  );
}

/**
 * Mental health crisis - serious mental health episode
 * Requires intervention choices with real consequences
 */
export function mentalHealthCrisis(player: Player, _type: string = 'check'): EventResult {
  const fname = 'mentalHealthCrisis';

  const check =
    !player.askedQuestions.has(fname) &&
    player.c.ageYears >= 16 &&
    ((player.c.happiness ?? 50) < 20 || (player.c.stress ?? 0) > 80) &&
    checkProbability(50000);

  if (!check) return null;

  player.askedQuestions.add(fname);

  player.c.happiness = modifyStat(player.c.happiness, -10);
  player.c.energy = modifyStat(player.c.energy, -15);

  return createQuestionEvent(
    fname,
    "You wake up and can't get out of bed. The weight of everything feels crushing. You've been struggling for weeks and today it all hit at once. You know you need help.",
    player,
    true,
    {
      answerOptions: [
        createAnswerOption('Call a therapist ($150)', 'therapy', 10, 0, 150),
        createAnswerOption('Talk to a family member', 'family', 10),
        createAnswerOption('Call a crisis helpline', 'helpline', 5),
        createAnswerOption('Try to handle it alone', 'alone'),
      ],
    }
  );
}

/**
 * Addiction warning - habit escalation into dangerous territory
 * Only triggers if player has relevant negative habits
 */
export function addictionWarning(player: Player, _type: string = 'check'): EventResult {
  const fname = 'addictionWarning';

  const characterAny = player.character as unknown as { habits?: Array<{ name: string; habitType: string; status: string }> };
  const habits = characterAny.habits ?? [];
  const dangerousHabits = habits.filter(
    (h) =>
      h.habitType === 'negative' &&
      h.status === 'active' &&
      ['smoking', 'excessive_alcohol_consumption', 'overeating_when_stressed'].includes(h.name)
  );

  const check =
    !player.askedQuestions.has(fname) &&
    player.c.ageYears >= 18 &&
    dangerousHabits.length > 0 &&
    checkProbability(60000);

  if (!check) return null;

  player.askedQuestions.add(fname);

  const habit = dangerousHabits[Math.floor(Math.random() * dangerousHabits.length)];

  const warnings: Record<string, string> = {
    smoking: "You notice you're going through a pack a day now. Your morning cough is getting worse, and you get irritable when you can't smoke. This is more than a habit.",
    excessive_alcohol_consumption: "You realize you've been drinking every night this week. You needed a drink to get through the day, and the thought of stopping makes you anxious. This is becoming a problem.",
    overeating_when_stressed: "You've gained noticeable weight and your eating feels out of control. Every stressful moment sends you straight to food. Your clothes don't fit and your energy is dropping.",
  };

  return createQuestionEvent(
    fname,
    warnings[habit.name] ?? "One of your habits is becoming a serious concern. You need to decide what to do about it.",
    player,
    true,
    {
      answerOptions: [
        createAnswerOption('Seek professional help ($200)', 'professional', 10, 0, 200),
        createAnswerOption('Try to quit on your own', 'quit', 15),
        createAnswerOption('Acknowledge it but do nothing yet', 'acknowledge'),
        createAnswerOption("It's not that bad", 'deny'),
      ],
    }
  );
}

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

export const healthNarrativeEvents = {
  feelingTiredWarning,
  annualCheckupReminder,
  greatWorkout,
  stressWarning,
  healthyEatingChoice,
  gymBuddyInvite,
  injuryFromActivityHealth,
  mentalHealthCrisis,
  addictionWarning,
};
