import React, { useRef, useState, useEffect } from "react";
import { Check, BookOpen, Lightbulb, Zap, Star, Target } from "lucide-react";
import { PracticeFromDataset } from "../../../components/lessons/LessonShell";
import {
  WORDS_CONTEXT_EASY,
  WORDS_CONTEXT_MEDIUM,
} from "../../../data/rw/words-in-context";
import ContextEliminationWidget, {
  type VocabExercise,
} from "../../../components/lessons/ContextEliminationWidget";
import RevealCardGrid from "../../../components/lessons/RevealCardGrid";
import useScrollReveal from "../../../components/lessons/useScrollReveal";

interface LessonProps {
  onFinish?: () => void;
}

const VOCAB_EXERCISES: VocabExercise[] = [
  {
    sentence:
      "The documentary filmmaker hoped to ______ audiences with her unflinching portrayal of poverty, prompting them to advocate for social change.",
    word: "______",
    question: "Which word most logically completes the sentence?",
    options: [
      {
        id: "a",
        definition: "entertain — to provide amusement",
        isCorrect: false,
        elimReason:
          "The context signals a serious goal (advocacy, social change), not mere amusement.",
      },
      {
        id: "b",
        definition: "galvanize — to shock or excite into taking action",
        isCorrect: true,
        elimReason: "",
      },
      {
        id: "c",
        definition: "placate — to make less angry or upset",
        isCorrect: false,
        elimReason:
          "Contradicts the goal of prompting advocacy; placating suggests calming, not motivating.",
      },
      {
        id: "d",
        definition: "perplex — to confuse someone greatly",
        isCorrect: false,
        elimReason:
          "Confusing audiences would undermine the filmmaker's goal of advocacy.",
      },
    ],
  },
  {
    sentence:
      "Though often described as a recluse, the novelist was in fact quite ______, hosting weekly salons attended by scientists, poets, and politicians.",
    word: "______",
    question: "Which word most logically completes the sentence?",
    options: [
      {
        id: "a",
        definition: "gregarious — fond of company; sociable",
        isCorrect: true,
        elimReason: "",
      },
      {
        id: "b",
        definition: "reticent — not revealing thoughts or feelings",
        isCorrect: false,
        elimReason:
          'Reticent reinforces "recluse" rather than contrasting with it; the word "though" signals a contradiction.',
      },
      {
        id: "c",
        definition: "pensive — engaged in deep thought",
        isCorrect: false,
        elimReason:
          "Being thoughtful does not explain weekly social gatherings.",
      },
      {
        id: "d",
        definition: "fastidious — very attentive to detail",
        isCorrect: false,
        elimReason:
          "Attention to detail is unrelated to the sociability implied by hosting salons.",
      },
    ],
  },
  {
    sentence:
      "The economist's forecast proved remarkably ______: every indicator she had cited came to pass within two years.",
    word: "______",
    question: "Which word most logically completes the sentence?",
    options: [
      {
        id: "a",
        definition: "optimistic — hopeful about the future",
        isCorrect: false,
        elimReason:
          "Optimistic describes an attitude, not the accuracy of a forecast.",
      },
      {
        id: "b",
        definition: "prescient — having knowledge of events before they occur",
        isCorrect: true,
        elimReason: "",
      },
      {
        id: "c",
        definition: "contentious — causing disagreement",
        isCorrect: false,
        elimReason:
          'The colon and "every indicator came to pass" signals accuracy, not controversy.',
      },
      {
        id: "d",
        definition: "redundant — not or no longer needed; superfluous",
        isCorrect: false,
        elimReason:
          "Redundancy contradicts the idea that every prediction proved true.",
      },
    ],
  },
];

const CLAIM_VERBS = [
  {
    label: "Make a claim",
    words: "advance, hypothesize, posit, proffer, speculate",
  },
  { label: "Support a claim", words: "bolster, buttress, substantiate" },
  {
    label: "Question a claim",
    words: "rebut, refute, ambivalence, skepticism",
  },
  { label: "Draw a conclusion", words: "infer, surmise" },
  { label: "Large amount", words: "multitude, plethora, profusion" },
  { label: "Small amount", words: "dearth, paucity" },
  { label: "Different/diverse", words: "disparate, eclectic, heterogeneous" },
  { label: "Noticeable/striking", words: "conspicuous, distinctive, salient" },
  { label: "Inborn", words: "inherent, innate, intrinsic" },
];

