import React, { useRef, useState, useEffect } from "react";
import { ArrowDown, Check, BookOpen, AlertTriangle, Zap } from "lucide-react";
import EvidenceHunterWidget, {
  type EvidenceExercise,
} from "../../../components/lessons/EvidenceHunterWidget";
import { PracticeFromDataset } from "../../../components/lessons/LessonShell";
import {
  COMMAND_EVIDENCE_EASY,
  COMMAND_EVIDENCE_MEDIUM,
} from "../../../data/rw/command-of-evidence";

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

const EVIDENCE_EXERCISES: EvidenceExercise[] = [
  {
    question:
      "According to the passage, what was the primary reason early astronomers miscalculated the distance to the Moon?",
    passage: [
      "Early astronomers were remarkably accurate in measuring celestial positions using basic instruments.",
      "However, calculating the actual distances to celestial bodies proved far more difficult.",
      "The primary obstacle was the lack of reliable baseline measurements on Earth's surface — without knowing the exact distance between two observation points, triangulation calculations were fundamentally flawed.",
      "It was not until the 18th century that land surveys became precise enough to enable accurate parallax measurements.",
      "Even then, the results varied significantly depending on atmospheric conditions during observation.",
    ],
    evidenceIndex: 2,
    explanation:
      "Sentence 3 explicitly states the primary reason: lack of reliable baseline measurements on Earth made triangulation calculations fundamentally flawed. This is directly stated — no inference needed. The correct answer to an explicit meaning question will mirror this sentence's claim.",
  },
  {
    question:
      "What does the author explicitly say about the role of microorganisms in soil health?",
    passage: [
      "Healthy agricultural soil is far more than a medium for plant roots.",
      "It is a living system teeming with billions of microorganisms per teaspoon.",
      "These microorganisms — bacteria, fungi, and protozoa — break down organic matter, releasing nutrients that plants need to grow.",
      "When farmers apply excess synthetic fertilizers, these microbial communities are disrupted, often permanently.",
      "Over time, this leads to soil compaction and loss of the natural nutrient cycle that sustained agriculture for millennia.",
    ],
    evidenceIndex: 2,
    explanation:
      "Sentence 3 explicitly states the role: microorganisms break down organic matter and release nutrients for plants. This is directly stated, word for word. Sentence 4 is about what harms them, and sentence 5 is about consequences — neither is the answer to what their role IS.",
  },
  {
    question:
      "According to the passage, when did scientists first observe the phenomenon described?",
    passage: [
      "The bioluminescence of deep-sea creatures has fascinated marine biologists for over a century.",
      "Early expeditions in the late 1800s brought up specimens that glowed faintly in darkness, confounding researchers.",
      "It was during the 1977 Alvin submersible dives off the Galápagos Rift that scientists first observed bioluminescence in its natural habitat.",
      "The footage captured was grainy but unmistakable — entire communities of organisms pulsing with cold blue light.",
      "This discovery fundamentally changed scientists' understanding of life in oxygen-deprived environments.",
    ],
    evidenceIndex: 2,
    explanation:
      'Sentence 3 explicitly states when: during the 1977 Alvin submersible dives. This is the direct answer. Sentence 2 mentions earlier expeditions but notes researchers were "confounded" — they observed specimens but not the phenomenon in its natural habitat.',
  },
];

