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

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

const EBRWVocabPreciseLesson: 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-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>
    );
  };

  const VOCAB_EXERCISES: VocabExercise[] = [
    {
      sentence:
        "The professor's explanation, though thorough, was unnecessarily prolix, causing many students to lose the thread of her argument.",
      word: "prolix",
      question: "As used in this sentence, 'prolix' most nearly means:",
      options: [
        {
          id: "A",
          definition: "unclear and ambiguous in meaning",
          isCorrect: false,
          elimReason:
            "The sentence says students lost the thread — but the issue is length, not ambiguity. 'Unnecessarily' before 'prolix' signals excessive quantity, not lack of clarity.",
        },
        {
          id: "B",
          definition: "excessively long and wordy",
          isCorrect: true,
          elimReason:
            "Fits perfectly — 'prolix' means tediously wordy. The 'unnecessarily' modifier and the result (losing the thread) both point to excessive length as the problem.",
        },
        {
          id: "C",
          definition: "overly formal and academic in tone",
          isCorrect: false,
          elimReason:
            "Tone mismatch — the sentence criticizes the length, not the register. Students losing the thread suggests quantity, not formality.",
        },
        {
          id: "D",
          definition: "repetitive in its use of examples",
          isCorrect: false,
          elimReason:
            "Too specific — 'prolix' applies to wordiness broadly, not specifically to repetitive examples.",
        },
      ],
    },
    {
      sentence:
        "The committee's decision to release the report was seen as a pragmatic solution to a politically charged situation.",
      word: "pragmatic",
      question: "As used in this sentence, 'pragmatic' most nearly means:",
      options: [
        {
          id: "A",
          definition: "morally correct and ethically sound",
          isCorrect: false,
          elimReason:
            "The sentence is about political feasibility, not ethics. 'Politically charged situation' signals practicality, not morality.",
        },
        {
          id: "B",
          definition: "financially motivated and cost-conscious",
          isCorrect: false,
          elimReason:
            "No financial context in the sentence — this is about political practicality, not money.",
        },
        {
          id: "C",
          definition: "practical and focused on real-world outcomes",
          isCorrect: true,
          elimReason:
            "Correct — 'pragmatic' means dealing with things sensibly and realistically rather than ideally. The 'politically charged' context confirms they chose what would work, not what was ideal.",
        },
        {
          id: "D",
          definition: "cautious and risk-averse",
          isCorrect: false,
          elimReason:
            "Close but too narrow — pragmatic means practical, not necessarily cautious. A pragmatic decision could be bold if it's realistic.",
        },
      ],
    },
    {
      sentence:
        "Her account of the events was largely corroborated by the testimony of three independent witnesses.",
      word: "corroborated",
      question: "As used in this sentence, 'corroborated' most nearly means:",
      options: [
        {
          id: "A",
          definition: "challenged and disputed",
          isCorrect: false,
          elimReason:
            "Opposite meaning — 'corroborated' means confirmed, not challenged. Three witnesses supporting her is positive confirmation.",
        },
        {
          id: "B",
          definition: "confirmed and supported by additional evidence",
          isCorrect: true,
          elimReason:
            "Exact meaning — 'corroborate' means to strengthen or confirm with new evidence. Three witnesses providing the same account confirms her version.",
        },
        {
          id: "C",
          definition: "recorded and preserved for future reference",
          isCorrect: false,
          elimReason:
            "The sentence is about verification, not archiving. Witnesses confirm accuracy, not storage.",
        },
        {
          id: "D",
          definition: "explained and clarified in detail",
          isCorrect: false,
          elimReason:
            "Witnesses don't clarify an account — they confirm it. 'Corroborated' implies agreement with the existing account, not elaboration.",
        },
      ],
    },
  ];

  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="Vocabulary Strategy"
            icon={BookOpen}
          />
          <SectionMarker
            index={1}
            title="Context Elimination"
            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: Vocabulary Strategy */}
        <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">
            Vocabulary in Context
          </div>
          <h2 className="text-4xl font-extrabold text-slate-900 mb-2">
            Vocabulary Strategy
          </h2>
          <p className="text-lg text-slate-500 mb-8">
            The SAT vocabulary question is a logic test disguised as a word
            test. Use context clues to find the word that fits precisely — in
            meaning, tone, and register.
          </p>

          <div className="bg-rose-50 border border-rose-200 rounded-2xl p-6 mb-6 space-y-4">
            <h3 className="text-lg font-bold text-rose-900">
              Four Essential Rules
            </h3>
            <div className="space-y-3">
              <div className="bg-white rounded-xl p-3 border border-rose-100">
                <p className="text-xs font-bold text-rose-700 mb-1">
                  1. Cover and Predict
                </p>
                <p className="text-xs text-slate-600">
                  Before looking at answer choices, cover them, read the
                  sentence, and predict what kind of word fits. Then find the
                  choice that matches your prediction.
                </p>
              </div>
              <div className="bg-white rounded-xl p-3 border border-rose-100">
                <p className="text-xs font-bold text-rose-700 mb-1">
                  2. Context Over Dictionary
                </p>
                <p className="text-xs text-slate-600">
                  The SAT tests how a word is used HERE, not its most common
                  meaning. 'Acute' usually means sharp, but in context may mean
                  'severe.'
                </p>
              </div>
              <div className="bg-white rounded-xl p-3 border border-rose-100">
                <p className="text-xs font-bold text-rose-700 mb-1">
                  3. Precise Fit
                </p>
                <p className="text-xs text-slate-600">
                  The right answer is not just generally correct — it fits the
                  TONE and REGISTER of the sentence (formal/informal,
                  positive/negative).
                </p>
              </div>
              <div className="bg-white rounded-xl p-3 border border-rose-100">
                <p className="text-xs font-bold text-rose-700 mb-1">
                  4. Elimination
                </p>
                <p className="text-xs text-slate-600">
                  The SAT rarely provides two obviously correct choices.
                  Eliminate by tone mismatch, connotation, and register before
                  picking.
                </p>
              </div>
            </div>
          </div>

          <div className="space-y-3 mb-6">
            <div className="bg-rose-100 rounded-xl p-4 border border-rose-200">
              <p className="text-sm text-slate-800 italic">
                "The diplomat's remarks were remarkably ____, avoiding any
                language that could be misinterpreted."
              </p>
            </div>
            <div className="bg-green-100 rounded-xl p-4 border border-green-200">
              <p className="text-sm text-slate-800">
                <span className="font-bold text-green-800">Correct:</span>{" "}
                'measured' — implies careful, deliberate, restrained language.
                Fits diplomatic context.
              </p>
            </div>
            <div className="bg-orange-100 rounded-xl p-4 border border-orange-200">
              <p className="text-sm text-slate-800">
                <span className="font-bold text-orange-800">Trap:</span> 'quiet'
                — a synonym that misses the connotation. The diplomat wasn't
                silent; they were precise.
              </p>
            </div>
          </div>

          <div className="bg-red-50 border border-red-200 rounded-xl p-4 mb-6">
            <p className="text-sm font-bold text-red-800 mb-1">
              Vocabulary precision trap
            </p>
            <p className="text-sm text-slate-700">
              Choose a word that is a synonym but wrong for the CONTEXT.
              'Economical' and 'frugal' both mean thrifty, but 'frugal' has a
              slightly negative connotation — the wrong fit for praising
              someone.
            </p>
          </div>

          <div className="bg-rose-900 rounded-2xl p-5 mb-8">
            <p className="text-sm font-bold text-rose-100 mb-1">Golden Rule</p>
            <p className="text-sm text-white">
              Re-read the sentence with your chosen word inserted. If it sounds
              perfect — not just acceptable — that's your answer.
            </p>
          </div>

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

        {/* Section 1: Context Elimination */}
        <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-rose-100 text-rose-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">
            Context Elimination
          </h2>
          <p className="text-lg text-slate-500 mb-8">
            For each question below, read the sentence and use context clues to
            eliminate wrong choices — then select the best meaning.
          </p>

          <ContextEliminationWidget
            exercises={VOCAB_EXERCISES}
            accentColor="rose"
          />

          <button
            onClick={() => scrollToSection(2)}
            className="mt-12 group flex items-center text-rose-600 font-bold hover:text-rose-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>
          {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-rose-900 text-white font-bold rounded-full hover:bg-rose-700 transition-colors"
            >
              Finish Lesson
            </button>
          </div>
        </section>
      </div>
    </div>
  );
};

export default EBRWVocabPreciseLesson;
