import React, { useRef, useState, useEffect } from "react";
import { Check, BookOpen, AlertTriangle, Zap, Target } from "lucide-react";
import { PracticeFromDataset } from "../../../components/lessons/LessonShell";
import {
  TRANSITIONS_EASY,
  TRANSITIONS_MEDIUM,
} from "../../../data/rw/transitions";
import DecisionTreeWidget, {
  type TreeScenario,
  type TreeNode,
} from "../../../components/lessons/DecisionTreeWidget";
import RevealCardGrid, {
  type RevealCard,
} from "../../../components/lessons/RevealCardGrid";
import useScrollReveal from "../../../components/lessons/useScrollReveal";

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

/* ── Data for RevealCardGrid widgets ── */
const COMMON_ERRORS: RevealCard[] = [
  {
    label: "Reading only the first sentence",
    content:
      "Always read BOTH ideas before deciding. The transition depends on the relationship between two things.",
  },
  {
    label: 'Picking "sophisticated" sounding words',
    content:
      "The choice depends entirely on which is logically accurate, not which sounds more formal.",
  },
  {
    label: "Ignoring direction",
    content:
      'Get SAME vs. OPPOSITE right first — if you skip this, you may pick "therefore" when the answer is "for example."',
  },
  {
    label: 'Confusing "although" with transitions',
    content:
      '"Although" starts a clause, not a sentence-opening transition. "However" starts a new sentence. Not interchangeable.',
  },
];

const SAME_SUBTREE: TreeNode = {
  id: "same-direction",
  question: "Is the second idea a CAUSE or RESULT of the first idea?",
  hint: 'If you can say "because of A, B happened" or "A led to B," there is a cause-effect relationship.',
  yesLabel: "Yes — cause-effect relationship",
  noLabel: "No — adding another point or example",
  yes: {
    id: "cause-effect",
    question: "",
    result:
      "✓ Use a CAUSE-EFFECT transition: therefore, thus, consequently, as a result, hence, accordingly.",
    resultType: "correct",
    ruleRef: "Idea A. Therefore, / As a result, / Consequently, Idea B.",
  },
  no: {
    id: "additive",
    question:
      "Is the second idea an EXAMPLE or ILLUSTRATION of the first idea?",
    hint: 'Can you say "for instance" or "to illustrate" before the second idea?',
    yesLabel: "Yes — second idea is a specific example",
    noLabel: "No — just adding a related point",
    yes: {
      id: "illustration",
      question: "",
      result:
        "✓ Use an ILLUSTRATION transition: for example, for instance, specifically, in particular, namely.",
      resultType: "correct",
      ruleRef: "General claim. For example, / Specifically, concrete example.",
    },
    no: {
      id: "additive-plain",
      question: "",
      result:
        "✓ Use an ADDITIVE transition: furthermore, moreover, additionally, also, in addition, likewise.",
      resultType: "correct",
      ruleRef: "Point A. Furthermore, / Moreover, / Additionally, Point B.",
    },
  },
};

const TRANSITIONS_TREE: TreeNode = {
  id: "root",
  question:
    "Do the two ideas move in the SAME direction or OPPOSITE directions?",
  hint: "Same = both ideas agree or build on each other. Opposite = second idea contrasts, contradicts, or surprises relative to the first.",
  yesLabel: "SAME direction — ideas agree or build on each other",
  noLabel: "OPPOSITE direction — second idea contrasts or contradicts",
  yes: SAME_SUBTREE,
  no: {
    id: "opposite",
    question:
      "Is the second idea CONCEDING a point while still maintaining an overall position?",
    hint: "Concession = admitting the other side has a valid point, while insisting on your view.",
    yesLabel: "Yes — conceding a point",
    noLabel: "No — direct contrast or contradiction",
    yes: {
      id: "concession",
      question: "",
      result:
        "✓ Use a CONCESSION transition: admittedly, granted, of course, certainly, to be sure.",
      resultType: "correct",
      ruleRef: "Admittedly, opposing point. Nevertheless, your main claim.",
    },
    no: {
      id: "contrast",
      question: "",
      result:
        "✓ Use a CONTRAST transition: however, nevertheless, nonetheless, on the other hand, in contrast, conversely, yet.",
      resultType: "correct",
      ruleRef: "Idea A. However, / Nevertheless, / In contrast, Idea B.",
    },
  },
};