const EBRWExplicitMeaningLesson: 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());
  }, []);

  const scrollToSection = (i: number) => {
    setActiveSection(i);
    sectionsRef.current[i]?.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" />
          ) : (
            <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 lg:bg-transparent z-0 hidden lg:block">
        <nav className="space-y-2 pt-6">
          <SectionMarker
            index={0}
            title="Concept & Annotation"
            icon={BookOpen}
          />
          <SectionMarker
            index={1}
            title="Evidence Hunter"
            icon={AlertTriangle}
          />
          <SectionMarker index={2} title="Practice Quiz" icon={Zap} />
        </nav>
      </aside>

      <div className="flex-1 lg:ml-64 p-6 md:p-12 max-w-4xl mx-auto">
        {/* Section 0: Concept & Annotation */}
        <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">
            Information & Ideas
          </div>
          <h2 className="text-4xl font-extrabold text-slate-900 mb-2">
            Explicit Meaning
          </h2>
          <p className="text-lg text-slate-500 mb-8">
            "According to the passage" = the answer is IN the text. No
            inference. No outside knowledge. Find it, paraphrase it, pick it.
          </p>

          {/* Rule grid */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-8">
            {[
              {
                num: "1",
                title: "Locate, Don't Interpret",
                body: "For explicit meaning questions, the answer is stated directly in the passage. Don't paraphrase or infer.",
              },
              {
                num: "2",
                title: "Line Reference = Go There",
                body: "If the question gives a line or paragraph, read 2 lines above AND below the cited text for full context.",
              },
              {
                num: "3",
                title: "Match the Exact Claim",
                body: "The correct answer mirrors what the text says, using different words. Avoid choices that add, subtract, or distort.",
              },
              {
                num: "4",
                title: "Best Evidence Pairs",
                body: "On DSAT, many explicit questions ask you to select BOTH the answer AND the quote that proves it. They must match.",
              },
            ].map((rule) => (
              <div
                key={rule.num}
                className="rounded-2xl border border-teal-200 bg-teal-50 p-5"
              >
                <div className="flex items-center gap-2 mb-2">
                  <span className="w-7 h-7 rounded-full bg-teal-600 text-white flex items-center justify-center text-xs font-bold shrink-0">
                    {rule.num}
                  </span>
                  <p className="text-sm font-bold text-teal-900">
                    {rule.title}
                  </p>
                </div>
                <p className="text-sm text-slate-700 leading-relaxed">
                  {rule.body}
                </p>
              </div>
            ))}
          </div>

          {/* Static annotation visual */}
          <h3 className="text-lg font-bold text-slate-800 mb-3">
            How to Annotate an Explicit Question
          </h3>
          <div className="space-y-3 mb-8">
            <div className="rounded-xl bg-teal-100 border border-teal-200 p-4">
              <p className="text-xs font-bold text-teal-700 uppercase tracking-wider mb-1">
                Question type
              </p>
              <p className="text-sm text-slate-800">
                "According to the passage, the researcher concluded that..."
              </p>
            </div>
            <div className="rounded-xl bg-green-100 border border-green-200 p-4">
              <p className="text-xs font-bold text-green-700 uppercase tracking-wider mb-1">
                Strategy
              </p>
              <p className="text-sm text-slate-800">
                Find the paragraph containing the researcher's conclusion. Read
                it directly.
              </p>
            </div>
            <div className="rounded-xl bg-orange-100 border border-orange-200 p-4">
              <p className="text-xs font-bold text-orange-700 uppercase tracking-wider mb-1">
                Trap
              </p>
              <p className="text-sm text-slate-800">
                A choice that is TRUE but not stated in the passage — it's an
                inference, not explicit meaning.
              </p>
            </div>
          </div>

          {/* Trap callout */}
          <div className="rounded-2xl bg-red-50 border border-red-200 p-5 mb-8">
            <p className="text-sm font-bold text-red-800 mb-2">
              The #1 Explicit Meaning Trap
            </p>
            <p className="text-sm text-slate-700 leading-relaxed">
              An answer that is logically consistent with the passage but not
              actually stated. If you can't point to the exact sentence that
              proves it, it's not explicit.
            </p>
          </div>

          {/* Golden rule */}
          <div className="rounded-2xl bg-teal-900 p-6 mb-8">
            <p className="text-xs font-bold text-teal-300 uppercase tracking-wider mb-2">
              Golden Rule
            </p>
            <p className="text-white font-semibold leading-relaxed">
              Explicit = you can put your finger on the line. If you have to
              reason from multiple pieces, it's an inference question.
            </p>
          </div>

          <button
            onClick={() => scrollToSection(1)}
            className="mt-4 group flex items-center text-teal-600 font-bold hover:text-teal-800 transition-colors"
          >
            Next: Evidence Hunter{" "}
            <ArrowDown className="ml-2 w-5 h-5 group-hover:translate-y-1 transition-transform" />
          </button>
        </section>

        {/* Section 1: Evidence Hunter */}
        <section
          ref={(el) => {
            sectionsRef.current[1] = el;
          }}
          className="min-h-screen flex flex-col justify-center mb-24"
        >
          <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">
            Interactive Practice
          </div>
          <h2 className="text-4xl font-extrabold text-slate-900 mb-2">
            Evidence Hunter
          </h2>
          <p className="text-lg text-slate-500 mb-8">
            Read each passage and click the sentence that directly answers the
            question. The answer must be explicitly stated — no reasoning
            required.
          </p>

          <EvidenceHunterWidget
            exercises={EVIDENCE_EXERCISES}
            accentColor="teal"
          />

          <button
            onClick={() => scrollToSection(2)}
            className="mt-12 group flex items-center text-teal-600 font-bold hover:text-teal-800 transition-colors"
          >
            Next: Practice Quiz{" "}
            <ArrowDown className="ml-2 w-5 h-5 group-hover:translate-y-1 transition-transform" />
          </button>
        </section>

        {/* Section 2: Practice Quiz */}
        <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-6">
            Practice Quiz
          </h2>
          {COMMAND_EVIDENCE_EASY.slice(0, 2).map((q) => (
            <PracticeFromDataset key={q.id} question={q} color="teal" />
          ))}
          {COMMAND_EVIDENCE_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 EBRWExplicitMeaningLesson;
