import type { DynamicTextFn, EventDefinition, EventPlayerContext } from '../types.js';
import { pickVariant } from '../../../utils/textVariations.js';

/**
 * Childhood ("first act") catalog (v2 / live runtime).
 *
 * Fills the EARLY-LIFE content desert: ages 0-9 were content-thin (the youngest
 * pre-existing v2 event was `minAge: 5`), so a brand-new player's opening years
 * — the most retention-critical window — felt empty. This pack adds warm,
 * age-appropriate beats spanning ~ages 2-9, several of them reachable before
 * age 5 so the very first in-game years have something happening.
 *
 * Authored per the established catalog recipe (`adolescence.ts`, `random.ts`,
 * `family-arcs.ts`):
 *
 *  - PASSIVE milestones (`kind: 'passive'`) are formative beats with a single
 *    auto-resolving "Continue"-style choice — first words, first steps, first
 *    day of school, a lost tooth. They carry small positive happiness nudges.
 *  - INTERACTIVE beats offer a small, kid-appropriate choice (share your toy vs
 *    keep it; brave the scary slide vs not) that GENTLY nudges a stat. Deltas
 *    are deliberately small/age-appropriate so early choices lightly matter
 *    without unbalancing a 0-100 stat economy.
 *  - Most childhood milestones are once-ever (no `repeatable`). The one genuine
 *    recurring beat (a bedtime story) is `repeatable` with a cooldown and uses
 *    date-seeded `promptFn`/`resolutionTextFn` text variation so it does not
 *    read identically each time.
 *
 * Category: reuses the existing 'family' bucket — childhood content lives in the
 * family/home life stage and avoids inventing a new EventCategory.
 *
 * Stat roster note: Person stats are intelligence / social / creativity /
 * happiness / health / stress / prestige (there is NO `looks`). Effects below
 * only ever touch that roster.
 *
 * All ids are namespaced under `childhood.` and are globally unique.
 */

function choice(
  choiceId: string,
  text: string,
  resolutionText: string,
  overrides?: Partial<EventDefinition['choices'][number]>
): EventDefinition['choices'][number] {
  return {
    choiceId,
    text,
    resolutionText,
    ...overrides,
  };
}

function variantSeed(player: EventPlayerContext, salt: string): string {
  const day =
    (player as { dayOfYear?: unknown }).dayOfYear ??
    (player.c as { date?: unknown }).date ??
    (player as { date?: unknown }).date ??
    0;
  return `${salt}:${player.c.ageYears ?? 0}:${String(day)}`;
}

function seeded(salt: string, variants: string[]): DynamicTextFn {
  return (player) => pickVariant(variants, variantSeed(player, salt));
}

