import React, { useRef, useState, useEffect } from "react";
import { Check, BookOpen, Lightbulb, Zap, Target } from "lucide-react";
import { PracticeFromDataset } from "../../../components/lessons/LessonShell";
import {
  INFERENCES_EASY,
  INFERENCES_MEDIUM,
} from "../../../data/rw/inferences";
import EvidenceHunterWidget, {
  type EvidenceExercise,
} from "../../../components/lessons/EvidenceHunterWidget";
import RevealCardGrid, {
  type RevealCard,
} from "../../../components/lessons/RevealCardGrid";
import useScrollReveal from "../../../components/lessons/useScrollReveal";

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

/* ── Data for RevealCardGrid widgets ── */
const INFERENCE_TYPES: RevealCard[] = [
  {
    label: "Valid / Necessary",
    sublabel: "CORRECT on SAT",
    content:
      "Must be true if the stated evidence is true. Example: If 14% of earthquakes are supershear → 86% are NOT supershear.",
  },
  {
    label: "Possible / Speculative",
    sublabel: "WRONG on SAT",
    content:
      'Could be true, but might not be; goes further than the evidence. Example: "Researchers must want more funding" — not stated.',
  },
  {
    label: "Contradicted",
    sublabel: "WRONG on SAT",
    content:
      'Directly conflicts with stated evidence. Example: "Exercise improves fitness equally for all" when passage says otherwise.',
  },
  {
    label: "Real-world true but unsupported",
    sublabel: "WRONG on SAT",
    content:
      "True in reality but not implied by the passage. The SAT only rewards what the text guarantees.",
  },
  {
    label: "Half-valid",
    sublabel: "WRONG on SAT",
    content:
      "First part follows from the evidence, but the second part goes beyond what the evidence requires.",
  },
];

const CHAIN_ERRORS: RevealCard[] = [
  {
    label: "Stopping too early",
    content:
      'Stopping at the finding rather than the conclusion (e.g., stopping at "feldspar was found" rather than following its implication for the competing theories).',
  },
  {
    label: "Skipping a step",
    content:
      "Jumping to a conclusion that goes further than the chain allows by skipping an intermediate logical step.",
  },
  {
    label: "Scope confusion",
    content:
      "The chain applies to one specific region or group, but the answer makes a universal claim about all regions or groups.",
  },
  {
    label: "Time assumption",
    content:
      "The evidence describes a current or past state, and the answer makes a claim about a future state without justification.",
  },
];

const EVIDENCE_EXERCISES: EvidenceExercise[] = [
  {
    question:
      "Based on the passage, which sentence provides the strongest basis for inferring that Dr. Patel's research contradicts established scientific consensus?",
    passage: [
      "Dr. Patel has spent fifteen years studying migration patterns of monarch butterflies.",
      "Her field stations span the entire North American flyway, from Canada to Mexico.",
      "She has published 47 peer-reviewed papers, each building on data collected across multiple seasons.",
      "Her most recent paper challenges the assumption that butterflies navigate primarily by magnetic fields.",
      "Instead, she proposes that polarized light plays a more significant role than previously recognized.",
    ],
    evidenceIndex: 3,
    explanation:
      'Sentence 4 is the basis for inferring contradiction with consensus. The word "challenges" indicates Dr. Patel is actively contradicting an established "assumption." This makes the inference valid — not speculation — because the passage directly states she is challenging the field.',
  },
  {
    question:
      "Which sentence provides the strongest basis for inferring that the plastic bag ban had unintended consequences?",
    passage: [
      "In 2015, the city council banned plastic bags at all grocery stores.",
      "The ban was intended to reduce plastic waste in local waterways.",
      "Plastic bag litter in rivers decreased by 40% in the first year.",
      "However, sales of heavier-gauge trash bags increased by 350% over the same period.",
      "Environmental analysts noted that thick trash bags contain more plastic by weight than the thin bags they replaced.",
    ],
    evidenceIndex: 3,
    explanation:
      "Sentence 4 is the evidence of the unintended consequence — a massive surge in heavier plastic bag purchases. Combined with sentence 5, it implies total plastic use may have increased, the opposite of the ban's stated goal.",
  },
];

