import React, { useEffect, useMemo, useRef, useState } from "react";

import styles from "./CrashTheServer.module.css";

type Rule = {
  id: number;
  stage: 1 | 2 | 3 | 4 | 5;
  title: string;
  hint: string; // shown after correct first-try answer
  weight: number;
  check: (input: string) => boolean;
};

// Normalize: lowercase + strip non-alphanumeric for flexible answer matching
function normalize(s: string): string {
  return s.toLowerCase().replace(/[^a-z0-9]/g, "");
}

// Clean escape sequences (like \n, \t) into spaces so word boundaries (\b) evaluate correctly
function cleanEscapeSequences(s: string): string {
  return s.replace(/\\[ntrfb0]|\\x[0-9a-fA-F]{2}/g, " ");
}

// Programmer catchphrases (normalized, for Rule 5 flexible matching)
const PROGRAMMER_PHRASES_NORM = [
  "helloworld",
  "itworksonmymachine",
  "lgtm",
  "bug",
  "coffee",
  "stackoverflow",
  "shipit",
  "worksasdesigned",
  "norepro",
  "haveyoutriedturningitoff",
];

function digitSum(s: string) {
  return [...s].filter((c) => /\d/.test(c)).reduce((a, c) => a + Number(c), 0);
}
function isPrime(n: number): boolean {
  if (n < 2) return false;
  for (let i = 2; i * i <= n; i++) if (n % i === 0) return false;
  return true;
}
function isPalindrome(s: string) {
  return s.length >= 3 && s === [...s].reverse().join("");
}
function hasPalindromeSubstring(s: string) {
  for (let i = 0; i < s.length; i++) {
    for (let j = i + 3; j <= s.length; j++) {
      if (isPalindrome(s.slice(i, j))) return true;
    }
  }
  return false;
}
function hasMatchingHtmlTriples(s: string) {
  const tags = s.matchAll(/<(\/)?([a-zA-Z][a-zA-Z0-9]*)>/g);
  const stack: string[] = [];
  let pairs = 0;
  for (const match of tags) {
    const isClosingTag = match[1] === "/";
    const tagName = match[2].toLowerCase();
    if (!isClosingTag) {
      stack.push(tagName);
    } else if (stack.pop() !== tagName) {
      return false;
    } else {
      pairs += 1;
    }
  }
  return pairs >= 3;
}
function hasBase64(s: string) {
  return /(?:^|[^A-Za-z0-9+/])(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)(?=$|[^A-Za-z0-9+/=])/.test(
    s
  );
}

// Detailed hints shown after a WRONG quiz answer, keyed by rule id
const RULE_DETAILED_HINTS: Record<number, { hint: string; term?: string }> = {
  1: {
    hint: "Count the characters you've typed so far and keep adding more until you reach at least 8.",
  },
  2: {
    hint: "Add any single digit character, 0 through 9, anywhere in your password.",
  },
  3: {
    hint: "Add at least one capital letter, A through Z, anywhere in your password.",
  },
  4: {
    hint: "Add a symbol that isn't a letter or number, such as ! @ # $ % ^ & *.",
  },
  5: {
    hint: "Think of a phrase that almost every programmer has typed at least once, or a famous developer meme often joked about when software behaves unexpectedly.",
  },
  6: {
    hint: "Include a valid escape sequence that could legally appear inside a programming language string.",
    term: "Escape sequence: A special combination of characters used to represent characters that cannot be typed directly, such as a newline, tab, or quotation mark.",
  },
  7: {
    hint: "Include the release year of a widely recognized programming language.",
  },
  8: {
    hint: "Think about what action you would take when a computer completely freezes or encounters a severe system failure.",
  },
  9: {
    hint: "Include a keyword related to how programming languages allocate, free, or safely reference memory.",
    term: "Memory safety: The property of a program that prevents invalid memory access, such as reading or writing memory that should not be accessed.",
  },
  10: {
    hint: "Include the name of a popular tool used for software automation, continuous integration, or application containers.",
    term: "Container: Packages an application with everything it needs to run. CI: Automatically builds and tests software when code changes.",
  },
  11: {
    hint: "Include a programming construct that allows multiple threads to safely coordinate access to shared resources.",
    term: "Synchronization primitive: A low-level programming mechanism used to coordinate multiple threads or processes.",
  },
  12: {
    hint: "Think about concepts related to threads waiting for one another or mechanisms that help avoid deadlocks.",
    term: "Deadlock: A situation where multiple threads are permanently waiting for each other, preventing any from continuing.",
  },
  13: {
    hint: "Include a term related to memory management, memory usage, garbage collection, or process termination.",
    term: "Garbage Collection (GC): The automatic process of reclaiming memory that is no longer being used.",
  },
  14: {
    hint: "Add together every digit that appears anywhere in your password. The total must equal the required target.",
  },
  15: {
    hint: "Include the IPv4 address that always refers back to the same computer it is running on.",
    term: "Loopback address: A special IP address reserved for communicating with the local machine.",
  },
  16: {
    hint: "Include the prefix of an IPv4 address range reserved for local area networks rather than the public Internet.",
    term: "Private subnet: An IP address range intended only for private networks such as homes, schools, or businesses.",
  },
  17: {
    hint: "Include one of the standard request methods used by web browsers and web servers.",
    term: "HTTP Method: Specifies what a web request wants to do, such as retrieving or submitting data.",
  },
  18: {
    hint: "Think of a port number commonly associated with websites or web servers.",
    term: "Port number: A numerical identifier that tells a computer which network service a connection should use.",
  },
  19: {
    hint: "Include a reserved keyword commonly used when querying or modifying relational databases.",
    term: "SQL: The standard language used to communicate with relational databases.",
  },
  20: {
    hint: "Think of a Git command that can rewrite history or potentially discard important work if used incorrectly.",
    term: "Git: A version control system used to track changes in source code.",
  },
  21: {
    hint: "Include a file extension commonly associated with a statically typed programming language.",
    term: "Statically typed language: A programming language where variable types are checked before the program runs.",
  },
  22: {
    hint: "Include a sequence of characters that reads exactly the same forwards and backwards.",
    term: "Palindrome: A word or sequence that is identical when reversed.",
  },
  23: {
    hint: "Count every vowel appearing in your entire password. The total number must satisfy a special mathematical property.",
    term: "Prime number: A positive integer greater than 1 that is divisible only by 1 and itself.",
  },
  24: {
    hint: "Include a three-letter symbol used to identify a financial asset or cryptocurrency in a trading system.",
    term: "Ticker: A short code that uniquely identifies a stock, currency, or cryptocurrency.",
  },
  25: {
    hint: "Include a programming keyword representing either a Boolean value or the absence of a value.",
  },
  26: {
    hint: "Include a number written using hexadecimal notation.",
    term: "Hexadecimal (Base-16): A numbering system that uses sixteen symbols (0–9 and A–F) instead of ten.",
  },
  27: {
    hint: "Think about one of the three computer scientists whose surnames give a famous encryption algorithm its name.",
    term: "RSA: One of the world's best-known public-key cryptography algorithms.",
  },
  28: {
    hint: "Include the Big-O time complexity of the binary search algorithm.",
    term: "Big-O notation: A mathematical notation describing how an algorithm's running time grows as the input size increases.",
  },
  29: {
    hint: "Include a CSS sizing value consisting of a number immediately followed by a valid CSS unit.",
    term: "CSS sizing unit: A unit used by web pages to specify dimensions, spacing, or font sizes.",
  },
  30: {
    hint: "Include three correctly matched pairs of HTML opening and closing tags.",
    term: "HTML tag: Markup enclosed in angle brackets that defines the structure of a web page.",
  },
  31: {
    hint: "Include a valid Base64-encoded string that meets the minimum required length.",
    term: "Base64: An encoding method that represents binary data using printable ASCII characters.",
  },
  32: {
    hint: "Look at the current system clock and include its minute value.",
  },
  33: {
    hint: "Include a valid three-digit UNIX file permission written in octal notation.",
    term: "Octal permission: A compact way of representing file permissions using base-8 digits.",
  },
  34: {
    hint: "Include the name of one of the standard output channels provided by most operating systems.",
    term: "Standard stream: A predefined communication channel used by programs for input, normal output, or error output.",
  },
  35: {
    hint: "Include the hexadecimal color code representing one of the two extreme grayscale colors.",
    term: "Hex color: A six-digit (or shorthand three-digit) hexadecimal representation of an RGB color used in web development.",
  },
  36: {
    hint: "Count every character in your password—including letters, numbers, spaces, and symbols. The total length must satisfy the required divisibility condition.",
  },
  37: {
    hint: "Include the required comment phrase exactly as specified. Every character, including spaces and punctuation, must match.",
  },
  38: {
    hint: "Include a version number that follows the Semantic Versioning standard.",
    term: "Semantic Versioning (SemVer): A convention that uses three numbers in the form major.minor.patch to indicate compatibility and scope of changes.",
  },
  39: {
    hint: "Include the required debugging-related word, but make sure it is placed far enough away from the specified phrase to satisfy the distance requirement.",
    term: "Adjacent: Two pieces of text are considered adjacent when they appear within the restricted number of characters defined by the rule.",
  },
  40: {
    hint: "Your password must literally end with: ; // Kernel Panic triggered successfully — copy it exactly, including the leading semicolon and slashes, as the very last characters you type.",
    term: "Kernel panic: The point at which an operating system halts because it has encountered an error it cannot safely recover from.",
  },
};

