/**
 * Family Dynamics Events
 *
 * Family members are generated but rarely do anything interesting.
 * These events make family feel alive with calls, visits, and interactions.
 *
 * Realtime events (function-based, checked each hour):
 * - parentCalls: Parent calls to check in
 * - siblingMemory: Sibling reminds you of a shared memory
 * - parentNeedsHelp: Parent needs practical help with something
 * - kidDrawing: Your child gives you a drawing or shows report card
 * - familyGroupChat: Family group chat blows up
 * - unexpectedFamilyVisit: Family member shows up unannounced
 */

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

// =============================================================================
// Helpers: Find real family members
// =============================================================================

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

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 'mom';
  if (rels.includes('father') || title === 'father') return 'dad';
  return 'parent';
}

function findAnyFamily(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') ||
      rels.includes('sibling') || rels.includes('brother') || rels.includes('sister') ||
      rels.includes('child') || rels.includes('spouse') ||
      title === 'mother' || title === 'father' ||
      title.includes('sibling') || title.includes('brother') || title.includes('sister');
  }) ?? null;
}

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

/**
 * Parent calls to check in
 * Answer: energy -5, affinity +3, happiness +3 | Ignore: affinity -2
 */
export function parentCalls(player: Player, _type: string = 'check'): EventResult {
  const fname = 'parentCalls';
  const parent = findParent(player);

  const check =
    !player.events.has(fname) &&
    player.c.ageYears >= 10 &&
    parent !== null &&
    player.hourOfDay >= 9 &&
    player.hourOfDay <= 21 &&
    checkProbability(5000);

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

  const title = getParentTitle(parent);
  const topics = [
    `"Just checking in, how are you doing?"`,
    `"I saw something that reminded me of you."`,
    `"Have you been eating well?"`,
    `"When are you coming to visit?"`,
    `"I just wanted to hear your voice."`,
  ];
  const topic = topics[Math.floor(Math.random() * topics.length)];

  return createQuestionEvent(
    fname,
    `Your ${title} ${parent.firstname} is calling. ${topic}`,
    player,
    true,
    {
      answerOptions: [
        createAnswerOption('Answer and chat for a while', 'answer', 5),
        createAnswerOption('Quick answer, you\'re busy', 'quick'),
        createAnswerOption('Let it go to voicemail', 'ignore'),
      ],
      characters: [{ id: parent.id, firstname: parent.firstname, lastname: parent.lastname, image: parent.image }],
    }
  );
}

/**
 * Sibling reminds you of a shared memory
 * Engage: happiness +5, affinity +3 | Dismiss: affinity -2
 */
export function siblingMemory(player: Player, _type: string = 'check'): EventResult {
  const fname = 'siblingMemory';
  const sibling = findSibling(player);

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

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

  const memories = [
    `that time you both got in trouble for breaking the neighbor's window`,
    `the road trip where you sang terrible karaoke in the back seat`,
    `when you stayed up all night watching scary movies and couldn't sleep for a week`,
    `the snowball fight that got way too competitive`,
    `building that massive pillow fort that took over the entire living room`,
  ];
  const memory = memories[Math.floor(Math.random() * memories.length)];

  return createQuestionEvent(
    fname,
    `${sibling.firstname} sends you a text: "Remember ${memory}? 😂 I was just thinking about that."`,
    player,
    true,
    {
      answerOptions: [
        createAnswerOption('Reply with your own memory', 'engage'),
        createAnswerOption('Send a laughing emoji back', 'emoji'),
        createAnswerOption('Leave it on read', 'ignore'),
      ],
      characters: [{ id: sibling.id, firstname: sibling.firstname, lastname: sibling.lastname, image: sibling.image }],
    }
  );
}

/**
 * Parent needs help with something practical
 * Help: energy -20, affinity +8 | Partial: energy -10, affinity +4 | Busy: affinity -5
 */
export function parentNeedsHelp(player: Player, _type: string = 'check'): EventResult {
  const fname = 'parentNeedsHelp';
  const parent = findParent(player);

  const check =
    !player.events.has(fname) &&
    player.c.ageYears >= 16 &&
    parent !== null &&
    (player.c.energy ?? 100) >= 25 &&
    checkProbability(6000);

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

  const title = getParentTitle(parent);
  const tasks = [
    'figure out their new phone',
    'move some heavy furniture',
    'drive them to an appointment',
    'help with their taxes',
    'fix something around the house',
  ];
  const task = tasks[Math.floor(Math.random() * tasks.length)];

  return createQuestionEvent(
    fname,
    `Your ${title} ${parent.firstname} calls: "Could you help me ${task}? I can't figure it out on my own."`,
    player,
    true,
    {
      answerOptions: [
        createAnswerOption('Of course, I\'ll come right over', 'help', 20),
        createAnswerOption('I can help for a bit', 'partial', 10),
        createAnswerOption('Sorry, I\'m really busy today', 'busy'),
      ],
      characters: [{ id: parent.id, firstname: parent.firstname, lastname: parent.lastname, image: parent.image }],
    }
  );
}