const EBRWInferencesLesson: 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.ElementType;
  }) => {
    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-teal-50" : "hover:bg-slate-50"}`}
      >
        <div
          className={`w-8 h-8 rounded-full flex items-center justify-center shrink-0
          ${isActive ? "bg-teal-600 text-white" : isPast ? "bg-teal-400 text-white" : "bg-slate-200 text-slate-500"}`}
        >
          {isPast ? (
            <Check className="w-4 h-4" />
          ) : (
            // @ts-ignore
            <Icon className="w-4 h-4" />
          )}
        </div>
        <p
          className={`text-sm font-bold ${isActive ? "text-teal-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="Valid Inferences" icon={BookOpen} />
          <SectionMarker
            index={1}
            title="Inference Patterns"
            icon={Lightbulb}
          />

          <SectionMarker index={2} title="Inference Tracker" icon={Target} />
          <SectionMarker index={3} title="Practice Questions" icon={Zap} />
        </nav>
      </aside>

      <div className="flex-1 lg:ml-64 md:p-12 max-w-full mx-auto">
        {/* Section 0 — Valid Inferences */}
        <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-teal-100 text-teal-700 px-3 py-1 rounded-full text-xs font-bold uppercase tracking-wider mb-4 w-fit">
            Information &amp; Ideas — Domain 2
          </div>
          <h2 className="text-4xl font-extrabold text-slate-900 mb-2">
            Inferences
          </h2>
          <p className="text-lg text-slate-500 mb-8">
            A valid inference MUST be true based on the passage — not merely
            possible, plausible, or consistent.
          </p>

          {/* Core Concept — now with RevealCardGrid */}
          <div className="scroll-reveal stagger-1 bg-teal-50 border border-teal-200 rounded-2xl p-6 mb-8">
            <h3 className="text-lg font-bold text-teal-900 mb-2">
              The Core Concept — What Makes an Inference Valid?
            </h3>
            <p className="text-sm text-slate-700 mb-4">
              A valid inference is a statement that MUST be true if the evidence
              is true. It cannot merely be likely, plausible, or consistent. The
              SAT rewards only conclusions that necessarily follow from what is
              stated.
            </p>
            <RevealCardGrid
              cards={INFERENCE_TYPES}
              columns={3}
              accentColor="teal"
            />
          </div>

          {/* 3-Step Text Completion Process */}
          <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 3-Step Text Completion Process
            </h3>
            <p className="text-sm text-slate-600">
              Text completion questions present a short passage followed by a
              blank at the end, asking "Which choice most logically completes
              the text?" The correct answer NECESSARILY follows from the stated
              evidence — not merely the most interesting or plausible
              continuation.
            </p>
            <div className="bg-teal-50 border border-teal-200 rounded-xl p-4">
              <p className="font-bold text-teal-800 text-sm mb-2">
                Universal Method for All Inference Questions
              </p>
              <div className="space-y-2">
                {[
                  [
                    "1",
                    "IDENTIFY the key claim or evidence (usually in the 1–2 sentences before the blank). Write it in 3–6 words on scratch paper.",
                  ],
                  [
                    "2",
                    'WORK OUT the implication: "If this is true, what MUST also be true?" Do this BEFORE looking at answers. Even one word helps.',
                  ],
                  [
                    "3",
                    "MATCH the answer: look for the option that says the same thing as your implication, possibly using different words, negation, or synonyms.",
                  ],
                ].map(([n, text]) => (
                  <div key={n} className="flex gap-2">
                    <span className="w-5 h-5 rounded-full bg-teal-600 text-white flex items-center justify-center text-xs font-bold shrink-0">
                      {n}
                    </span>
                    <p className="text-xs text-slate-700">{text}</p>
                  </div>
                ))}
              </div>
            </div>
            <div className="bg-amber-50 border border-amber-200 rounded-xl p-4">
              <p className="font-bold text-amber-800 text-sm mb-1">
                WHY THIS MATTERS
              </p>
              <p className="text-xs text-slate-700">
                If you look at answer choices before working out the
                implication, you are vulnerable to speculation traps — answers
                that sound plausible because they extend the idea in a
                reasonable direction, but go further than the evidence requires.
              </p>
            </div>
          </div>
        </section>

        {/* Section 1 — Inference Patterns */}
        <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">
            Inference Patterns
          </h2>
          <p className="text-lg text-slate-500 mb-8">
            The four core patterns, speculation traps, double negatives, and
            multi-step chains.
          </p>

          {/* 6A — 4 Core Patterns */}
          <div className="scroll-reveal stagger-1 rounded-2xl p-6 mb-8 bg-teal-50 border border-teal-200 space-y-4">
            <h3 className="text-lg font-bold text-teal-900">
              The Four Core Valid Inference Patterns
            </h3>
            <div className="space-y-4">
              {[
                {
                  num: 1,
                  pattern: "Negation / Contrapositive",
                  rule: "If only X has property Y, then everything that is not-X must lack property Y. This works in both directions.",
                  examples: [
                    "If 14% of earthquakes are supershear events → 86% are NOT supershear events.",
                    "If a phenomenon occurs ONLY during slow-wave sleep → it does NOT occur during REM sleep.",
                    "If researchers focused mostly on land → most data comes from land, therefore they may have undercounted non-land events.",
                  ],
                },
                {
                  num: 2,
                  pattern: "Relative Comparison",
                  rule: "If X is more than Y, you can restate this as Y is less than X. If X is the most, you can infer that all others are less than X.",
                  examples: [
                    "If muscular contractions when lowering weights are MOST effective → contractions when raising weights are LESS effective.",
                    "If big brown bats emit the most cries → all other species emit fewer cries.",
                    "Restatement direction: if the claim is A > B, a valid answer might say B < A.",
                  ],
                },
                {
                  num: 3,
                  pattern: "Logical Elimination",
                  rule: "When possibilities are listed and most are ruled out, the remaining possibility is the valid inference.",
                  examples: [
                    "Researchers studied supershear earthquakes mostly on land → they did not study underwater earthquakes → many supershear earthquakes likely occur underwater.",
                    "Two theories for Mars's crust: (a) magma ocean or (b) different origin. If feldspar (associated with b) is found → theory (a) alone does not explain the crust.",
                  ],
                },
                {
                  num: 4,
                  pattern: "Causal / Consequential Extension",
                  rule: "If X causes Y, then applying X to a new situation should produce Y. Removing X should reduce Y.",
                  examples: [
                    "If replay during slow-wave sleep consolidates memory → dancers who sleep several hours right after learning a routine should remember it better two weeks later.",
                    "If hyperglycemia (high blood sugar) reduces exercise response → a drug that lowers blood sugar should improve exercise response.",
                    "Apply the mechanism to a new group, new time period, or new scenario — but STAY within the same causal framework.",
                  ],
                },
              ].map((p) => (
                <div
                  key={p.num}
                  className="card-tilt bg-white border border-slate-200 rounded-xl p-5"
                >
                  <div className="flex items-center gap-2 mb-2">
                    <span className="w-6 h-6 rounded-full bg-teal-600 text-white flex items-center justify-center text-xs font-bold shrink-0">
                      {p.num}
                    </span>
                    <p className="font-bold text-teal-900">{p.pattern}</p>
                  </div>
                  <p className="text-sm text-slate-700 mb-2">{p.rule}</p>
                  <ul className="space-y-1">
                    {p.examples.map((ex, i) => (
                      <li
                        key={i}
                        className="text-xs text-slate-500 bg-slate-50 rounded px-2 py-1 italic"
                      >
                        • {ex}
                      </li>
                    ))}
                  </ul>
                </div>
              ))}
            </div>
          </div>

          {/* 6B — Speculation Traps */}
          <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">
              Speculation Traps
            </h3>
            <p className="text-sm text-slate-600">
              Speculation traps are the most common wrong answer type in text
              completions. They go one plausible step too far beyond what the
              evidence necessarily implies.
            </p>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <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">
                  How to Identify a Speculation Trap
                </p>
                <ul className="text-xs text-slate-600 space-y-1">
                  <li>• The answer could be true but doesn't have to be.</li>
                  <li>
                    • The answer introduces a new assumption not grounded in the
                    passage.
                  </li>
                  <li>
                    • The answer requires you to imagine a scenario the passage
                    doesn't describe.
                  </li>
                  <li>
                    • The answer goes from "this happens" to "this is the
                    best/only/most effective way."
                  </li>
                </ul>
              </div>
              <div className="card-tilt bg-teal-50 border border-teal-200 rounded-xl p-4">
                <p className="font-bold text-teal-800 text-sm mb-2">
                  Worked Example
                </p>
                <p className="text-xs text-slate-600 mb-2 italic">
                  Evidence: Sea turtle conservation focuses on protecting
                  hatchlings after they emerge.
                </p>
                <ul className="text-xs space-y-1">
                  <li className="text-green-700">
                    ✓ VALID: Conservation focuses less on hatchlings before they
                    emerge.
                  </li>
                  <li className="text-red-600">
                    ✗ TRAP: Protecting hatchlings after emergence is the only
                    effective method.
                  </li>
                  <li className="text-red-600">
                    ✗ TRAP: Pre-emergence protection is more effective.
                  </li>
                </ul>
              </div>
            </div>
            <div className="bg-amber-50 border border-amber-200 rounded-xl p-4">
              <p className="font-bold text-amber-800 text-sm mb-1">RULE</p>
              <p className="text-xs text-slate-700">
                The word "only" in an answer choice is almost always a sign of
                over-speculation. Very few things on the SAT are literally "the
                only way." Be very suspicious of absolute claims in answer
                choices.
              </p>
            </div>
          </div>

          {/* 6C — Double Negatives & Second Meanings */}
          <div className="scroll-reveal stagger-3 rounded-2xl p-6 mb-8 bg-white border border-slate-200 space-y-4">
            <h3 className="text-lg font-bold text-slate-900">
              Double Negatives and Second Meanings in Answer Choices
            </h3>
            <p className="text-sm text-slate-600">
              Inference answer choices frequently use double negatives (which
              create positive meanings) or words in their second meanings. These
              are designed to make correct answers look wrong to careless
              readers.
            </p>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div className="card-tilt bg-teal-50 border border-teal-200 rounded-xl p-4">
                <p className="font-bold text-teal-800 text-sm mb-2">
                  Double Negative Translations
                </p>
                <ul className="text-xs text-slate-600 space-y-1">
                  <li>• "Not impossible" = possible</li>
                  <li>• "Not unimportant" = important</li>
                  <li>• "Not unlike" = similar</li>
                  <li>• "Less harmful" = milder, but still harmful</li>
                  <li>• Decode completely before evaluating the answer.</li>
                  <li className="italic text-teal-700">
                    Strategy: Replace "not un-X" with "X" and "not im-X" with
                    "X".
                  </li>
                </ul>
              </div>
              <div className="card-tilt bg-teal-50 border border-teal-200 rounded-xl p-4">
                <p className="font-bold text-teal-800 text-sm mb-2">
                  Second Meanings to Know
                </p>
                <ul className="text-xs text-slate-600 space-y-1">
                  <li>
                    • "Qualify" = limit the scope of a claim (not: meet
                    requirements)
                  </li>
                  <li>• "Sound" = valid, reliable (not: audio)</li>
                  <li>• "Check" = restrain, control (not: verify)</li>
                  <li>
                    • "Economy" = thrift, efficiency (not: the financial system)
                  </li>
                  <li>• "Reserve" = hold off on (not: book in advance)</li>
                  <li className="italic text-teal-700">
                    When a simple common word appears as an answer, suspect a
                    second meaning.
                  </li>
                </ul>
              </div>
            </div>
          </div>

          {/* 6D — Multi-Step Logical Chains */}
          <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">
              Multi-Step Logical Chains
            </h3>
            <p className="text-sm text-slate-600">
              Some text completion questions require you to follow 2–3 logical
              steps before arriving at the conclusion. Students most often lose
              points here by stopping one step too early or introducing an extra
              assumption.
            </p>
            <div className="bg-slate-50 border border-slate-200 rounded-xl p-4">
              <p className="font-bold text-slate-800 text-sm mb-2">
                Multi-Step Chain: Worked Example (Mars Crust)
              </p>
              <div className="space-y-1 text-xs text-slate-700">
                <p>
                  <span className="font-bold">Step 1:</span> Two theories exist
                  for the first Martian crust: (a) all-encompassing magma ocean,
                  (b) different origin with high silica.
                </p>
                <p>
                  <span className="font-bold">Step 2:</span> Researchers find
                  feldspar (associated with high-silica lava flows) in 9
                  locations on Mars.
                </p>
                <p>
                  <span className="font-bold">Step 3:</span> Feldspar is
                  evidence for Theory (b) — different origin with high silica.
                </p>
                <p>
                  <span className="font-bold">Step 4:</span> If Theory (b)
                  accounts for some locations, Theory (a) (magma ocean) could
                  not have been ALL-ENCOMPASSING.
                </p>
                <p className="text-green-700 font-bold mt-2">
                  Valid Conclusion: The magma ocean was not all-encompassing.
                </p>
                <p className="text-red-600 italic">
                  Speculation Trap: "Portions of Mars' surface were never
                  covered by a crust." (no evidence for this)
                </p>
              </div>
            </div>
            <p className="font-semibold text-sm text-slate-800">
              Common errors in multi-step chains:
            </p>
            <RevealCardGrid
              cards={CHAIN_ERRORS}
              columns={2}
              accentColor="teal"
            />
          </div>

          {/* 6E — Scratch Paper */}
          <div className="scroll-reveal stagger-5 rounded-2xl p-6 mb-8 bg-teal-50 border border-teal-200 space-y-4">
            <h3 className="text-lg font-bold text-teal-900">
              Using Scratch Paper for Inference Questions
            </h3>
            <p className="text-sm text-slate-700">
              For text completions, scratch paper is not optional — it is
              essential. Writing down even a brief summary of the key claim and
              your predicted answer protects you from being seduced by
              plausible-sounding wrong answers.
            </p>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div className="card-tilt bg-white border border-teal-100 rounded-xl p-4">
                <p className="font-bold text-teal-800 text-sm mb-2">
                  What to Write
                </p>
                <ul className="text-xs text-slate-600 space-y-1">
                  <li>• 3–6 word summary of the key claim.</li>
                  <li>
                    • Arrow indicating direction: "X → Y" or "less X = more Y".
                  </li>
                  <li>
                    • Your predicted answer in 3–5 words before looking at
                    choices.
                  </li>
                  <li>
                    • For multi-step chains: number each step (1) → (2) → (3).
                  </li>
                </ul>
              </div>
              <div className="card-tilt bg-white border border-teal-100 rounded-xl p-4">
                <p className="font-bold text-teal-800 text-sm mb-2">
                  What This Prevents
                </p>
                <ul className="text-xs text-slate-600 space-y-1">
                  <li>
                    • Choosing a speculative answer because it sounded good.
                  </li>
                  <li>
                    • Forgetting the specific constraint after reading 4 answer
                    choices.
                  </li>
                  <li>• Losing track of the logical chain halfway through.</li>
                  <li>
                    • Selecting half-valid answers that address only part of the
                    claim.
                  </li>
                </ul>
              </div>
            </div>
          </div>

          <div className="scroll-reveal-scale golden-rule-glow bg-teal-900 text-white rounded-2xl p-5 mb-8">
            <p className="font-bold mb-1">Golden Rule</p>
            <p className="text-sm text-teal-100">
              Test every answer with: "Does the passage GUARANTEE this is true?"
              If you can imagine a scenario where the passage is correct but
              this answer is still false, eliminate it. Only the answer that
              MUST be true is correct. "Only," "best," and "most effective" in
              answer choices = almost always over-speculation.
            </p>
          </div>
        </section>

        {/* Section 2 — Inference Tracker widget */}
        <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">
            Inference Tracker
          </h2>
          <p className="text-lg text-slate-500 mb-8">
            Click the sentence that provides the strongest basis for the
            inference. Which sentence GUARANTEES the conclusion?
          </p>
          <EvidenceHunterWidget
            exercises={EVIDENCE_EXERCISES}
            accentColor="teal"
          />
        </section>

        {/* Section 3 — Practice */}
        <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-6">
            Practice Questions
          </h2>
          {INFERENCES_EASY.slice(0, 2).map((q) => (
            <PracticeFromDataset key={q.id} question={q} color="teal" />
          ))}
          {INFERENCES_MEDIUM.slice(0, 1).map((q) => (
            <PracticeFromDataset key={q.id} question={q} color="teal" />
          ))}
          <div className="mt-8 text-center">
            <button
              onClick={onFinish}
              className="px-6 py-3 bg-teal-900 text-white font-bold rounded-full hover:bg-teal-700 transition-colors"
            >
              Finish Lesson ✓
            </button>
          </div>
        </section>
      </div>
    </div>
  );
};

export default EBRWInferencesLesson;