export const childhoodCatalog: EventDefinition[] = [
  // ===========================================================================
  // Toddler beats (minAge < 5) — passive milestones that reliably fire for the
  // very youngest characters, so the opening years are not silent.
  // ===========================================================================

  // First words (age ~2). PASSIVE milestone.
  {
    id: 'childhood.firstWords',
    category: 'family',
    kind: 'passive',
    prompt: 'A Tiny Voice',
    minAge: 2,
    maxAge: 3,
    weight: 2,
    choices: [
      choice(
        'first_word',
        'Continue',
        'You said your very first real word today, and the whole house lit up. Someone scrambled for a phone to capture it, then made you say it again and again. You giggled at all the fuss.',
        { effects: { stats: { happiness: 4, intelligence: 2 } } }
      ),
    ],
  },

  // First steps (age ~2). PASSIVE milestone.
  {
    id: 'childhood.firstSteps',
    category: 'family',
    kind: 'passive',
    prompt: 'Wobbly Steps',
    minAge: 2,
    maxAge: 4,
    weight: 2,
    choices: [
      choice(
        'take_steps',
        'Continue',
        'You let go of the couch and took three wobbly steps before plopping down with a surprised laugh. Everyone cheered like you had just won a race. You decided walking was definitely worth the effort.',
        { effects: { stats: { happiness: 4, health: 2 } } }
      ),
    ],
  },

  // Toddler: share the toy or keep it (age ~3-4). INTERACTIVE — gentle social nudge.
  {
    id: 'childhood.shareTheToy',
    category: 'family',
    prompt:
      'At the playground, another little kid is staring longingly at your favorite toy. What do you do?',
    minAge: 3,
    maxAge: 6,
    weight: 1,
    choices: [
      choice(
        'share',
        'Share it with them',
        'You toddled over and handed the toy to the other kid. They beamed, and soon the two of you were taking turns. Sharing felt nice, and you made a tiny new friend.',
        { effects: { stats: { social: 4, happiness: 3 } } }
      ),
      choice(
        'keep',
        'Keep it to yourself',
        'You clutched the toy tight and turned away. It stayed all yours, which felt good for a moment, but the other kid wandered off and the playground felt a little quieter.',
        { effects: { stats: { happiness: -1, social: -1 } } }
      ),
    ],
  },

  // Toddler: bedtime story (recurring). PASSIVE + REPEATABLE with date-seeded copy.
  {
    id: 'childhood.bedtimeStory',
    category: 'family',
    kind: 'passive',
    prompt: 'Just One More Story',
    promptFn: seeded('bedtime:prompt', [
      'Just One More Story',
      'Story Time',
      'Under the Covers',
      'One Last Chapter',
    ]),
    minAge: 2,
    maxAge: 8,
    repeatable: true,
    cooldownDays: 120,
    weight: 1,
    choices: [
      choice(
        'listen',
        'Continue',
        'Tucked in tight, you listened to a bedtime story with your eyes getting heavier and heavier. You begged for one more, got it, then drifted off mid-sentence feeling safe and warm.',
        {
          resolutionTextFn: seeded('bedtime:res', [
            'Tucked in tight, you listened to a bedtime story with your eyes getting heavier and heavier. You begged for one more, got it, then drifted off feeling safe and warm.',
            'Someone read you your favorite story in funny voices. You knew every line by heart and corrected them at the good parts, then fell asleep with a smile.',
            'The familiar story carried you off to sleep. You did not remember how it ended, but you remembered feeling looked after, which mattered more.',
          ]),
          effects: { stats: { happiness: 3, intelligence: 1 } },
        }
      ),
    ],
  },

  // ===========================================================================
  // Early-childhood beats (ages 5-9) — a warm mix of milestones and small
  // choices, capped with maxAge so they stay inside childhood.
  // ===========================================================================

  // First day of school (age ~5-6). PASSIVE milestone.
  {
    id: 'childhood.firstDayOfSchool',
    category: 'family',
    kind: 'passive',
    prompt: 'First Day of School',
    minAge: 5,
    maxAge: 7,
    weight: 2,
    choices: [
      choice(
        'go_to_school',
        'Continue',
        'You walked into your first day of school with a backpack almost as big as you. The morning was scary and the afternoon was thrilling, and you came home with a drawing, a new friend, and a hundred stories.',
        { effects: { stats: { intelligence: 3, social: 2, happiness: 2 } } }
      ),
    ],
  },

  // Learning to ride a bike (age ~5-7). INTERACTIVE — brave it or hold back.
  {
    id: 'childhood.learnToRideBike',
    category: 'family',
    prompt:
      'The training wheels are off your bike for the first time. Someone is holding the seat, ready to let go. Are you ready?',
    minAge: 5,
    maxAge: 9,
    weight: 1,
    choices: [
      choice(
        'go_for_it',
        'Pedal hard and go for it!',
        'You pedaled like mad, wobbled, and suddenly realized no one was holding on anymore — you were riding! You crashed into a bush a moment later, but you were grinning the whole way down.',
        { effects: { stats: { happiness: 4, health: 2, creativity: 1 } } }
      ),
      choice(
        'go_slow',
        'Ask them to keep holding on',
        'You asked them to keep holding the seat a little longer. You took it slow and steady, and by the end of the week you were riding on your own — just at your own careful pace.',
        { effects: { stats: { happiness: 2, health: 1 } } }
      ),
    ],
  },

  // A childhood pet (age ~5-9). INTERACTIVE — small choice about caring for it.
  {
    id: 'childhood.firstPet',
    category: 'family',
    prompt:
      "The family brings home a small, wide-eyed pet that is now yours to help look after. There's so much you could do. What's first?",
    minAge: 5,
    maxAge: 9,
    weight: 1,
    choices: [
      choice(
        'care_for_it',
        'Promise to feed and care for it every day',
        'You appointed yourself Chief Pet Caretaker. You learned the feeding schedule, made a little chart, and beamed every time it ran to greet you. Looking after something taught you more than you realized.',
        { effects: { stats: { happiness: 4, intelligence: 2, social: 1 } } }
      ),
      choice(
        'just_play',
        'Mostly just want to play with it',
        'You mostly wanted to play, and play you did — endless games of chase and fetch. The grown-ups handled most of the chores, but you and your new friend were inseparable.',
        { effects: { stats: { happiness: 3 } } }
      ),
    ],
  },

  // First family trip / vacation (age ~6-9). PASSIVE milestone.
  {
    id: 'childhood.familyTrip',
    category: 'family',
    kind: 'passive',
    prompt: 'The Big Family Trip',
    minAge: 6,
    maxAge: 9,
    weight: 1,
    choices: [
      choice(
        'go_on_trip',
        'Continue',
        'The whole family piled into the car for a big trip. You watched the world blur past the window, asked "are we there yet?" a hundred times, and made memories you would carry your whole life.',
        { effects: { stats: { happiness: 5, social: 2, creativity: 1 } } }
      ),
    ],
  },

  // Lost a tooth / tooth fairy (age ~6-8). PASSIVE milestone.
  {
    id: 'childhood.lostTooth',
    category: 'family',
    kind: 'passive',
    prompt: 'A Wiggly Tooth',
    minAge: 6,
    maxAge: 8,
    weight: 1,
    choices: [
      choice(
        'lose_tooth',
        'Continue',
        'Your wiggly tooth finally came out, and you could not stop poking the new gap with your tongue. You tucked the tooth under your pillow and woke up to a little surprise where it had been. Growing up felt magical.',
        { effects: { stats: { happiness: 4 } } }
      ),
    ],
  },

  // The scary slide (age ~5-8). INTERACTIVE — try the big slide or not.
  {
    id: 'childhood.scarySlide',
    category: 'family',
    prompt:
      'At the park there is a HUGE slide the big kids go on. Your friends dare you to try it. It looks awfully high from down here. Do you climb up?',
    minAge: 5,
    maxAge: 9,
    weight: 1,
    choices: [
      choice(
        'try_slide',
        'Climb up and brave it',
        'Heart pounding, you climbed all the way up and pushed off before you could change your mind. You whooshed down screaming with delight and immediately ran back to do it again. You felt brave and unstoppable.',
        { effects: { stats: { happiness: 4, social: 2, creativity: 1 } } }
      ),
      choice(
        'small_slide',
        'Stick to the smaller slide',
        'You decided the big slide could wait and stuck to the smaller one you knew and loved. No shame in that — you had a great time, and the big slide would still be there next time.',
        { effects: { stats: { happiness: 1 } } }
      ),
    ],
  },
];

/**
 * Deterministic resolution-text lookup for a childhood-catalog choice (static
 * fallback text). Used by tests and any caller needing the resolved copy
 * without firing the engine.
 */
export function resolveChildhoodChoice(eventId: string, choiceId: string): string | null {
  const definition = childhoodCatalog.find((event) => event.id === eventId);
  if (!definition) {
    return null;
  }
  const selectedChoice = definition.choices.find((item) => item.choiceId === choiceId);
  return selectedChoice?.resolutionText ?? null;
}