// Encouraging messages shown when Server Overload crosses 39 / 56 / 87 %
const MILESTONE_POOLS: Record<number, string[]> = {
  39: [
    "You're shaking the foundations! Keep pushing!",
    "The server is sweating. Don't stop now!",
    "You've got this fragile system on the ropes!",
  ],
  56: [
    "Brilliant minds break systems. You're doing exactly that!",
    "Fans are spinning at maximum speed! Melt that silicon!",
    "CPU usage is redlining! Victory is just a few rule-breaks away!",
  ],
  87: [
    "Warning: High memory pressure detected. Excellent work!",
    "The stack is overflowing! Keep feeding it!",
    "The system is crying for help. Finish the job, legend!",
    "Almost there! One more brilliant line to crush it!",
  ],
};

const RULE_POOL: Rule[] = [
  // Stage 1 — Onboarding
  {
    id: 1,
    stage: 1,
    weight: 5,
    title: "Your password must be at least 8 characters.",
    hint: "Just keep typing.",
    check: (s) => s.length >= 8,
  },
  {
    id: 2,
    stage: 1,
    weight: 5,
    title: "Your password must include a number.",
    hint: "Any digit 0-9.",
    check: (s) => /\d/.test(s),
  },
  {
    id: 3,
    stage: 1,
    weight: 5,
    title: "Your password must include an uppercase letter.",
    hint: "Hold Shift.",
    check: (s) => /[A-Z]/.test(s),
  },
  {
    id: 4,
    stage: 1,
    weight: 5,
    title: "Your password must include a special character.",
    hint: "Try ! @ # $ % ^ & *",
    check: (s) => /[!@#$%^&*()_+\-=[\]{};:'",.<>/?\\|`~]/.test(s),
  },
  {
    id: 5,
    stage: 1,
    weight: 5,
    title: "Your password must include a classic programmer catchphrase.",
    hint: `Try "hello world", "helloworld", "lgtm", "shipit", or "norepro".`,
    check: (s) => {
      const norm = normalize(s);
      return PROGRAMMER_PHRASES_NORM.some((p) => norm.includes(p));
    },
  },
  {
    id: 6,
    stage: 1,
    weight: 5,
    title: "Your password must contain a valid escape sequence.",
    hint: "Type a literal backslash followed by n, t, b, r, f, 0, or a hex code — e.g. \\n, \\t, \\x41.",
    check: (s) => /\\[ntrfb'"0]|\\x[0-9a-fA-F]{2}/.test(s),
  },
  {
    id: 7,
    stage: 1,
    weight: 5,
    title:
      "Your password must include the release year of a famous programming language.",
    hint: "Fortran 1957, C 1972, C++ 1983, Python 1991, Java/JS 1995, Go 2009, Rust 2010, Swift 2014.",
    check: (s) =>
      /(?<!\d)(1957|1958|1959|1970|1972|1983|1987|1991|1995|2000|2009|2010|2011|2014)(?!\d)/.test(
        s
      ),
  },

  // Stage 2 — Production incidents (scenario-injected)
  {
    id: 8,
    stage: 2,
    weight: 6,
    title:
      "The Senior Dev pushed untested code straight to prod — Kernel Space crashed. Your password must contain the word that brings the box back.",
    hint: "Either type 'reboot' or admit the system is in 'panic'.",
    check: (s) => /reboot|panic/i.test(s),
  },
  {
    id: 9,
    stage: 2,
    weight: 6,
    title:
      "A New Grad dereferenced something they shouldn't in Heap Memory → Segmentation Fault. Your password must contain a memory-safety keyword.",
    hint: "Languages call invalid pointers different things: nullptr, malloc, free.",
    check: (s) => /nullptr|malloc|free/i.test(s),
  },
  {
    id: 10,
    stage: 2,
    weight: 6,
    title:
      "The DevOps Lead quit and torched the CI/CD Pipeline on the way out. Your password must contain an automation / container tool name.",
    hint: "What runs in containers and what schedules them? docker, jenkins, yaml.",
    check: (s) => /docker|jenkins|yaml/i.test(s),
  },
  {
    id: 11,
    stage: 2,
    weight: 6,
    title:
      "The AI Copilot generated lock-free code in the Order Book Cache — Data Race in production. Your password must contain a synchronization primitive.",
    hint: "What protects a critical section? mutex, lock, atomic.",
    check: (s) => /mutex|lock|atomic/i.test(s),
  },
  {
    id: 12,
    stage: 2,
    weight: 6,
    title:
      "Concurrency spiked and the scheduler deadlocked. Your password must contain a word from Coffman's conditions or a deadlock-breaker.",
    hint: "Think OS textbook: semaphore, wait.",
    check: (s) => /semaphore|wait/i.test(s),
  },
  {
    id: 13,
    stage: 2,
    weight: 6,
    title:
      "Memory pressure went vertical and the OOM Killer woke up. Your password must contain a GC or memory metric keyword.",
    hint: "gc, ram, kill.",
    check: (s) => /\bgc\b|\bram\b|\bkill\b/i.test(cleanEscapeSequences(s)),
  },
  {
    id: 14,
    stage: 2,
    weight: 8,
    title:
      "The digits in your password must add up to the Ultimate Answer to Life, the Universe, and Everything.",
    hint: "Deep Thought took 7.5 million years to calculate this. You don't have that long — just make sure your digits total exactly 42.",
    check: (s) => digitSum(s) === 42,
  },

  // Stage 3 — Network & protocol forensics
  {
    id: 15,
    stage: 3,
    weight: 7,
    title: "Your password must include the classic IPv4 loopback address.",
    hint: "There's no place like 127.0.0.1.",
    check: (s) => s.includes("127.0.0.1"),
  },
  {
    id: 16,
    stage: 3,
    weight: 7,
    title: "Your password must include a standard private IPv4 subnet prefix.",
    hint: "RFC1918: 192.168. or 10.0.",
    check: (s) => /192\.168\.|10\.0\./.test(s),
  },
  {
    id: 17,
    stage: 3,
    weight: 7,
    title: "Your password must include a valid HTTP method.",
    hint: "GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH — any case works.",
    check: (s) =>
      /\b(GET|POST|PUT|DELETE|HEAD|OPTIONS|PATCH|TRACE|CONNECT)/i.test(s),
  },
  {
    id: 18,
    stage: 3,
    weight: 7,
    title: "Your password must contain a standard web port number.",
    hint: "HTTP, HTTPS, or the dev favorite: 80, 443, 8080.",
    check: (s) => /(?<!\d)(80|443|8080)(?!\d)/.test(s),
  },
  {
    id: 19,
    stage: 3,
    weight: 7,
    title: "Your password must include a SQL keyword.",
    hint: "SELECT, WHERE, DROP, JOIN, INSERT, UPDATE, DELETE, CREATE — any case.",
    check: (s) =>
      /\b(SELECT|WHERE|DROP|JOIN|INSERT|UPDATE|DELETE|CREATE|ALTER|UNION)\b/i.test(
        cleanEscapeSequences(s)
      ),
  },
  {
    id: 20,
    stage: 3,
    weight: 7,
    title:
      "Your password must include a git command that could ruin a repository.",
    hint: "The trio of regret: push --force, rebase, reset --hard.",
    check: (s) => /push --force|rebase|reset --hard/i.test(s),
  },
  {
    id: 21,
    stage: 3,
    weight: 7,
    title:
      "Your password must include a file extension from a statically typed language.",
    hint: ".cpp / .rs / .go / .java / .ts / .swift",
    check: (s) => /\.(cpp|rs|go|java|cs|ts|swift|kt)\b/i.test(s),
  },

  // Stage 4 — Concurrency & algorithmic torment
  {
    id: 22,
    stage: 4,
    weight: 8,
    title:
      "Your password must contain a palindrome substring of length ≥ 3 (simulating a circular queue).",
    hint: "aba, racecar, level — anything that reads the same both ways.",
    check: (s) => hasPalindromeSubstring(s),
  },
  {
    id: 23,
    stage: 4,
    weight: 8,
    title:
      "The number of vowels (A,E,I,O,U) in your password must be a prime number.",
    hint: "Prime vowel counts: 2, 3, 5, 7, 11…",
    check: (s) => isPrime((s.match(/[aeiou]/gi) || []).length),
  },
  {
    id: 24,
    stage: 4,
    weight: 8,
    title:
      "Your password must include a 3-letter ticker from a prediction market / order book.",
    hint: "BTC, ETH, USD, SOL, XRP, EUR, JPY, GBP — uppercase.",
    check: (s) =>
      /(USD|BTC|ETH|SOL|XRP|EUR|JPY|GBP|CAD|DOG|DOGE|ADA|BNB)/.test(s),
  },
  {
    id: 25,
    stage: 4,
    weight: 8,
    title: "Your password must include a Boolean / nil keyword.",
    hint: "true, false, null, undefined, nil, None — any case.",
    check: (s) =>
      /\b(true|false|null|undefined|nil|none|nullptr|NaN)\b/i.test(
        cleanEscapeSequences(s)
      ),
  },
  {
    id: 26,
    stage: 4,
    weight: 8,
    title: "Your password must include a hexadecimal literal.",
    hint: "Type 0x followed by hex digits, e.g. 0x4A.",
    check: (s) => /0x[0-9a-fA-F]+/.test(s),
  },
  {
    id: 27,
    stage: 4,
    weight: 8,
    title:
      "Your password must include the surname of one of the inventors of the RSA algorithm.",
    hint: "R, S, A — three names. Rivest, Shamir, Adleman.",
    check: (s) => /Rivest|Shamir|Adleman/i.test(s),
  },
  {
    id: 28,
    stage: 4,
    weight: 8,
    title:
      "Your password must contain the big-O time complexity of binary search.",
    hint: "Type it literally: O(logn), O(log n), O(logN), or O(log2n).",
    check: (s) => /O\(log[ \u2082]?[2]?\s?[nN]\)/i.test(s),
  },
  {
    id: 29,
    stage: 4,
    weight: 8,
    title: "Your password must include a valid CSS sizing unit.",
    hint: "px, em, rem, vh.",
    check: (s) => /\d(px|em|rem|vh)/i.test(s),
  },

  // Stage 5 — Final kernel panic
  {
    id: 30,
    stage: 5,
    weight: 9,
    title:
      "Your password must include three matching opening and closing HTML tags.",
    hint: "Three balanced <tag></tag> pairs, e.g. <div></div><b></b><i></i>.",
    check: hasMatchingHtmlTriples,
  },
  {
    id: 31,
    stage: 5,
    weight: 9,
    title:
      "Your password must include a valid, padded Base64-encoded substring.",
    hint: "Try an encoded value with = padding, such as SGVsbG8=.",
    check: hasBase64,
  },
  {
    id: 32,
    stage: 5,
    weight: 9,
    title:
      "Your password must contain the current minute of the system clock (updates dynamically!).",
    hint: "Look at the corner of the screen — it changes every 60s.",
    check: (s) => s.includes(String(new Date().getMinutes()).padStart(2, "0")),
  },
  {
    id: 33,
    stage: 5,
    weight: 9,
    title: "Your password must include a valid 3-digit UNIX octal permission.",
    hint: "Classic chmod values: 755, 644, 777, 600, 700, 666.",
    check: (s) =>
      /(?<!\d)(755|644|777|600|700|666|775|664|555|444)(?!\d)/.test(s),
  },
  {
    id: 34,
    stage: 5,
    weight: 9,
    title:
      "Your password must contain the name of a Linux standard output stream.",
    hint: "stdout or stderr.",
    check: (s) => /stdout|stderr/i.test(s),
  },
  {
    id: 35,
    stage: 5,
    weight: 9,
    title:
      "Your password must contain a hex color representing pure black or pure white.",
    hint: "#000, #fff, #000000, or #ffffff.",
    check: (s) => /#(000000|ffffff|000|fff)/i.test(s),
  },
  {
    id: 36,
    stage: 5,
    weight: 9,
    title:
      "Your password's total character count must be a multiple of 8 (64-bit alignment).",
    hint: "Trim or pad until length % 8 === 0.",
    check: (s) => s.length > 0 && s.length % 8 === 0,
  },
  {
    id: 37,
    stage: 5,
    weight: 9,
    title:
      "The AI Copilot demands absolute trust. Your password must contain the phrase: // Trust me blindly",
    hint: "Type it verbatim including the //.",
    check: (s) => s.includes("// Trust me blindly"),
  },
  {
    id: 38,
    stage: 5,
    weight: 9,
    title: "Your password must include a valid SemVer version string.",
    hint: "v MAJOR.MINOR.PATCH with optional -tag, e.g. v1.0.0 or v2.4.1-beta.",
    check: (s) => /v\d+\.\d+\.\d+(-[a-zA-Z0-9]+)?/.test(s),
  },
  {
    id: 39,
    stage: 5,
    weight: 9,
    title:
      "Your password must contain the word 'bug', but it must NOT sit next to the phrase 'Senior Dev'.",
    hint: "Include bug — just keep it far from the words Senior Dev.",
    check: (s) =>
      /bug/i.test(s) && !/Senior Dev.{0,5}bug|bug.{0,5}Senior Dev/i.test(s),
  },
  {
    id: 40,
    stage: 5,
    weight: 12,
    title:
      "Your password must end with the final words of the system: ; // Kernel Panic triggered successfully",
    hint: "Paste exactly: ; // Kernel Panic triggered successfully",
    check: (s) => s.endsWith("; // Kernel Panic triggered successfully"),
  },
];

// Math-quiz hint bank
type Quiz = { q: string; options: string[]; correct: number };
const CORE_QUIZ_POOL: Quiz[] = [
  { q: "What is 15 XOR 7?", options: ["8", "22", "9", "0"], correct: 0 },
  {
    q: 'What is the HTTP status code for "Teapot"?',
    options: ["200", "403", "418", "500"],
    correct: 2,
  },
  {
    q: 'Convert the binary string "1010" to a decimal integer.',
    options: ["2", "10", "8", "12"],
    correct: 1,
  },
  {
    q: "How many bits are there in 4 Bytes?",
    options: ["4", "16", "32", "64"],
    correct: 2,
  },
  {
    q: "A binary tree has a depth of 4. What is the maximum number of leaf nodes it can have?",
    options: ["4", "8", "16", "32"],
    correct: 1,
  },
  { q: "What is 65 % 8?", options: ["1", "0", "5", "8"], correct: 0 },
  {
    q: "In 64-bit architecture, how many bytes is a single standard memory pointer?",
    options: ["4", "8", "16", "64"],
    correct: 1,
  },
  {
    q: "What is the decimal value of the hexadecimal number 0x10?",
    options: ["10", "16", "24", "32"],
    correct: 1,
  },
  {
    q: "If an array index starts at 0, what is the index of the 5th element?",
    options: ["5", "4", "0", "6"],
    correct: 1,
  },
  {
    q: "What is the HTTP status code for a successful 'OK' response?",
    options: ["200", "201", "301", "400"],
    correct: 0,
  },
  {
    q: "An RGB color picker uses 8 bits per channel. What is the maximum decimal value for a single channel?",
    options: ["128", "255", "256", "512"],
    correct: 1,
  },
  {
    q: "What is the default port number used by unsecured HTTP traffic?",
    options: ["21", "80", "443", "8080"],
    correct: 1,
  },
  {
    q: "How many unique values can be represented by a single Nibble (4 bits)?",
    options: ["4", "8", "16", "32"],
    correct: 2,
  },
  {
    q: "If a loop runs from i=0 to 10 with i++, how many times does it execute?",
    options: ["10", "11", "9", "Unlimited"],
    correct: 1,
  },
  {
    q: "How many bits are in a standard IPv4 address?",
    options: ["16", "32", "64", "128"],
    correct: 1,
  },
];
const BACKUP_QUIZ_POOL: Quiz[] = [
  {
    q: "What is 12 AND 5? (bitwise, decimal)",
    options: ["4", "17", "0", "5"],
    correct: 0,
  },
  {
    q: 'What is the HTTP status code for "Unauthorized Access"?',
    options: ["400", "401", "403", "404"],
    correct: 1,
  },
  {
    q: 'Convert the binary string "1111" to a decimal integer.',
    options: ["7", "11", "15", "16"],
    correct: 2,
  },
  {
    q: "How many bits are in a single Byte?",
    options: ["4", "8", "16", "32"],
    correct: 1,
  },
  {
    q: "A full binary tree has a total of 15 nodes. What is its depth?",
    options: ["3", "4", "5", "15"],
    correct: 1,
  },
  { q: "What is 1024 % 10?", options: ["2", "4", "0", "24"], correct: 1 },
  {
    q: "How many bytes are in a standard 32-bit integer?",
    options: ["2", "4", "8", "32"],
    correct: 1,
  },
  {
    q: "What is the decimal value of the hexadecimal number 0x0F?",
    options: ["15", "0", "16", "255"],
    correct: 0,
  },
  {
    q: "If a string is 'Hello', what is the index of the character 'o'?",
    options: ["5", "4", "3", "1"],
    correct: 1,
  },
  {
    q: "A boolean expression is (True AND False) OR (NOT False). What does it evaluate to?",
    options: ["0 (False)", "1 (True)"],
    correct: 1,
  },
  {
    q: "What is the maximum number of values a single Boolean variable can hold?",
    options: ["1", "2", "4", "Infinite"],
    correct: 1,
  },
  {
    q: "What is the default port number used by secured HTTPS traffic?",
    options: ["80", "8080", "443", "22"],
    correct: 2,
  },
  {
    q: "How many combinations can you make with 3 binary switches?",
    options: ["3", "6", "8", "9"],
    correct: 2,
  },
  {
    q: 'What is the HTTP status code for "Not Found"?',
    options: ["401", "403", "404", "500"],
    correct: 2,
  },
  {
    q: 'In Git, to undo the last commit completely you use "git reset --hard HEAD~1".',
    options: ["0 (No)", "1 (Yes)"],
    correct: 1,
  },
];

function pickCampaign(): Rule[] {
  const stages: Rule[][] = [1, 2, 3, 4, 5].map((s) =>
    RULE_POOL.filter((r) => r.stage === s)
  );
  const picked: Rule[] = [];
  for (const group of stages) {
    const shuffled = [...group].sort(() => Math.random() - 0.5);
    picked.push(...shuffled.slice(0, 4));
  }
  return picked.sort((a, b) => a.stage - b.stage || a.id - b.id);
}

function Confetti() {
  const pieces = useMemo(
    () =>
      Array.from({ length: 60 }, (_, i) => ({
        id: i,
        left: Math.random() * 100,
        delay: Math.random() * 1.5,
        duration: 2.5 + Math.random() * 2.5,
        color: ["#f472b6", "#facc15", "#34d399", "#60a5fa", "#a78bfa"][i % 5],
        size: 6 + Math.random() * 8,
      })),
    []
  );
  return (
    <div className={styles.confetti}>
      {pieces.map((p) => (
        <div
          key={p.id}
          className={styles.confettiPiece}
          style={{
            left: `${p.left}%`,
            width: p.size,
            height: p.size,
            background: p.color,
            animationDuration: `${p.duration}s`,
            animationDelay: `${p.delay}s`,
          }}
        />
      ))}
    </div>
  );
}

type TerminalPhase = "idle" | "booting" | "challenge" | "unlocked";
const BOOT_LINE_TEMPLATES = [
  "fetching_hint...",
  "connecting_to_codey_server...",
  "auth: ok · latency {ms}ms",
  "challenge_loaded ✓",
];

function pickCampaignStable(): Rule[] {
  const stages: Rule[][] = [1, 2, 3, 4, 5].map((s) =>
    RULE_POOL.filter((r) => r.stage === s)
  );
  return stages.flatMap((group) => group.slice(0, 4));
}

export function CrashTheServer() {
  const [isLoaded, setIsLoaded] = useState(false);
  const [input, setInput] = useState("");
  const [won, setWon] = useState(false);
  const [campaign, setCampaign] = useState<Rule[]>(() => pickCampaignStable());
  const [unlockedHints, setUnlockedHints] = useState<Set<number>>(new Set());
  const [quizTargetRuleId, setQuizTargetRuleId] = useState<number | null>(null);
  const [quiz, setQuiz] = useState<Quiz | null>(null);
  const [quizPicked, setQuizPicked] = useState<number | null>(null); // highlighted but not submitted
  const [quizPairIndex, setQuizPairIndex] = useState(0);
  const [quizUsingBackup, setQuizUsingBackup] = useState(false);
  const [quizIsFirstTry, setQuizIsFirstTry] = useState(true);
  const [quizFirstTrySuccess, setQuizFirstTrySuccess] = useState(false);
  const [quizShowHint, setQuizShowHint] = useState(false);
  const [terminalPhase, setTerminalPhase] = useState<TerminalPhase>("idle");
  const [bootStep, setBootStep] = useState(0);
  const [typedHint, setTypedHint] = useState("");
  const [hintLatency, setHintLatency] = useState(42);
  const [foldedStages, setFoldedStages] = useState<Set<number>>(new Set());
  const [usedQuizIndices, setUsedQuizIndices] = useState<Set<number>>(
    new Set()
  );
  const [milestoneMessage, setMilestoneMessage] = useState<string | null>(null);
  const shownMilestonesRef = useRef<Set<number>>(new Set());
  const completedStagesRef = useRef<Set<number>>(new Set());
  const [hasSeenTutorial, setHasSeenTutorial] = useState(false);

  // tick once a second so Rule 32 re-evaluates against system clock
  const [, setTick] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setTick((t) => t + 1), 1000);
    return () => clearInterval(id);
  }, []);

  const totalWeight = campaign.reduce((a, r) => a + r.weight, 0);
  const passed = campaign.map((r) => r.check(input));
  const earned = passed.reduce(
    (a, ok, i) => a + (ok ? campaign[i].weight : 0),
    0
  );
  const progress = Math.round((earned / totalWeight) * 100);
  const allPassed = passed.every(Boolean);

  useEffect(() => {
    if (allPassed && input.length > 0) setWon(true);
  }, [allPassed, input]);

  // Milestone encouraging messages at 39 / 56 / 87 %
  useEffect(() => {
    const latest = [87, 56, 39].find(
      (t) => progress >= t && !shownMilestonesRef.current.has(t)
    );
    if (!latest) return;
    shownMilestonesRef.current.add(latest);
    const pool = MILESTONE_POOLS[latest];
    const msg = pool[Math.floor(Math.random() * pool.length)];
    setMilestoneMessage(msg);
    const t = window.setTimeout(() => setMilestoneMessage(null), 4500);
    return () => clearTimeout(t);
  }, [progress]);

  // Load game state from localStorage on mount (hydration check)
  useEffect(() => {
    setIsLoaded(true);
    try {
      const saved = localStorage.getItem("crash_the_server_state");
      if (saved) {
        const parsed = JSON.parse(saved) as {
          password?: string;
          unlockedHints?: number[];
          campaignRuleIds?: number[];
          foldedStages?: number[];
          usedQuizIndices?: number[];
          hasSeenTutorial?: boolean;
        } | null;
        if (parsed) {
          if (parsed.password !== undefined) setInput(parsed.password);
          if (parsed.unlockedHints && Array.isArray(parsed.unlockedHints)) {
            setUnlockedHints(new Set(parsed.unlockedHints));
          }
          if (parsed.campaignRuleIds && Array.isArray(parsed.campaignRuleIds)) {
            const rules = parsed.campaignRuleIds
              .map((id: number) => RULE_POOL.find((r) => r.id === id))
              .filter((r: Rule | undefined): r is Rule => !!r);
            if (rules.length === 20) {
              setCampaign(rules);
            }
          }
          if (parsed.foldedStages && Array.isArray(parsed.foldedStages)) {
            setFoldedStages(new Set(parsed.foldedStages));
          }
          if (parsed.usedQuizIndices && Array.isArray(parsed.usedQuizIndices)) {
            setUsedQuizIndices(new Set(parsed.usedQuizIndices));
          }
          if (parsed.hasSeenTutorial) setHasSeenTutorial(true);
        }
      } else {
        setCampaign(pickCampaign());
      }
    } catch (e) {
      console.warn("Unable to restore saved game state:", e);
      setCampaign(pickCampaign());
    }
  }, []);

  // Save game state to localStorage
  useEffect(() => {
    if (!isLoaded) return;
    const state = {
      password: input,
      unlockedHints: Array.from(unlockedHints),
      campaignRuleIds: campaign.map((r) => r.id),
      foldedStages: Array.from(foldedStages),
      usedQuizIndices: Array.from(usedQuizIndices),
      hasSeenTutorial,
    };
    try {
      localStorage.setItem("crash_the_server_state", JSON.stringify(state));
    } catch (e) {
      console.warn("Unable to save game state:", e);
    }
  }, [
    input,
    unlockedHints,
    campaign,
    foldedStages,
    usedQuizIndices,
    hasSeenTutorial,
    isLoaded,
  ]);

  const closeTutorial = () => setHasSeenTutorial(true);
  const tutorialVisible = isLoaded && !hasSeenTutorial;

  const reset = () => {
    setInput("");
    setWon(false);
    setCampaign(pickCampaign());
    setUnlockedHints(new Set());
    setTerminalPhase("idle");
    setQuiz(null);
    setQuizPicked(null);
    setQuizTargetRuleId(null);
    setQuizIsFirstTry(true);
    setQuizFirstTrySuccess(false);
    setQuizShowHint(false);
    setBootStep(0);
    setTypedHint("");
    setFoldedStages(new Set());
    setUsedQuizIndices(new Set());
    setMilestoneMessage(null);
    shownMilestonesRef.current = new Set();
    completedStagesRef.current = new Set();
    try {
      localStorage.removeItem("crash_the_server_state");
    } catch (e) {
      console.warn("Unable to remove saved game state:", e);
    }
  };

  const firstFailingIndex = passed.findIndex((ok) => !ok);
  const lockedRule =
    firstFailingIndex >= 0 ? campaign[firstFailingIndex] : null;

  // reset the terminal whenever a new rule becomes locked
  useEffect(() => {
    setTerminalPhase("idle");
    setQuiz(null);
    setQuizPicked(null);
    setQuizIsFirstTry(true);
    setQuizFirstTrySuccess(false);
    setQuizShowHint(false);
    setBootStep(0);
    setTypedHint("");
  }, [lockedRule?.id]);

  // If the current locked rule's hint has already been unlocked, automatically show it
  useEffect(() => {
    if (
      lockedRule &&
      unlockedHints.has(lockedRule.id) &&
      terminalPhase === "idle"
    ) {
      setTerminalPhase("unlocked");
    }
  }, [lockedRule, unlockedHints, terminalPhase]);

  // simulate the server "booting" a few log lines
  useEffect(() => {
    if (terminalPhase !== "booting") return;
    if (bootStep >= BOOT_LINE_TEMPLATES.length) {
      const t = window.setTimeout(() => setTerminalPhase("challenge"), 300);
      return () => clearTimeout(t);
    }
    const t = window.setTimeout(
      () => setBootStep((s) => s + 1),
      380 + Math.random() * 220
    );
    return () => clearTimeout(t);
  }, [terminalPhase, bootStep]);

  // type out decrypted hint letter by letter
  useEffect(() => {
    if (terminalPhase !== "unlocked" || !lockedRule) return;
    const full = lockedRule.hint;
    let i = 0;
    setTypedHint("");
    const id = window.setInterval(() => {
      i += 1;
      setTypedHint(full.slice(0, i));
      if (i >= full.length) clearInterval(id);
    }, 28);
    return () => clearInterval(id);
  }, [terminalPhase, lockedRule]);

  const openQuiz = () => {
    if (!lockedRule || unlockedHints.has(lockedRule.id)) return;

    // Filter to find indices that haven't been used yet in this session
    const unusedIndices = Array.from(
      { length: CORE_QUIZ_POOL.length },
      (_, i) => i
    ).filter((i) => !usedQuizIndices.has(i));

    let idx: number;
    if (unusedIndices.length > 0) {
      idx = unusedIndices[Math.floor(Math.random() * unusedIndices.length)];
    } else {
      // If we ran out of unique questions, reset and pick from all
      idx = Math.floor(Math.random() * CORE_QUIZ_POOL.length);
    }

    setUsedQuizIndices((prev) => {
      const next = new Set(prev);
      if (unusedIndices.length === 0) {
        next.clear();
      }
      next.add(idx);
      return next;
    });

    setQuizPairIndex(idx);
    setQuizUsingBackup(false);
    setQuiz(CORE_QUIZ_POOL[idx]);
    setQuizPicked(null);
    setQuizIsFirstTry(true);
    setQuizFirstTrySuccess(false);
    setQuizShowHint(false);
    setQuizTargetRuleId(lockedRule.id);
    setHintLatency(30 + Math.floor(Math.random() * 70));
    setTypedHint("");
    setBootStep(0);
    setTerminalPhase("booting");
  };

  // Select an option (highlight only — does NOT immediately submit)
  const pickOption = (i: number) => {
    if (!quiz || quizShowHint) return;
    setQuizPicked(i);
  };

  // Submit the selected option
  const submitQuiz = () => {
    if (quizPicked === null || !quiz) return;
    if (quizPicked === quiz.correct) {
      if (quizIsFirstTry) setQuizFirstTrySuccess(true);
      if (quizTargetRuleId != null) {
        setUnlockedHints((prev) => new Set([...prev, quizTargetRuleId]));
      }
      setTerminalPhase("unlocked");
    } else {
      setQuizIsFirstTry(false);
      setQuizShowHint(true);
    }
  };

  const handleRetry = () => {
    setQuizPicked(null);
    setQuizShowHint(false);
  };

  const rerollQuiz = () => {
    const useBackup = !quizUsingBackup;
    setQuizUsingBackup(useBackup);
    setQuiz((useBackup ? BACKUP_QUIZ_POOL : CORE_QUIZ_POOL)[quizPairIndex]);
    setQuizPicked(null);
    setQuizIsFirstTry(true);
    setQuizFirstTrySuccess(false);
    setQuizShowHint(false);
  };

  const closeChallenge = () => {
    setTerminalPhase("idle");
    setQuiz(null);
    setQuizPicked(null);
    setQuizIsFirstTry(true);
    setQuizFirstTrySuccess(false);
    setQuizShowHint(false);
    setBootStep(0);
  };

  const toggleStageExpansion = (s: number) => {
    const next = new Set(foldedStages);
    if (next.has(s)) {
      next.delete(s);
    } else {
      next.add(s);
    }
    setFoldedStages(next);
  };

  // Auto-fold a stage the moment it newly becomes fully passed; auto-unfold
  // if a rule inside it breaks again. Tracked against the stage's own
  // previous completion state (not against foldedStages) so that manually
  // re-opening an already-completed stage isn't immediately re-collapsed by
  // this effect on the next render (`passed` is a fresh array every render).
  useEffect(() => {
    const previouslyCompleted = completedStagesRef.current;
    const nowCompleted = new Set<number>();
    setFoldedStages((prev) => {
      const next = new Set(prev);
      let changed = false;
      [1, 2, 3, 4, 5].forEach((s) => {
        const stageRules = campaign.filter((r) => r.stage === s);
        const allDone = stageRules.every((r) => passed[campaign.indexOf(r)]);
        if (allDone) nowCompleted.add(s);
        if (allDone && !previouslyCompleted.has(s)) {
          next.add(s);
          changed = true;
        }
        if (!allDone && previouslyCompleted.has(s)) {
          next.delete(s);
          changed = true;
        }
      });
      return changed ? next : prev;
    });
    completedStagesRef.current = nowCompleted;
  }, [passed, campaign]);

  const renderRuleCard = (rule: Rule, index: number, ok: boolean) => {
    return (
      <div
        key={rule.id}
        className={
          ok
            ? `${styles.rule} ${styles.rulePassed}`
            : `${styles.rule} ${styles.ruleFailed}`
        }
      >
        <div className={styles.ruleRow}>
          <div
            className={
              ok
                ? `${styles.ruleIcon} ${styles.ruleIconOk}`
                : `${styles.ruleIcon} ${styles.ruleIconFail}`
            }
          >
            {ok ? "✓" : "✗"}
          </div>
          <div className={styles.ruleBody}>
            <span className={styles.ruleMeta}>
              Stage {rule.stage} · Rule {rule.id}
            </span>
            <p
              className={
                rule.title.length > 100
                  ? `${styles.ruleTitle} text-sm`
                  : styles.ruleTitle
              }
            >
              {rule.title}
            </p>
            {!ok && unlockedHints.has(rule.id) && (
              <p className={styles.ruleHintNotice}>
                💡 Hint revealed in the Math Intercom →
              </p>
            )}
          </div>
        </div>
      </div>
    );
  };

  return (
    <section className={styles.game}>
      <div className={styles.layout}>
        <div className={styles.main}>
          <div className={styles.progress}>
            <div className={styles.progressHeading}>
              <span className={styles.progressLabel}>Server Overload</span>
              <span className={styles.progressValue}>
                {progress}
                <span className={styles.progressPercent}>%</span>
              </span>
            </div>
            <div className={styles.progressTrack}>
              <div
                className={
                  allPassed
                    ? `${styles.progressFill} ${styles.progressFillComplete}`
                    : styles.progressFill
                }
                style={{ width: `${progress}%` }}
              />
            </div>

            {/* Milestone banner */}
            {milestoneMessage && (
              <div className={styles.milestoneBanner}>
                🚨 {milestoneMessage}
              </div>
            )}
          </div>

          <div className={styles.inputCard}>
            <label className={styles.inputLabel}>Enter your password</label>
            <textarea
              autoFocus
              value={input}
              onChange={(e) => setInput(e.target.value)}
              spellCheck={false}
              rows={3}
              placeholder="Start typing to make it crash..."
              className={styles.input}
            />
            <div className={styles.inputMeta}>
              <span>Characters: {input.length}</span>
              <span>
                {passed.filter(Boolean).length} / {campaign.length} rules passed
              </span>
            </div>
          </div>

          <div className={styles.rules}>
            {(() => {
              // Determine which stages are fully completed
              const completedStageSet = new Set(
                [1, 2, 3, 4, 5].filter((s) =>
                  campaign
                    .filter((r) => r.stage === s)
                    .every((r) => passed[campaign.indexOf(r)])
                )
              );

              // 1. TOP: the currently failing/locked rule
              const failingCards = lockedRule
                ? [
                    renderRuleCard(
                      lockedRule,
                      campaign.indexOf(lockedRule),
                      false
                    ),
                  ]
                : [];

              // 2. MIDDLE: passing rules NOT in a completed stage
              const passingCards = campaign
                .map((r, i) => ({ rule: r, ok: passed[i], idx: i }))
                .filter(
                  ({ rule, ok }) => ok && !completedStageSet.has(rule.stage)
                )
                .map(({ rule, idx }) => renderRuleCard(rule, idx, true));

              // 3. BOTTOM: completed stage folders (always collapsed by default)
              const folderCards = [...completedStageSet].sort().map((s) => {
                const isFolded = foldedStages.has(s);
                const stageRules = campaign.filter((r) => r.stage === s);
                return (
                  <div key={`stage-folder-${s}`} className={styles.stageFolder}>
                    <button
                      type="button"
                      onClick={() => toggleStageExpansion(s)}
                      className={styles.stageFolderHeader}
                    >
                      <span>
                        📁 Stage {s} · All {stageRules.length} rules passed ✓
                      </span>
                      <span>{isFolded ? "▼" : "▲"}</span>
                    </button>
                    {!isFolded && (
                      <div className={styles.stageFolderContent}>
                        {stageRules.map((r) =>
                          renderRuleCard(r, campaign.indexOf(r), true)
                        )}
                      </div>
                    )}
                  </div>
                );
              });

              return [...failingCards, ...passingCards, ...folderCards];
            })()}
          </div>
        </div>

        {/* Right-side mini-terminal */}
        <aside className={styles.intercom}>
          <div className={styles.terminalWindow}>
            {/* Terminal Title Bar */}
            <div className={styles.terminalTitleBar}>
              <div className={styles.terminalControls}>
                <span className={`${styles.terminalDot} ${styles.dotRed}`} />
                <span className={`${styles.terminalDot} ${styles.dotYellow}`} />
                <span className={`${styles.terminalDot} ${styles.dotGreen}`} />
              </div>
              <span className={styles.terminalTitle}>
                📟 codey@helpdesk · ~/hints
              </span>
              <span
                className={styles.terminalBadge}
                style={{
                  backgroundColor: lockedRule
                    ? "rgba(185, 28, 28, 0.1)"
                    : "rgba(16, 185, 129, 0.1)",
                  color: lockedRule ? "#b91c1c" : "#10b981",
                }}
              >
                {lockedRule ? `RULE ${lockedRule.id} · LOCKED` : "ALL CLEAR"}
              </span>
            </div>

            {/* Terminal Body */}
            <div className={styles.terminalBody}>
              <p className={styles.terminalTextMuted}>
                codey-helpdesk v1.4.0 — type a password, request a hint when
                stuck.
              </p>
              <p className={styles.terminalTextMuted}>ready.</p>

              {terminalPhase !== "idle" && lockedRule && (
                <div className={styles.terminalCommandBlock}>
                  <p className={styles.terminalCmd}>
                    $ request_hint --rule {lockedRule.id}
                  </p>
                  {BOOT_LINE_TEMPLATES.slice(0, bootStep).map((line, i) => (
                    <p key={i} className={styles.terminalResponse}>
                      &gt; {line.replace("{ms}", String(hintLatency))}
                    </p>
                  ))}
                </div>
              )}

              {terminalPhase === "unlocked" && (
                <p className={styles.terminalResponse}>
                  &gt; decrypting hint...
                </p>
              )}
            </div>

            {/* Challenge Card inside terminal */}
            {terminalPhase === "challenge" && quiz && (
              <div className={styles.challengeCard}>
                <div className={styles.challengeHeader}>
                  <span className={styles.challengeIndicator} />
                  <span className={styles.challengeLabel}>
                    Challenge · pick one to unlock hint
                  </span>
                </div>
                <p className={styles.challengeQuestion}>{quiz.q}</p>

                {/* Options (highlight on click; Submit triggers the real check) */}
                <div className={styles.challengeOptions}>
                  {quiz.options.map((opt, i) => {
                    const letter = String.fromCharCode(65 + i);
                    const isPicked = quizPicked === i;
                    let optStyle = styles.optionBtn;
                    if (isPicked) optStyle += ` ${styles.optionBtnSelected}`;
                    return (
                      <button
                        key={i}
                        onClick={() => pickOption(i)}
                        disabled={quizShowHint}
                        className={optStyle}
                      >
                        <span
                          className={styles.optionLetter}
                          style={{
                            backgroundColor: isPicked ? "#6366f1" : "#f1f1ef",
                            color: isPicked ? "white" : "#555",
                          }}
                        >
                          {letter}
                        </span>
                        {opt}
                      </button>
                    );
                  })}
                </div>

                {/* Submit button — only visible when an option is selected and hint not shown */}
                {quizPicked !== null && !quizShowHint && (
                  <button onClick={submitQuiz} className={styles.quizSubmitBtn}>
                    $ submit_answer
                  </button>
                )}

                {/* Wrong answer: show detailed hint + retry */}
                {quizShowHint && (
                  <div className={styles.wrongAnswerPanel}>
                    <p className={styles.wrongAnswerTitle}>
                      Sadly, you didn&apos;t get it right, here is the hint we
                      give it to you!
                    </p>
                    {lockedRule && RULE_DETAILED_HINTS[lockedRule.id] && (
                      <div className={styles.detailedHintBox}>
                        <p className={styles.detailedHintLabel}>💡 Hint</p>
                        <p className={styles.detailedHintText}>
                          {RULE_DETAILED_HINTS[lockedRule.id].hint}
                        </p>
                        {RULE_DETAILED_HINTS[lockedRule.id].term && (
                          <div className={styles.detailedHintTerm}>
                            <p className={styles.detailedHintTermLabel}>
                              📖 Terminology
                            </p>
                            <p className={styles.detailedHintTermText}>
                              {RULE_DETAILED_HINTS[lockedRule.id].term}
                            </p>
                          </div>
                        )}
                      </div>
                    )}
                    <p className={styles.wrongAnswerFootnote}>
                      retry and get it right on the first try if you want to get
                      more hint on this rule:
                    </p>
                    <button onClick={handleRetry} className={styles.retryBtn}>
                      ↩ Retry
                    </button>
                  </div>
                )}

                {/* Bottom actions (hidden when wrong-hint panel is visible) */}
                {!quizShowHint && (
                  <div className={styles.challengeActions}>
                    <button onClick={rerollQuiz} className={styles.actionBtn}>
                      $ swap_question
                    </button>
                    <button
                      onClick={closeChallenge}
                      className={styles.actionBtn}
                    >
                      esc
                    </button>
                  </div>
                )}
              </div>
            )}

            {/* Decrypted Hint */}
            {terminalPhase === "unlocked" && lockedRule && (
              <>
                {quizFirstTrySuccess && (
                  <div className={styles.firstTrySuccessPanel}>
                    🎉 You got it right on the first try!
                  </div>
                )}
                <div className={styles.decryptedPanel}>
                  <div className={styles.decryptedLabel}>
                    decrypted_hint.txt
                  </div>
                  <p className={styles.decryptedText}>
                    💡 {typedHint}
                    {typedHint.length < lockedRule.hint.length && (
                      <span className={styles.terminalCursor}>▌</span>
                    )}
                  </p>
                </div>
              </>
            )}

            {/* Bottom Command Bar */}
            <div className={styles.terminalBottomBar}>
              <p className={styles.terminalBottomPrompt}>
                $ stuck? request a hint
              </p>
              <div className={styles.terminalBottomActions}>
                <button
                  disabled={
                    !lockedRule ||
                    unlockedHints.has(lockedRule.id) ||
                    terminalPhase === "booting" ||
                    terminalPhase === "challenge"
                  }
                  onClick={openQuiz}
                  className={styles.terminalSubmitBtn}
                >
                  {!lockedRule
                    ? "Request Hint"
                    : unlockedHints.has(lockedRule.id)
                    ? "Hint already revealed"
                    : terminalPhase === "booting"
                    ? "connecting…"
                    : terminalPhase === "challenge"
                    ? "challenge in progress…"
                    : "Request Hint"}
                </button>
                <button
                  onClick={reset}
                  title="New campaign (reshuffle rules)"
                  className={styles.terminalResetBtn}
                >
                  ↻
                </button>
              </div>
            </div>
          </div>
        </aside>
      </div>

      {won && (
        <>
          <Confetti />
          <div className={styles.overlay} onClick={reset}>
            <div
              className={styles.winModal}
              onClick={(e) => e.stopPropagation()}
            >
              <div className={styles.winEmoji}>🏆</div>
              <h2 className={styles.winTitle}>You did it!</h2>
              <p className={styles.winText}>
                You crashed the server with a single password
                <br />
                and earned the{" "}
                <span className={styles.winHighlight}>Turing Award</span>!
              </p>
              <p className={styles.winStats}>
                Hints used: <strong>{unlockedHints.size}</strong>
              </p>
              <div className={styles.winPasswordPanel}>
                <div className={styles.winPasswordLabel}>
                  Your winning password
                </div>
                <div className={styles.winPasswordValue}>{input}</div>
              </div>
              <button onClick={reset} className={styles.primaryButtonLarge}>
                New campaign ✨
              </button>
            </div>
          </div>
        </>
      )}

      {tutorialVisible && (
        <div className={styles.overlay} onClick={closeTutorial}>
          <div
            className={styles.tutorialModal}
            onClick={(e) => e.stopPropagation()}
          >
            <button
              onClick={closeTutorial}
              aria-label="Close tutorial"
              className={styles.tutorialCloseX}
            >
              ✕
            </button>
            <div className={styles.tutorialEmoji}>🖥️💥</div>
            <h2 className={styles.tutorialTitle}>Incoming Transmission</h2>
            <p className={styles.tutorialStory}>
              <em>The CSC server room, 2:47 AM.</em>
              <br />
              <br />
              The onboarding server has been running unpatched for six years,
              held together by duct tape and a password policy nobody has ever
              fully read. Tonight, you&apos;ve been given root access — and one
              simple task.
              <br />
              <br />
              Your mission: craft a single password that satisfies{" "}
              <em>every</em> rule the system throws at you — from basic
              complexity checks to full-blown production nightmares: kernel
              panics, memory leaks, deadlocks, and worse. Stack enough rules at
              once, and the server&apos;s fragile little heart will finally give
              out.
            </p>
            <div className={styles.tutorialSectionLabel}>🎯 Your Goal</div>
            <p className={styles.tutorialSectionText}>
              Come up with the perfect password that follows all the required
              rules — simultaneously.
            </p>
            <div className={styles.tutorialSectionLabel}>💡 Hint</div>
            <p className={styles.tutorialSectionText}>
              Stuck on a rule? Ask Cody for help at the terminal on the right.
              Answer Cody&apos;s question correctly, and you&apos;ll unlock a
              hint to help you crack it.
            </p>
            <button
              onClick={closeTutorial}
              className={styles.primaryButtonLarge}
            >
              Let&apos;s crash it →
            </button>
          </div>
        </div>
      )}
    </section>
  );
}