/**
 * Kid's drawing or report card - only if player has children
 * React enthusiastically: happiness +8, child affinity +5 | Polite: +3 | Dismiss: -5
 */
export function kidDrawing(player: Player, _type: string = 'check'): EventResult {
  const fname = 'kidDrawing';
  const child = findChild(player);

  const check =
    !player.events.has(fname) &&
    player.c.ageYears >= 20 &&
    child !== null &&
    (child.ageYears ?? 0) >= 3 &&
    (child.ageYears ?? 0) <= 12 &&
    checkProbability(4000);

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

  const isDrawing = Math.random() > 0.5;

  const message = isDrawing
    ? `Your child ${child.firstname} runs up to you holding a crayon drawing. "Look what I made! It's our family!" The stick figures are adorable.`
    : `${child.firstname} comes home from school and shyly hands you their report card. They're watching your face nervously.`;

  return createQuestionEvent(
    fname,
    message,
    player,
    true,
    {
      answerOptions: [
        createAnswerOption(isDrawing ? 'Put it on the fridge with pride!' : 'Tell them how proud you are', 'enthuse'),
        createAnswerOption(isDrawing ? 'Say it\'s nice and set it aside' : 'Review it calmly', 'polite'),
        createAnswerOption(isDrawing ? 'You\'re too busy right now' : 'Focus only on what needs improvement', 'dismiss'),
      ],
      characters: [{ id: child.id, firstname: child.firstname, lastname: child.lastname, image: child.image }],
    }
  );
}

/**
 * Family group chat blows up
 * Engage: energy -5, happiness +5 | Mute: miss things | React only: low effort
 */
export function familyGroupChat(player: Player, _type: string = 'check'): EventResult {
  const fname = 'familyGroupChat';

  const familyCount = (player.r ?? []).filter((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') || rels.includes('sibling') ||
      rels.includes('brother') || rels.includes('sister') ||
      title === 'mother' || title === 'father';
  }).length;

  const check =
    !player.events.has(fname) &&
    player.c.ageYears >= 12 &&
    familyCount >= 2 &&
    checkProbability(5000);

  if (!check) return null;

  const topics = [
    'planning who brings what to the next holiday dinner',
    'sharing old family photos someone found in the attic',
    'debating where to eat for a family dinner',
    'arguing about whose turn it is to visit grandma',
    'sharing memes that only your family would find funny',
  ];
  const topic = topics[Math.floor(Math.random() * topics.length)];

  return createQuestionEvent(
    fname,
    `The family group chat is blowing up. Everyone is ${topic}. Your phone won't stop buzzing.`,
    player,
    true,
    {
      answerOptions: [
        createAnswerOption('Jump in and participate', 'engage', 5),
        createAnswerOption('Send a few reactions', 'react'),
        createAnswerOption('Mute the chat', 'mute'),
      ],
    }
  );
}

/**
 * Unexpected family visit - family member shows up unannounced
 * Welcome: energy -10, happiness +5, affinity +5 | Polite: +2 | Annoyed: affinity -3
 */
export function unexpectedFamilyVisit(player: Player, _type: string = 'check'): EventResult {
  const fname = 'unexpectedFamilyVisit';
  const family = findAnyFamily(player);

  const check =
    !player.events.has(fname) &&
    player.c.ageYears >= 18 &&
    family !== null &&
    player.hourOfDay >= 10 &&
    player.hourOfDay <= 20 &&
    checkProbability(7000);

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

  const rels = family.relationships ?? [];
  const title = (family as ExtendedPerson).title?.toLowerCase() ?? '';
  let relation = 'family member';
  if (rels.includes('mother') || title === 'mother') relation = 'mom';
  else if (rels.includes('father') || title === 'father') relation = 'dad';
  else if (rels.includes('sibling') || rels.includes('brother') || title.includes('brother')) relation = 'brother';
  else if (rels.includes('sister') || title.includes('sister')) relation = 'sister';

  return createQuestionEvent(
    fname,
    `Your ${relation} ${family.firstname} just showed up at your door unannounced with bags of groceries. "Surprise! I thought we could cook dinner together."`,
    player,
    true,
    {
      answerOptions: [
        createAnswerOption('Welcome them in warmly', 'welcome', 10),
        createAnswerOption('Let them in but mention calling first', 'polite'),
        createAnswerOption('Tell them it\'s not a good time', 'annoyed'),
      ],
      characters: [{ id: family.id, firstname: family.firstname, lastname: family.lastname, image: family.image }],
    }
  );
}

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

export const familyDynamicsEvents = {
  parentCalls,
  siblingMemory,
  parentNeedsHelp,
  kidDrawing,
  familyGroupChat,
  unexpectedFamilyVisit,
};