const TREE_SCENARIOS: TreeScenario[] = [
  {
    label: "Pair 1",
    sentence:
      "The new policy reduced carbon emissions by 20%. [BLANK] it faced significant opposition from industry groups.",
    tree: TRANSITIONS_TREE,
  },
  {
    label: "Pair 2",
    sentence:
      "Photosynthesis requires sunlight, water, and carbon dioxide. [BLANK] a plant deprived of any one of these inputs cannot produce glucose.",
    tree: TRANSITIONS_TREE,
  },
  {
    label: "Pair 3",
    sentence:
      "Several ancient civilizations developed written language independently. [BLANK] the Sumerians created cuneiform around 3200 BCE.",
    tree: TRANSITIONS_TREE,
  },
];

const EBRWTransitionsLesson: React.FC<LessonProps> = ({ onFinish }) => {
  const [activeSection, setActiveSection] = useState(0);
  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-rose-50" : "hover:bg-slate-50"}`}
      >
        <div
          className={`w-8 h-8 rounded-full flex items-center justify-center shrink-0
          ${isActive ? "bg-rose-600 text-white" : isPast ? "bg-rose-400 text-white" : "bg-slate-200 text-slate-500"}`}
        >
          {isPast ? (
            <Check className="w-4 h-4" />
          ) : (
            <Icon className="w-4 h-4" />
          )}
        </div>
        <p
          className={`text-sm font-bold ${isActive ? "text-rose-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="Transition Categories"
            icon={BookOpen}
          />
          <SectionMarker
            index={1}
            title="Confused Pairs &amp; Errors"
            icon={AlertTriangle}
          />
          <SectionMarker index={2} title="Worked Examples" icon={Target} />
          <SectionMarker index={3} title="Logic Tree" icon={AlertTriangle} />
          <SectionMarker index={4} title="Practice Questions" icon={Zap} />
        </nav>
      </aside>

      <div className="flex-1 lg:ml-64 md:p-12 max-w-full mx-auto">
        {/* ── Section 0: Transition Categories ── */}
        <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-rose-100 text-rose-700 px-3 py-1 rounded-full text-xs font-bold uppercase tracking-wider mb-4 w-fit">
            Expression of Ideas — Domain 4
          </div>
          <h2 className="text-4xl font-extrabold text-slate-900 mb-2">
            Transitions
          </h2>
          <p className="text-lg text-slate-500 mb-8">
            Every transition question comes down to one question: do the two
            ideas move in the SAME or OPPOSITE direction?
          </p>

          {/* §10.1 Question Format */}
          <div className="scroll-reveal stagger-1 rounded-2xl p-6 mb-8 bg-rose-50 border border-rose-200 space-y-4">
            <h3 className="text-lg font-bold text-rose-900">
              What the Question Looks Like
            </h3>
            <div className="bg-white border border-rose-200 rounded-xl p-4">
              <p className="text-xs text-slate-500 font-bold uppercase tracking-wider mb-1">
                Typical Question Stem
              </p>
              <p className="text-sm italic text-slate-700">
                "Which choice completes the text with the most logical
                transition?"
              </p>
            </div>
            <p className="text-sm text-slate-700">
              The blank always sits{" "}
              <span className="font-bold">between two ideas</span> — between two
              sentences or within a sentence connecting two clauses. The four
              answer choices are always individual transition words or short
              phrases from different categories, so identifying the direction
              eliminates three wrong answers at once.
            </p>
          </div>

          {/* Same / Opposite */}
          <div className="scroll-reveal stagger-2 rounded-2xl p-6 mb-8 bg-white border border-slate-200 space-y-4">
            <h3 className="text-lg font-bold text-slate-900">
              The Core Framework: SAME or OPPOSITE?
            </h3>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div className="card-tilt bg-green-50 border border-green-200 rounded-xl p-4">
                <p className="font-bold text-green-800 text-sm mb-2">
                  SAME Direction
                </p>
                <p className="text-xs text-slate-600 mb-3">
                  Both ideas agree, build on each other, or the second follows
                  from the first.
                </p>
                <div className="space-y-1">
                  {[
                    "Additionally, furthermore, moreover",
                    "Therefore, thus, consequently",
                    "For example, for instance",
                    "Similarly, likewise",
                  ].map((t) => (
                    <p
                      key={t}
                      className="text-xs bg-green-100 text-green-800 px-2 py-1 rounded font-mono"
                    >
                      {t}
                    </p>
                  ))}
                </div>
              </div>
              <div className="card-tilt bg-red-50 border border-red-200 rounded-xl p-4">
                <p className="font-bold text-red-800 text-sm mb-2">
                  OPPOSITE Direction
                </p>
                <p className="text-xs text-slate-600 mb-3">
                  The second idea contradicts, limits, or surprises relative to
                  the first.
                </p>
                <div className="space-y-1">
                  {[
                    "However, nevertheless, nonetheless",
                    "In contrast, on the other hand",
                    "Admittedly, granted, of course",
                    "Yet, but, still",
                  ].map((t) => (
                    <p
                      key={t}
                      className="text-xs bg-red-100 text-red-800 px-2 py-1 rounded font-mono"
                    >
                      {t}
                    </p>
                  ))}
                </div>
              </div>
            </div>
          </div>

          {/* §10.3 Full Category Tables */}
          <div className="scroll-reveal stagger-3 rounded-2xl p-6 mb-8 bg-rose-50 border border-rose-200 space-y-4">
            <h3 className="text-lg font-bold text-rose-900">
              The 6 Transition Categories
            </h3>
            <div className="space-y-3">
              {[
                {
                  cat: "Continuers (Additive)",
                  dir: "SAME",
                  dirColor: "green",
                  when: "Adding another point that supports or extends the previous idea.",
                  words: [
                    {
                      w: "additionally",
                      n: 'neutral addition — "one more thing"',
                    },
                    {
                      w: "furthermore",
                      n: 'stronger — "and even more importantly"',
                    },
                    {
                      w: "moreover",
                      n: "strongest — often signals a clinching point",
                    },
                    {
                      w: "likewise / similarly",
                      n: "signals a parallel or analogous point",
                    },
                  ],
                },
                {
                  cat: "Contradictors (Contrast)",
                  dir: "OPPOSITE",
                  dirColor: "red",
                  when: "The second idea contradicts or surprises relative to the first.",
                  words: [
                    {
                      w: "however",
                      n: "neutral contrast — most common SAT contrast word",
                    },
                    {
                      w: "nevertheless / nonetheless",
                      n: "contrast despite an acknowledged difficulty",
                    },
                    {
                      w: "in contrast",
                      n: "explicit comparison showing a difference",
                    },
                    {
                      w: "conversely",
                      n: "second idea is the direct opposite of the first",
                    },
                  ],
                },
                {
                  cat: "Cause-Effect",
                  dir: "SAME",
                  dirColor: "green",
                  when: "Second idea is a result or logical consequence of the first.",
                  words: [
                    { w: "therefore", n: "general logical consequence" },
                    {
                      w: "thus",
                      n: "formal cause-effect; used in academic writing",
                    },
                    {
                      w: "consequently",
                      n: "strong result; implies significant consequence",
                    },
                    {
                      w: "as a result / hence",
                      n: 'plain cause-effect; interchangeable with "consequently"',
                    },
                  ],
                },
                {
                  cat: "Illustration",
                  dir: "SAME",
                  dirColor: "green",
                  when: "Second idea is a concrete example of the general claim in the first.",
                  words: [
                    {
                      w: "for example / for instance",
                      n: "most common; interchangeable",
                    },
                    { w: "specifically", n: "narrows from general to precise" },
                    {
                      w: "in particular / namely",
                      n: "singles out one specific item from a group",
                    },
                  ],
                },
                {
                  cat: "Concession",
                  dir: "OPPOSITE",
                  dirColor: "amber",
                  when: "Acknowledging a valid counterpoint before maintaining the main argument.",
                  words: [
                    {
                      w: "admittedly",
                      n: "acknowledges a valid point on the other side",
                    },
                    {
                      w: "granted / of course",
                      n: "concedes a point before asserting the main claim",
                    },
                    {
                      w: "to be sure",
                      n: "formal concession; acknowledges complexity",
                    },
                  ],
                },
                {
                  cat: "Sequence / Emphasis",
                  dir: "SAME",
                  dirColor: "green",
                  when: "Ordering points in a sequence, or signaling the most important or final idea.",
                  words: [
                    {
                      w: "first / second / finally",
                      n: "orders items in a list or argument",
                    },
                    {
                      w: "ultimately / above all",
                      n: "signals the most important point",
                    },
                    {
                      w: "in conclusion / in summary",
                      n: "wraps up a series of ideas",
                    },
                  ],
                },
              ].map((c) => (
                <div
                  key={c.cat}
                  className="card-tilt bg-white border border-slate-200 rounded-xl p-4"
                >
                  <div className="flex items-center gap-2 mb-2">
                    <p className="font-bold text-rose-800 text-sm">{c.cat}</p>
                    <span
                      className={`px-2 py-0.5 rounded-full text-xs font-bold ${c.dirColor === "green" ? "bg-green-100 text-green-800" : c.dirColor === "red" ? "bg-red-100 text-red-800" : "bg-amber-100 text-amber-800"}`}
                    >
                      {c.dir}
                    </span>
                  </div>
                  <p className="text-xs text-slate-500 italic mb-2">{c.when}</p>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-1">
                    {c.words.map((w) => (
                      <div key={w.w} className="flex gap-1 text-xs">
                        <span className="font-bold text-slate-800 whitespace-nowrap">
                          {w.w}:
                        </span>
                        <span className="text-slate-500">{w.n}</span>
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* 4-Step Strategy */}
          <div className="scroll-reveal stagger-4 rounded-2xl p-6 mb-8 bg-white border border-slate-200 space-y-4">
            <h3 className="text-lg font-bold text-slate-900">
              The 4-Step Strategy
            </h3>
            <div className="space-y-2">
              {[
                {
                  step: 1,
                  action: "Read BOTH ideas completely",
                  tip: "Never decide on a transition before reading the full second idea. The relationship exists between two complete thoughts.",
                },
                {
                  step: 2,
                  action: "Determine: SAME or OPPOSITE?",
                  tip: "Getting the direction wrong eliminates you from the correct answer category — usually cutting choices in half immediately.",
                },
                {
                  step: 3,
                  action: "Identify the specific logical relationship",
                  tip: "Cause-effect? An example? A concession? Narrow to the right sub-category.",
                },
                {
                  step: 4,
                  action: "Match to the answer choice",
                  tip: "Find the transition word in that category. If multiple fit, choose the most precise one.",
                },
              ].map((s) => (
                <div
                  key={s.step}
                  className="flex gap-3 bg-rose-50 border border-rose-100 rounded-xl px-4 py-3"
                >
                  <span className="w-6 h-6 rounded-full bg-rose-600 text-white flex items-center justify-center text-xs font-bold shrink-0">
                    {s.step}
                  </span>
                  <div>
                    <p className="font-bold text-slate-800 text-sm">
                      {s.action}
                    </p>
                    <p className="text-xs text-slate-500 mt-0.5">{s.tip}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="scroll-reveal-scale golden-rule-glow bg-rose-900 text-white rounded-2xl p-5 mb-8">
            <p className="font-bold mb-1">Golden Rule</p>
            <p className="text-sm text-rose-100">
              SAME or OPPOSITE? Answer this one question before looking at any
              answer choices. Getting the direction wrong eliminates you from
              the correct category entirely. Once you have the direction, narrow
              to the specific sub-category: cause-effect, illustration,
              additive, contrast, or concession.
            </p>
          </div>
        </section>

        {/* ── Section 1: Confused Pairs & Errors ── */}
        <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">
            Confused Pairs &amp; Errors
          </h2>
          <p className="text-lg text-slate-500 mb-8">
            The pairs students most commonly mix up, how transitions connect to
            reading skills, and the most common mistakes to avoid.
          </p>

          {/* §10.6 Confused Pairs */}
          <div className="scroll-reveal stagger-1 rounded-2xl p-6 mb-8 bg-rose-50 border border-rose-200 space-y-4">
            <h3 className="text-lg font-bold text-rose-900">
              Six Commonly Confused Pairs
            </h3>
            <div className="space-y-3">
              {[
                {
                  pair: "Therefore vs. However",
                  dirs: ["SAME (cause-effect)", "OPPOSITE (contrast)"],
                  diff: '"Therefore" means the second idea RESULTS from the first. "However" means the second idea CONTRADICTS or surprises.',
                  tip: 'Ask: "Does the second idea follow logically, or does it push back?" These are the most swapped pair on the SAT.',
                },
                {
                  pair: "Furthermore vs. Nevertheless",
                  dirs: ["SAME (additive)", "OPPOSITE (contrast)"],
                  diff: '"Furthermore" adds another supporting point. "Nevertheless" means "despite what was just said, this is still true."',
                  tip: 'If the first idea is negative and the second is positive (or vice versa), you need "nevertheless."',
                },
                {
                  pair: "For example vs. Therefore",
                  dirs: ["SAME (illustration)", "SAME (cause-effect)"],
                  diff: 'Both SAME direction, but different relationships. "For example" introduces a SPECIFIC CASE; "therefore" introduces a RESULT.',
                  tip: 'Ask: "Is the second sentence a result, or an example?" A result can\'t be introduced by "for example."',
                },
                {
                  pair: "Similarly vs. Consequently",
                  dirs: ["SAME (comparison)", "SAME (cause-effect)"],
                  diff: '"Similarly" says the two things share a parallel quality. "Consequently" says the second HAPPENED BECAUSE of the first.',
                  tip: 'Can you replace the blank with "as a result"? If yes → consequently. If it\'s a parallel comparison → similarly.',
                },
                {
                  pair: "Admittedly vs. However",
                  dirs: ["OPPOSITE (concession)", "OPPOSITE (contrast)"],
                  diff: '"Admittedly" concedes a point while implying the writer still holds their main view. "However" simply introduces a contrasting fact.',
                  tip: '"Admittedly" is almost always followed by a "but/nevertheless/still" that reasserts the main point.',
                },
                {
                  pair: "In contrast vs. In addition",
                  dirs: ["OPPOSITE (contrast)", "SAME (additive)"],
                  diff: '"In contrast" signals the second idea differs from the first. "In addition" signals the second idea builds on the first.',
                  tip: "These look similar in length and formality but are opposite in direction — a common trap.",
                },
              ].map((p) => (
                <div
                  key={p.pair}
                  className="card-tilt bg-white border border-slate-200 rounded-xl p-4"
                >
                  <div className="flex flex-wrap items-center gap-2 mb-2">
                    <p className="font-bold text-rose-800 text-sm">{p.pair}</p>
                    {p.dirs.map((d, i) => (
                      <span
                        key={i}
                        className={`px-2 py-0.5 rounded-full text-xs font-bold ${d.startsWith("SAME") ? "bg-green-100 text-green-800" : "bg-red-100 text-red-800"}`}
                      >
                        {d}
                      </span>
                    ))}
                  </div>
                  <p className="text-xs text-slate-700 mb-2">
                    <span className="font-bold">Key difference:</span> {p.diff}
                  </p>
                  <p className="text-xs text-amber-700 bg-amber-50 border border-amber-100 rounded px-2 py-1">
                    <span className="font-bold">Tip:</span> {p.tip}
                  </p>
                </div>
              ))}
            </div>
          </div>

          {/* Common Errors & Checklist */}
          <div className="scroll-reveal stagger-2 rounded-2xl p-6 mb-8 bg-white border border-slate-200 space-y-4">
            <h3 className="text-lg font-bold text-slate-900">
              Common Errors — tap to reveal the fix:
            </h3>
            <RevealCardGrid
              cards={COMMON_ERRORS}
              columns={2}
              accentColor="rose"
            />
            <div className="bg-rose-50 border border-rose-200 rounded-xl p-4">
              <p className="font-bold text-rose-900 text-sm mb-2">
                Domain 4 Self-Check
              </p>
              <div className="space-y-2">
                {[
                  "Did I read BOTH ideas completely before choosing a transition?",
                  "Did I determine SAME or OPPOSITE direction first?",
                  "Did I identify the specific sub-category (cause-effect / illustration / additive / contrast / concession)?",
                  "Could my answer create a comma splice? (transition words need a semicolon or period before them)",
                  "For Rhetorical Synthesis: Did I read the goal before the notes?",
                  "For Rhetorical Synthesis: Is every fact in my chosen answer directly supported by a note?",
                ].map((item) => (
                  <div key={item} className="flex gap-2 items-start">
                    <span className="w-4 h-4 rounded border border-rose-400 shrink-0 mt-0.5 bg-white" />
                    <p className="text-xs text-slate-700">{item}</p>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </section>

        {/* ── Section 2: Worked Examples ── */}
        <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">
            Worked Examples
          </h2>
          <p className="text-lg text-slate-500 mb-8">
            Three worked examples showing the full decision process for
            contrast, cause-effect, and illustration.
          </p>

          <div className="space-y-6">
            {[
              {
                label: "Example 1 — Contrast",
                context:
                  '"Solar energy is now cheaper than coal in most markets. [BLANK], many developing nations still rely primarily on coal for electricity generation."',
                options: [
                  {
                    opt: "A",
                    word: "Therefore",
                    dir: "SAME (cause-effect)",
                    right: false,
                    why: "Wrong direction. Solar being cheap does not logically cause nations to rely on coal — these ideas contradict.",
                  },
                  {
                    opt: "B",
                    word: "Furthermore",
                    dir: "SAME (additive)",
                    right: false,
                    why: "Wrong direction. Both ideas are not building the same point; the second surprises us given the first.",
                  },
                  {
                    opt: "C",
                    word: "However",
                    dir: "OPPOSITE (contrast)",
                    right: true,
                    why: "Correct. Solar being cheap sets up an expectation that coal use would decline — but nations still rely on coal. Classic expectation-surprise contrast.",
                  },
                  {
                    opt: "D",
                    word: "For example",
                    dir: "SAME (illustration)",
                    right: false,
                    why: "Wrong direction. The second sentence is not an example of solar being cheap; it contradicts that expectation.",
                  },
                ],
                path: "SAME or OPPOSITE? → Solar cheap / coal still used = OPPOSITE. Sub-category? → Pure contrast. Answer: However.",
              },
              {
                label: "Example 2 — Cause-Effect",
                context:
                  '"Deforestation destroys the natural habitats of countless species. [BLANK], biodiversity in heavily deforested regions has declined by over 30 percent."',
                options: [
                  {
                    opt: "A",
                    word: "Consequently",
                    dir: "SAME (cause-effect)",
                    right: true,
                    why: "Correct. Habitat destruction directly causes biodiversity decline. The second sentence is the result of the first.",
                  },
                  {
                    opt: "B",
                    word: "However",
                    dir: "OPPOSITE (contrast)",
                    right: false,
                    why: "Wrong direction. The decline in biodiversity is not surprising given habitat loss — it is the expected result.",
                  },
                  {
                    opt: "C",
                    word: "For instance",
                    dir: "SAME (illustration)",
                    right: false,
                    why: "Wrong sub-category. The second sentence is a result, not a specific example of deforestation.",
                  },
                  {
                    opt: "D",
                    word: "Moreover",
                    dir: "SAME (additive)",
                    right: false,
                    why: "Wrong sub-category. The second sentence explains the outcome caused by the first — not just another added point.",
                  },
                ],
                path: "SAME or OPPOSITE? → Habitat loss → biodiversity decline = SAME. Sub-category? → Second is a RESULT of the first = cause-effect. Answer: Consequently.",
              },
              {
                label: "Example 3 — Illustration",
                context:
                  '"Many ancient civilizations developed sophisticated mathematical systems independently. [BLANK], the Babylonians had already calculated the value of π to two decimal places by 1900 BCE."',
                options: [
                  {
                    opt: "A",
                    word: "Therefore",
                    dir: "SAME (cause-effect)",
                    right: false,
                    why: "Wrong sub-category. The Babylonian calculation is not a result of ancient civilizations developing math — it is an instance of that general claim.",
                  },
                  {
                    opt: "B",
                    word: "Nevertheless",
                    dir: "OPPOSITE (concession)",
                    right: false,
                    why: "Wrong direction. The Babylonian example supports the first sentence; it does not contradict it.",
                  },
                  {
                    opt: "C",
                    word: "For example",
                    dir: "SAME (illustration)",
                    right: true,
                    why: "Correct. The Babylonian calculation of π is a concrete specific example of the general claim about ancient math systems.",
                  },
                  {
                    opt: "D",
                    word: "In contrast",
                    dir: "OPPOSITE (contrast)",
                    right: false,
                    why: "Wrong direction. The Babylonians are not being contrasted with the general claim — they are confirming it.",
                  },
                ],
                path: "SAME or OPPOSITE? → Specific case supports general claim = SAME. Sub-category? → Second is a concrete EXAMPLE = illustration. Answer: For example.",
              },
            ].map((ex) => (
              <div
                key={ex.label}
                className="scroll-reveal rounded-2xl p-6 bg-slate-50 border border-slate-200 space-y-4"
              >
                <p className="text-xs font-bold text-rose-600 uppercase tracking-wider">
                  {ex.label}
                </p>
                <div className="bg-white border border-slate-200 rounded-xl p-4">
                  <p className="text-sm text-slate-700 italic">{ex.context}</p>
                </div>
                <div className="space-y-2">
                  {ex.options.map((o) => (
                    <div
                      key={o.opt}
                      className={`flex gap-2 p-3 rounded-xl text-xs ${o.right ? "bg-green-50 border border-green-200" : "bg-red-50 border border-red-100"}`}
                    >
                      <span
                        className={`font-bold shrink-0 w-16 ${o.right ? "text-green-700" : "text-red-500"}`}
                      >
                        {o.opt}. {o.word}
                      </span>
                      <span
                        className={`shrink-0 px-1 rounded text-xs self-start mt-0.5 ${o.right ? "bg-green-100 text-green-700" : "bg-red-100 text-red-600"}`}
                      >
                        {o.dir}
                      </span>
                      <span className="text-slate-600">{o.why}</span>
                    </div>
                  ))}
                </div>
                <div className="bg-amber-50 border border-amber-200 rounded-xl p-3">
                  <p className="text-xs text-amber-800">
                    <span className="font-bold">Decision path:</span> {ex.path}
                  </p>
                </div>
              </div>
            ))}
          </div>
        </section>

        {/* ── Section 3: Logic Tree ── */}
        <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">
            Logic Tree
          </h2>
          <p className="text-lg text-slate-500 mb-8">
            Work through the direction and relationship for each sentence pair
            to find the correct transition category.
          </p>
          <DecisionTreeWidget scenarios={TREE_SCENARIOS} accentColor="rose" />
        </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>
          {TRANSITIONS_EASY.slice(0, 2).map((q) => (
            <PracticeFromDataset key={q.id} question={q} color="rose" />
          ))}
          {TRANSITIONS_MEDIUM.slice(0, 1).map((q) => (
            <PracticeFromDataset key={q.id} question={q} color="rose" />
          ))}
          <div className="mt-8 text-center">
            <button
              onClick={onFinish}
              className="px-6 py-3 bg-rose-900 text-white font-bold rounded-full hover:bg-rose-700 transition-colors"
            >
              Finish Lesson ✓
            </button>
          </div>
        </section>
      </div>
    </div>
  );
};

export default EBRWTransitionsLesson;