const SCIENCE_TERMS = [
  { word: "empirical", def: "Relying on hard, observable data" },
  { word: "hierarchy", def: "System of rank; opposite of egalitarian" },
  { word: "indigenous", def: "Native to a region" },
  { word: "inhibit", def: "To prevent or impede a response" },
  { word: "predisposed", def: "Having a tendency toward something" },
  { word: "replicate", def: "To repeat an experiment with same results" },
  { word: "stimulus", def: "Something that provokes a specific response" },
  { word: "symbiotic", def: "Beneficial interaction between two organisms" },
  { word: "taxonomy", def: "A classification system" },
  { word: "velocity", def: "Speed" },
];

const ALL_VOCAB_KEYS = [
  ...CLAIM_VERBS.map((v) => v.label),
  ...SCIENCE_TERMS.map((t) => t.word),
];

const SECOND_MEANINGS = [
  { label: "arrest", content: "To stop (not just apprehend a criminal)" },
  {
    label: "assume",
    content: "To take on responsibility for; to acquire a new position",
  },
  {
    label: "bent",
    content:
      "A liking or natural tendency toward something (synonym: proclivity)",
  },
  { label: "capacity", content: "Ability" },
  {
    label: "channel",
    content: "To direct energy or resources toward a specific purpose",
  },
  { label: "check", content: "To restrain, control, or reduce" },
  { label: "coin", content: "To invent (e.g., coin a phrase)" },
  { label: "compromise", content: "To endanger or make vulnerable" },
  {
    label: "discriminating",
    content: "Able to make fine distinctions (positive word)",
  },
  { label: "doctor", content: "To tamper with" },
  {
    label: "economy / economical",
    content: "Thrift; using few words or resources (not about money)",
  },
  {
    label: "exploit",
    content: "To make use of (no negative connotation required)",
  },
  { label: "facility", content: "Ease; ability to do something effortlessly" },
  { label: "fluid", content: "Able to change shape; not rigid" },
  { label: "foil", content: "To put a stop to; to thwart" },
  { label: "harbor", content: "To hold or possess (e.g., harbor a belief)" },
  {
    label: "plastic",
    content: "Malleable; able to be changed (as in brain plasticity)",
  },
  { label: "reserve / reservations", content: "To hold off; misgivings" },
  { label: "sound", content: "Firm, stable, reliable, valid" },
  { label: "static", content: "Unchanging; in a state of stasis" },
  {
    label: "table / shelve",
    content: "To reject or discard an idea or proposal",
  },
  { label: "uniform", content: "Constant; unvarying" },
  { label: "upset", content: "To interfere with an expected outcome" },
];

const NEGATIVE_LOOKING = [
  {
    label: "critic / criticism",
    content:
      "A person who writes commentary, positive or negative; not inherently hostile",
  },
  {
    label: "discerning",
    content: "Perceptive; able to make fine distinctions",
  },
  { label: "ineffable", content: "Beyond words; sublime; indescribable" },
  { label: "infallible", content: "Unable to be wrong; perfectly reliable" },
  { label: "ingenious", content: "Clever, brilliant" },
  { label: "ingenuous", content: "Naive (note: distinct from ingenious)" },
  { label: "inimitable", content: "Unique; one-of-a-kind" },
  { label: "innocuous", content: "Harmless" },
  { label: "invaluable", content: "Having immense value; priceless" },
  { label: "unassuming", content: "Modest" },
  { label: "unqualified", content: "Absolute (e.g., unqualified success)" },
];

const EBRWWordsInContextLesson: React.FC<LessonProps> = ({ onFinish }) => {
  const [activeSection, setActiveSection] = useState(0);
  const [revealedVocab, setRevealedVocab] = useState<Set<string>>(new Set());

  const toggleVocab = (key: string) => {
    setRevealedVocab((prev) => {
      const next = new Set(prev);
      if (next.has(key)) next.delete(key);
      else next.add(key);
      return next;
    });
  };
  const sectionsRef = useRef<(HTMLElement | null)[]>([]);

  useEffect(() => {
    const observers: IntersectionObserver[] = [];
    sectionsRef.current.forEach((el, idx) => {
      if (!el) return;
      const obs = new IntersectionObserver(
        ([entry]) => {
          if (entry.isIntersecting) setActiveSection(idx);
        },
        { threshold: 0.3 },
      );
      obs.observe(el);
      observers.push(obs);
    });
    return () => observers.forEach((o) => o.disconnect());
  }, []);

  useScrollReveal();

  const scrollToSection = (index: number) => {
    setActiveSection(index);
    sectionsRef.current[index]?.scrollIntoView({ behavior: "smooth" });
  };

  const SectionMarker = ({
    index,
    title,
    icon: Icon,
  }: {
    index: number;
    title: string;
    icon: React.ComponentType<React.SVGProps<SVGSVGElement>>;
  }) => {
    const isActive = activeSection === index;
    const isPast = activeSection > index;
    return (
      <button
        onClick={() => scrollToSection(index)}
        className={`flex items-center gap-3 p-3 w-full rounded-lg text-left transition-all ${isActive ? "bg-fuchsia-50" : "hover:bg-slate-50"}`}
      >
        <div
          className={`w-8 h-8 rounded-full flex items-center justify-center shrink-0
          ${isActive ? "bg-fuchsia-600 text-white" : isPast ? "bg-fuchsia-400 text-white" : "bg-slate-200 text-slate-500"}`}
        >
          {isPast ? <Check className="w-4 h-4" /> : <Icon />}
        </div>
        <p
          className={`text-sm font-bold ${isActive ? "text-fuchsia-900" : "text-slate-600"}`}
        >
          {title}
        </p>
      </button>
    );
  };

  return (
    <div className="flex flex-col lg:flex-row min-h-screen">
      <aside className="w-full lg:w-64 lg:fixed lg:top-14 lg:bottom-0 lg:overflow-y-auto p-4 border-r border-slate-200 bg-slate-50 z-0 hidden lg:block">
        <nav className="space-y-2 pt-6">
          <SectionMarker
            index={0}
            title="Sentence Completions"
            icon={BookOpen}
          />
          <SectionMarker index={1} title="Context Signals" icon={Star} />
          <SectionMarker
            index={2}
            title="Meaning in Context"
            icon={Lightbulb}
          />
          <SectionMarker index={3} title="Elimination Practice" icon={Target} />
          <SectionMarker index={4} title="Practice Questions" icon={Zap} />
        </nav>
      </aside>

      <div className="flex-1 lg:ml-64 md:p-12 max-w-4xl mx-auto">
        {/* ── SECTION 0: SENTENCE COMPLETIONS ── */}
        <section
          ref={(el) => {
            sectionsRef.current[0] = el;
          }}
          className="min-h-screen flex flex-col justify-center mb-24 pt-20 lg:pt-0"
        >
          <div className="inline-flex items-center gap-2 bg-fuchsia-100 text-fuchsia-700 px-3 py-1 rounded-full text-xs font-bold uppercase tracking-wider mb-4 w-fit">
            Craft &amp; Structure — Domain 1
          </div>
          <h2 className="text-4xl font-extrabold text-slate-900 mb-2">
            Words in Context
          </h2>
          <p className="text-lg text-slate-500 mb-8">
            Identify the signal, determine the charge, predict your answer
            before reading options — context determines meaning, not the
            dictionary.
          </p>

          {/* Two Question Subtypes */}
          <div className="bg-fuchsia-50 border border-fuchsia-200 rounded-2xl p-6 mb-8 space-y-4 scroll-reveal">
            <h3 className="text-lg font-bold text-fuchsia-900">
              The Two Question Subtypes
            </h3>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {[
                {
                  num: "A",
                  rule: "Sentence Completions",
                  stem: '"Which choice completes the text with the most logical and precise word or phrase?"',
                  desc: "A blank must be filled. Answer choices include challenging academic vocabulary (epitomize, succinct, anomaly). Requires both contextual reasoning AND knowledge of word meanings.",
                },
                {
                  num: "B",
                  rule: "Meaning in Context",
                  stem: '"As used in the text, what does the word X most nearly mean?"',
                  desc: "A familiar word is used in a non-standard definition. The dictionary meaning is VERY LIKELY to appear as a wrong answer — treat it as a red flag, not a confirmation.",
                },
              ].map((r) => (
                <div
                  key={r.num}
                  className="bg-white border border-fuchsia-200 rounded-xl p-4 card-tilt"
                >
                  <div className="flex items-center gap-2 mb-2">
                    <span className="w-6 h-6 rounded-full bg-fuchsia-600 text-white flex items-center justify-center text-xs font-bold shrink-0">
                      {r.num}
                    </span>
                    <span className="font-bold text-fuchsia-900 text-sm">
                      {r.rule}
                    </span>
                  </div>
                  <p className="text-xs text-slate-400 italic mb-2">{r.stem}</p>
                  <p className="text-xs text-slate-600">{r.desc}</p>
                </div>
              ))}
            </div>
          </div>

          {/* When to Study Vocabulary */}
          <div className="bg-white border border-slate-200 rounded-2xl p-6 mb-8 space-y-4 scroll-reveal stagger-1">
            <h3 className="text-lg font-bold text-slate-900">
              When to Study Vocabulary
            </h3>
            <p className="text-sm text-slate-600">
              If you are already scoring above 90% on Words in Context
              questions, vocabulary study has diminishing returns. Focus on
              speed and elimination instead. If you are scoring below 70%,
              targeted vocabulary building — especially roots, prefixes, and the
              academic words below — is the single highest-ROI investment you
              can make for this question type.
            </p>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div className="bg-fuchsia-50 border border-fuchsia-200 rounded-xl p-4">
                <p className="font-bold text-fuchsia-800 text-sm mb-1">
                  High Scorers (90%+)
                </p>
                <p className="text-xs text-slate-600">
                  Focus on elimination speed, second meanings, and advanced
                  context clue patterns. Vocabulary drills are unlikely to gain
                  points.
                </p>
              </div>
              <div className="bg-fuchsia-50 border border-fuchsia-200 rounded-xl p-4">
                <p className="font-bold text-fuchsia-800 text-sm mb-1">
                  Building Scorers (below 70%)
                </p>
                <p className="text-xs text-slate-600">
                  Study the Academic Vocabulary and Common Second Meanings
                  tables below. Learn 10 new words per week using flashcards
                  with context sentences, not isolated definitions.
                </p>
              </div>
            </div>
          </div>

          {/* 4-Step Process */}
          <div className="rounded-2xl p-6 mb-8 bg-white border border-slate-200 space-y-4 scroll-reveal stagger-2">
            <h3 className="text-lg font-bold text-slate-900">
              The 4-Step Process for Sentence Completions
            </h3>
            <div className="space-y-3">
              {[
                {
                  step: 1,
                  title: "Read the entire passage",
                  desc: "Identify key words or phrases. Consider the missing word in context of the full passage — focusing only on the blank line is a common error that leads to missing crucial information elsewhere.",
                },
                {
                  step: 2,
                  title: "Plug in your own word",
                  desc: "If a word comes to mind, write it down. This reduces error by establishing what the blank requires before looking at options. Spend no more than a few seconds on this. If you are not certain what belongs, skip this step entirely — guessing a filler word when uncertain creates misdirection.",
                },
                {
                  step: 3,
                  title: "Play positive/negative",
                  desc: "Determine whether the blank requires a positive, negative, or neutral word and write + or − on scratch paper. Then eliminate any answer choice that contradicts the charge. Go through options in order (A through D) to maintain systematic thinking and reduce careless error.",
                },
                {
                  step: 4,
                  title: "Plug in remaining options and compare",
                  desc: "Choose the best fit. Focus on what a word means, not how it sounds — a word may seem odd in context yet be the precise match required.",
                },
              ].map((s) => (
                <div
                  key={s.step}
                  className="flex gap-3 bg-fuchsia-50 border border-fuchsia-100 rounded-xl p-4"
                >
                  <span className="w-7 h-7 rounded-full bg-fuchsia-600 text-white flex items-center justify-center text-sm font-bold shrink-0">
                    {s.step}
                  </span>
                  <div>
                    <p className="font-bold text-slate-800 text-sm">
                      {s.title}
                    </p>
                    <p className="text-xs text-slate-500 mt-0.5">{s.desc}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </section>

        {/* ── SECTION 1: CONTEXT SIGNALS ── */}
        <section
          ref={(el) => {
            sectionsRef.current[1] = el;
          }}
          className="min-h-screen flex flex-col justify-center mb-24"
        >
          <h2 className="text-4xl font-extrabold text-slate-900 mb-2">
            Context Signals
          </h2>
          <p className="text-lg text-slate-500 mb-8">
            Signal words tell you exactly what direction and charge the blank
            must have. Identify the signal before looking at any answer choice.
          </p>

          {/* 3 Context Clue Signal Types */}
          <div className="bg-fuchsia-50 border border-fuchsia-200 rounded-2xl p-6 mb-8 space-y-4 scroll-reveal">
            <h3 className="text-lg font-bold text-fuchsia-900">
              The 3 Context Clue Signal Types
            </h3>
            <div className="space-y-3">
              {[
                {
                  type: "Type 1: Continuers",
                  color: "bg-green-50 border-green-200",
                  badge: "bg-green-600",
                  words:
                    "also, and, as well as, furthermore, in addition, just as, likewise, moreover, not only...but also, similarly",
                  meaning:
                    "The sentence continues in the same direction. The blank must have a similar meaning or charge to the surrounding context.",
                  ex: 'Soil is poor and resources are ___. The continuer "and" links the blank to "poor" — the blank must also be negative, meaning something like scarce or limited.',
                },
                {
                  type: "Type 2: Cause-and-Effect",
                  color: "bg-blue-50 border-blue-200",
                  badge: "bg-blue-600",
                  words:
                    "as a result, because, consequently, therefore, thus — and punctuation marks such as colons and dashes",
                  meaning:
                    "One idea causes or explains another. The blank must fit logically as either the cause or the effect of nearby information.",
                  ex: 'Astronauts required mental evaluation because the ___ danger was as important as the physiological one. "Because" links the blank to mental evaluation — the blank must mean psychological.',
                },
                {
                  type: "Type 3: Contradictors",
                  color: "bg-red-50 border-red-200",
                  badge: "bg-red-600",
                  words:
                    "although, but, despite, for all (= despite), however, in contrast, in spite of, meanwhile, nevertheless, on the other hand, though, unlike, whereas, while",
                  meaning:
                    "The sentence shifts direction. The blank must have the opposite meaning or charge from what precedes or follows the contradictor.",
                  ex: 'The Afar Triangle seems quite ___. However, its appearance is deceptive, obscuring fiery lava just beneath. "However" signals contrast with fiery lava — the blank must mean calm or peaceful.',
                },
              ].map((s) => (
                <div
                  key={s.type}
                  className={`border rounded-xl p-4 ${s.color}`}
                >
                  <div className="flex items-center gap-2 mb-1">
                    <span
                      className={`px-2 py-0.5 rounded-full text-white text-xs font-bold ${s.badge}`}
                    >
                      {s.type}
                    </span>
                  </div>
                  <p className="text-xs text-slate-500 italic mb-1">
                    {s.words}
                  </p>
                  <p className="text-sm text-slate-700 mb-2">{s.meaning}</p>
                  <div className="bg-white/70 rounded-lg p-2">
                    <p className="text-xs text-slate-600 italic">
                      <span className="font-bold not-italic text-slate-700">
                        Example:{" "}
                      </span>
                      {s.ex}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Advanced Patterns */}
          <div className="rounded-2xl p-6 mb-8 bg-white border border-slate-200 space-y-4 scroll-reveal stagger-1">
            <h3 className="text-lg font-bold text-slate-900">
              Advanced Sentence Structure Patterns
            </h3>
            <div className="space-y-3">
              <div className="bg-fuchsia-50 border border-fuchsia-200 rounded-xl p-4">
                <p className="font-bold text-fuchsia-800 text-sm mb-1">
                  Parallel Structure
                </p>
                <p className="text-xs text-slate-600 mb-2">
                  When a sentence uses constructions on either side of a paired
                  word (both...and, not only...but also), the items must be
                  grammatically parallel. This structure tells you what form the
                  blank must take.
                </p>
                <p className="text-xs text-slate-600 italic">
                  <span className="font-bold not-italic text-slate-700">
                    Example:{" "}
                  </span>
                  Praised for being both accessible and ___: while it captures
                  clarity, it does so without sacrificing subtlety or
                  complexity. Blank must parallel "accessible" — something like{" "}
                  <em>nuanced</em> or <em>sophisticated</em>.
                </p>
              </div>
              <div className="bg-fuchsia-50 border border-fuchsia-200 rounded-xl p-4">
                <p className="font-bold text-fuchsia-800 text-sm mb-1">
                  Two Negatives Equal a Positive
                </p>
                <p className="text-xs text-slate-600 mb-2">
                  Watch for sentences in which the negation of a negative word
                  produces a positive overall meaning. Students see the negative
                  charge of individual words and miss the positive meaning they
                  create together.
                </p>
                <p className="text-xs text-slate-600 italic">
                  <span className="font-bold not-italic text-slate-700">
                    Example:{" "}
                  </span>
                  Other species play a less ___ role because their caterpillars
                  consume harmful insects. The overall idea is positive
                  (helpful). But "less + [something good] = negative." So the
                  blank must be a negative word like <em>detrimental</em>, not a
                  positive word like <em>beneficial</em>.
                </p>
              </div>
            </div>
          </div>

          {/* Roots & Prefixes */}
          <div className="bg-fuchsia-50 border border-fuchsia-200 rounded-2xl p-6 mb-8 space-y-4 scroll-reveal stagger-2">
            <h3 className="text-lg font-bold text-fuchsia-900">
              Using Roots &amp; Prefixes
            </h3>
            <p className="text-sm text-slate-700">
              Knowledge of Latin and Romance-language roots allows educated
              guesses about unfamiliar words — often more valuable than
              memorizing definitions because it applies to words never seen
              before.
            </p>
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
              {[
                ["a-", "not (anomaly = unique)"],
                ["de-", "not/away from (detrimental = harmful)"],
                ["bene-", "good (beneficial = producing good)"],
                ["facil-", "easy (facility = ease)"],
              ].map(([prefix, meaning]) => (
                <div
                  key={prefix}
                  className="bg-white border border-fuchsia-100 rounded-lg px-3 py-2"
                >
                  <p className="font-bold text-fuchsia-700 text-sm">{prefix}</p>
                  <p className="text-xs text-slate-600">{meaning}</p>
                </div>
              ))}
            </div>
            <div className="bg-amber-50 border border-amber-200 rounded-lg p-3">
              <p className="text-xs text-amber-800 font-bold mb-1">
                Important Caveat
              </p>
              <p className="text-xs text-slate-600">
                Some positive words have prefixes that ordinarily signal
                negatives (discerning, innate, invaluable). These are
                exceptions. In general, logical use of roots and prefixes
                produces reliable results.
              </p>
            </div>
          </div>

          <div className="bg-fuchsia-900 text-white rounded-2xl p-5 mb-8 scroll-reveal-scale golden-rule-glow">
            <p className="font-bold mb-1">Golden Rule — Sentence Completions</p>
            <p className="text-sm text-fuchsia-100">
              Read the entire passage, identify the signal word (continuer /
              cause-effect / contradictor), determine positive or negative
              charge, plug in your own word, then eliminate by charge before
              testing by meaning. Never look at answer choices first.
            </p>
          </div>
        </section>

        {/* ── SECTION 2: MEANING IN CONTEXT ── */}
        <section
          ref={(el) => {
            sectionsRef.current[2] = el;
          }}
          className="min-h-screen flex flex-col justify-center mb-24"
        >
          <h2 className="text-4xl font-extrabold text-slate-900 mb-2">
            Meaning in Context
          </h2>
          <p className="text-lg text-slate-500 mb-8">
            Context determines meaning. A word means whatever the author uses it
            to mean in that passage — regardless of its dictionary definition.
          </p>

          {/* Three Strategies */}
          <div className="bg-fuchsia-50 border border-fuchsia-200 rounded-2xl p-6 mb-8 space-y-4 scroll-reveal">
            <h3 className="text-lg font-bold text-fuchsia-900">
              Three Strategies for Meaning-in-Context Questions
            </h3>
            <div className="space-y-3">
              {[
                {
                  num: 1,
                  title: "Substitute Your Own Word",
                  desc: "Use context to determine what word belongs, then find the answer choice that matches. This is the fastest approach for clear-context questions.",
                },
                {
                  num: 2,
                  title: "Plug In Each Answer Choice",
                  desc: "Replace the word in question with each option and test whether it fits the logic of the passage. Eliminate choices that produce illogical or grammatically awkward sentences.",
                },
                {
                  num: 3,
                  title: "Play Positive/Negative, Then Plug In",
                  desc: "Determine the charge of the blank, eliminate clearly opposite-charge answers, then test the remainder. Especially useful when meaning is less immediately clear.",
                },
              ].map((s) => (
                <div
                  key={s.num}
                  className="flex gap-3 bg-white border border-fuchsia-100 rounded-xl p-4"
                >
                  <span className="w-7 h-7 rounded-full bg-fuchsia-600 text-white flex items-center justify-center text-sm font-bold shrink-0">
                    {s.num}
                  </span>
                  <div>
                    <p className="font-bold text-slate-800 text-sm">
                      {s.title}
                    </p>
                    <p className="text-xs text-slate-500 mt-0.5">{s.desc}</p>
                  </div>
                </div>
              ))}
            </div>
            <div className="bg-amber-50 border border-amber-200 rounded-xl p-4">
              <p className="font-bold text-amber-900 text-sm mb-1">
                Secondary Meaning Indicator
              </p>
              <p className="text-xs text-slate-700">
                When all four answer choices are the same part of speech but one
                is a word normally used as a different part of speech (e.g.,{" "}
                <em>fluid</em> appearing as an adjective), this is a definitive
                signal that a second meaning is being tested. The
                unusual-looking option has an above-average chance of being
                correct and should be examined first.
              </p>
            </div>
          </div>

          {/* Common Second Meanings */}
          <div className="rounded-2xl p-6 mb-8 bg-white border border-slate-200 space-y-4 scroll-reveal">
            <h3 className="text-lg font-bold text-slate-900">
              Common Second Meanings — Master Reference
            </h3>
            <p className="text-sm text-slate-500">
              These words frequently appear in Meaning-in-Context questions in
              their secondary definitions. Tap each card to reveal.
            </p>
            <RevealCardGrid
              cards={SECOND_MEANINGS}
              columns={4}
              accentColor="fuchsia"
            />
          </div>

          {/* Words That Look Negative But Are Not */}
          <div className="bg-fuchsia-50 border border-fuchsia-200 rounded-2xl p-6 mb-8 space-y-4 scroll-reveal stagger-1">
            <h3 className="text-lg font-bold text-fuchsia-900">
              Words That Look Negative But Are Not
            </h3>
            <p className="text-sm text-slate-600">
              These words trap students who eliminate them based on their prefix
              or appearance. Tap each to see the actual definition.
            </p>
            <RevealCardGrid
              cards={NEGATIVE_LOOKING}
              columns={3}
              accentColor="fuchsia"
            />
          </div>

          {/* Academic Vocabulary — Interactive */}
          <div className="rounded-2xl p-6 mb-8 bg-white border border-slate-200 space-y-4 scroll-reveal stagger-2">
            <div className="flex items-center justify-between">
              <h3 className="text-lg font-bold text-slate-900">
                Academic Vocabulary to Know
              </h3>
              <div className="flex items-center gap-3">
                <span className="text-xs text-slate-400">
                  {revealedVocab.size}/{ALL_VOCAB_KEYS.length} revealed
                </span>
                <button
                  onClick={() =>
                    setRevealedVocab(
                      revealedVocab.size >= ALL_VOCAB_KEYS.length
                        ? new Set()
                        : new Set(ALL_VOCAB_KEYS),
                    )
                  }
                  className="text-xs font-bold text-fuchsia-600 hover:text-fuchsia-800 transition-colors"
                >
                  {revealedVocab.size >= ALL_VOCAB_KEYS.length
                    ? "Hide All"
                    : "Reveal All"}
                </button>
              </div>
            </div>
            <p className="text-sm text-slate-500">
              Click each card to test yourself, then tap to reveal the answer.
            </p>

            <p className="font-bold text-fuchsia-800 text-sm">
              Key Claim / Argument Verbs
            </p>
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
              {CLAIM_VERBS.map((v) => {
                const isRevealed = revealedVocab.has(v.label);
                return (
                  <button
                    key={v.label}
                    onClick={() => toggleVocab(v.label)}
                    className={`text-left rounded-xl p-3 border transition-all duration-200 ${isRevealed ? "bg-fuchsia-50 border-fuchsia-300 shadow-sm" : "bg-slate-50 border-slate-200 hover:border-fuchsia-300 hover:shadow-sm"}`}
                  >
                    <p className="font-bold text-fuchsia-700 text-xs mb-1">
                      {v.label}
                    </p>
                    {isRevealed ? (
                      <p className="text-xs text-slate-600 font-mono leading-relaxed">
                        {v.words}
                      </p>
                    ) : (
                      <p className="text-xs text-slate-400 italic">
                        tap to reveal
                      </p>
                    )}
                  </button>
                );
              })}
            </div>

            <p className="font-bold text-fuchsia-800 text-sm mt-2">
              Key Science &amp; Academic Terms
            </p>
            <div className="grid grid-cols-2 sm:grid-cols-5 gap-3">
              {SCIENCE_TERMS.map((t) => {
                const isRevealed = revealedVocab.has(t.word);
                return (
                  <button
                    key={t.word}
                    onClick={() => toggleVocab(t.word)}
                    className={`text-left rounded-xl p-3 border transition-all duration-200 ${isRevealed ? "bg-fuchsia-50 border-fuchsia-300 shadow-sm" : "bg-slate-50 border-slate-200 hover:border-fuchsia-300 hover:shadow-sm"}`}
                  >
                    <p className="font-bold text-fuchsia-700 text-xs mb-1">
                      {t.word}
                    </p>
                    {isRevealed ? (
                      <p className="text-xs text-slate-600 leading-relaxed">
                        {t.def}
                      </p>
                    ) : (
                      <p className="text-xs text-slate-400 italic">
                        tap to reveal
                      </p>
                    )}
                  </button>
                );
              })}
            </div>
          </div>

          <div className="bg-fuchsia-900 text-white rounded-2xl p-5 mb-8 scroll-reveal-scale golden-rule-glow">
            <p className="font-bold mb-1">Golden Rule — Meaning in Context</p>
            <p className="text-sm text-fuchsia-100">
              Never rely on the dictionary definition. Context determines
              meaning. The standard definition will very commonly appear as a
              wrong answer — treat its presence as a red flag, not a
              confirmation.
            </p>
          </div>
        </section>

        {/* ── SECTION 3: WIDGET ── */}
        <section
          ref={(el) => {
            sectionsRef.current[3] = el;
          }}
          className="min-h-screen flex flex-col justify-center mb-24"
        >
          <h2 className="text-4xl font-extrabold text-slate-900 mb-2">
            Elimination Practice
          </h2>
          <p className="text-lg text-slate-500 mb-8">
            Use the signal + your prediction to eliminate wrong answers one by
            one.
          </p>
          <ContextEliminationWidget
            exercises={VOCAB_EXERCISES}
            accentColor="fuchsia"
          />
        </section>

        {/* ── SECTION 4: PRACTICE ── */}
        <section
          ref={(el) => {
            sectionsRef.current[4] = el;
          }}
          className="min-h-screen flex flex-col justify-center mb-24"
        >
          <h2 className="text-4xl font-extrabold text-slate-900 mb-6">
            Practice Questions
          </h2>
          {WORDS_CONTEXT_EASY.slice(0, 2).map((q) => (
            <PracticeFromDataset key={q.id} question={q} color="fuchsia" />
          ))}
          {WORDS_CONTEXT_MEDIUM.slice(0, 1).map((q) => (
            <PracticeFromDataset key={q.id} question={q} color="fuchsia" />
          ))}
          <div className="mt-8 text-center">
            <button
              onClick={onFinish}
              className="px-6 py-3 bg-fuchsia-900 text-white font-bold rounded-full hover:bg-fuchsia-700 transition-colors"
            >
              Finish Lesson ✓
            </button>
          </div>
        </section>
      </div>
    </div>
  );
};

export default EBRWWordsInContextLesson;
