import React, { useRef, useState, useEffect } from "react";
import { Check, BookOpen, Lightbulb, Zap, Target } from "lucide-react";
import { PracticeFromDataset } from "../../../components/lessons/LessonShell";
import {
  CROSS_TEXT_EASY,
  CROSS_TEXT_MEDIUM,
} from "../../../data/rw/cross-text-connections";
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 RESPONSE_PATTERNS: RevealCard[] = [
  {
    label: "Overstated / exaggerated",
    content: '"It overstates the environmental impact of X."',
  },
  {
    label: "Insufficiently supported",
    content: '"The data do not support the conclusion drawn."',
  },
  {
    label: "Incomplete / overlooks evidence",
    content: '"It overlooks a crucial statistic / factor."',
  },
  {
    label: "Logically flawed",
    content: '"The reasoning does not follow from the evidence presented."',
  },
];

const SCOPE_ERRORS: RevealCard[] = [
  {
    label: "Scope Error",
    content:
      "Answer is more general or more specific than what either text actually argues. The correct answer matches the EXACT scope of the relevant text.",
  },
  {
    label: "One-Text Error",
    content:
      'Answer accurately reflects one text but ignores the other. In "both agree" questions, every word must apply to both passages.',
  },
  {
    label: "Extreme Language",
    content:
      'Answer uses "always," "never," "all," "none" when neither author makes such an absolute claim.',
  },
  {
    label: "Fabricated Connection",
    content:
      "Answer invents a relationship between the texts that neither author states or implies.",
  },
];

const EVIDENCE_EXERCISES: EvidenceExercise[] = [
  {
    question:
      "Text 1 claims social media increases political polarization. Which sentence from Text 2 most directly responds to this claim?",
    passage: [
      "Social media platforms are designed to maximize engagement through outrage.",
      "Studies of Twitter and Facebook show users cluster in ideological echo chambers.",
      "However, a 2022 meta-analysis of 31 studies found no consistent causal link between social media use and polarization.",
      "The authors note that correlation between social media use and polarized views may reflect self-selection bias.",
      "People who are already polarized may simply use social media more frequently.",
    ],
    evidenceIndex: 2,
    explanation:
      'Sentence 3 directly challenges the claim that social media causes polarization by citing a meta-analysis finding no consistent causal link. The word "however" signals this is the point where Text 2 diverges from Text 1\'s argument.',
  },
  {
    question:
      "Both passages discuss the role of apprenticeships in education. Which sentence from Text 2 would Text 1's author most likely agree with?",
    passage: [
      "Modern universities emphasize abstract theory over practical skills.",
      "Employers increasingly report that graduates cannot apply classroom knowledge to real problems.",
      "Apprenticeship programs combine theoretical learning with supervised hands-on practice.",
      "Countries with strong apprenticeship traditions, such as Germany, report lower youth unemployment.",
      "Critics argue that apprenticeships limit social mobility by tracking students into specific trades.",
    ],
    evidenceIndex: 2,
    explanation:
      "Sentence 3 describes apprenticeships as combining theory and practice — this is the bridge both texts share. Text 1 likely argues for integrating practical skills with theoretical knowledge, making this the point of agreement.",
  },
];

const EBRWCrossTextLesson: 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-fuchsia-50" : "hover:bg-slate-50"}`}
      >
        <div
          className={`w-8 h-8 rounded-full flex items-center justify-center shrink-0
          ${isActive ? "bg-fuchsia-600 text-white" : isPast ? "bg-fuchsia-400 text-white" : "bg-slate-200 text-slate-500"}`}
        >
          {isPast ? (
            <Check className="w-4 h-4" />
          ) : (
            <Icon className="w-4 h-4" />
          )}
        </div>
        <p
          className={`text-sm font-bold ${isActive ? "text-fuchsia-900" : "text-slate-600"}`}
        >
          {title}
        </p>
      </button>
    );
  };

  return (
    <div className="flex flex-col lg:flex-row min-h-screen">
      <aside className="w-full lg:w-64 lg:fixed lg:top-14 lg:bottom-0 lg:overflow-y-auto p-4 border-r border-slate-200 bg-slate-50 z-0 hidden lg:block">
        <nav className="space-y-2 pt-6">
          <SectionMarker
            index={0}
            title="Paired Passage Strategy"
            icon={BookOpen}
          />
          <SectionMarker
            index={1}
            title="Relationship Types"
            icon={Lightbulb}
          />
          <SectionMarker index={2} title="Connection Finder" 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: PAIRED PASSAGE 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-fuchsia-100 text-fuchsia-700 px-3 py-1 rounded-full text-xs font-bold uppercase tracking-wider mb-4 w-fit">
            Craft &amp; Structure — Domain 1
          </div>
          <h2 className="text-4xl font-extrabold text-slate-900 mb-2">
            Cross-Text Connections
          </h2>
          <p className="text-lg text-slate-500 mb-8">
            Two short passages, one question — always about the relationship
            between the authors' claims. Summarize each text before reading the
            question.
          </p>

          {/* Format & Question Stems */}
          <div className="scroll-reveal stagger-1 bg-fuchsia-50 border border-fuchsia-200 rounded-2xl p-6 mb-8 space-y-4">
            <h3 className="text-lg font-bold text-fuchsia-900">
              Format &amp; Common Question Stems
            </h3>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div className="card-tilt bg-white border border-fuchsia-200 rounded-xl p-4">
                <p className="font-bold text-fuchsia-800 text-sm mb-2">
                  What to Expect
                </p>
                <ul className="space-y-1">
                  {[
                    "Both texts are very short — typically 50–100 words each.",
                    "They cover the same general topic but present different perspectives.",
                    "Only one question accompanies the pair.",
                    "The most common relationship is disagreement — one challenges or qualifies the other.",
                    "Authors may also partially agree, or one may complicate the other's conclusion.",
                  ].map((f) => (
                    <li
                      key={f}
                      className="flex items-start gap-2 text-xs text-slate-700"
                    >
                      <span className="text-fuchsia-500 shrink-0 mt-0.5">
                        •
                      </span>
                      {f}
                    </li>
                  ))}
                </ul>
              </div>
              <div className="card-tilt bg-white border border-fuchsia-200 rounded-xl p-4">
                <p className="font-bold text-fuchsia-800 text-sm mb-2">
                  Common Question Stems
                </p>
                <ul className="space-y-2">
                  {[
                    '"Based on the texts, how would [Author 2] most likely describe the view in Text 1?"',
                    '"Based on the texts, how would [Author 2] most likely respond to what [Author 1] says about X?"',
                    '"Both texts discuss X. How do they differ in their treatment of it?"',
                    '"Which statement would [Author 1] most likely agree with?"',
                  ].map((stem) => (
                    <li
                      key={stem}
                      className="text-xs text-slate-600 italic bg-fuchsia-50 rounded-lg px-2 py-1"
                    >
                      {stem}
                    </li>
                  ))}
                </ul>
              </div>
            </div>
          </div>

          {/* Five-Step 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 Five-Step Process
            </h3>
            <div className="space-y-3">
              {[
                {
                  step: 1,
                  action: "Read Text 1 and identify its main point",
                  tip: "Write it down in 4–6 words on scratch paper.",
                },
                {
                  step: 2,
                  action: "Read Text 2 and identify its main point",
                  tip: "Write it down in 4–6 words on scratch paper.",
                },
                {
                  step: 3,
                  action: "Write the relationship between the two",
                  tip: "Disagree, partially agree, or agree with different emphasis.",
                },
                {
                  step: 4,
                  action:
                    "Answer the question in your own words before looking at options",
                  tip: "Base this on your written main points and the relationship.",
                },
                {
                  step: 5,
                  action:
                    "Read the answer choices and select the closest match",
                  tip: "Use elimination — wrong charges can often be spotted from the first few words of each option.",
                },
              ].map((s) => (
                <div
                  key={s.step}
                  className="flex gap-3 bg-fuchsia-50 border border-fuchsia-100 rounded-xl p-4"
                >
                  <span className="w-7 h-7 rounded-full bg-fuchsia-600 text-white flex items-center justify-center text-sm font-bold shrink-0">
                    {s.step}
                  </span>
                  <div>
                    <p className="font-bold text-slate-800 text-sm">
                      {s.action}
                    </p>
                    <p className="text-xs text-slate-500 mt-0.5">{s.tip}</p>
                  </div>
                </div>
              ))}
            </div>
            <div className="bg-red-50 border border-red-200 rounded-xl p-4">
              <p className="font-bold text-red-800 text-sm mb-1">
                Critical Warning
              </p>
              <p className="text-xs text-slate-700">
                The biggest mistake is reading both passages without writing
                anything down and relying on memory. Under exam pressure, this
                almost always leads to error. The notes take ten seconds and can
                save a minute of confusion.
              </p>
            </div>
          </div>
        </section>

        {/* ── SECTION 1: RELATIONSHIP TYPES & ELIMINATION ── */}
        <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">
            Relationship Types
          </h2>
          <p className="text-lg text-slate-500 mb-8">
            Once the relationship is established, elimination becomes powerful —
            wrong-charge answers can be ruled out immediately.
          </p>

          {/* 3 Relationship Types */}
          <div className="scroll-reveal stagger-1 bg-fuchsia-50 border border-fuchsia-200 rounded-2xl p-6 mb-8 space-y-4">
            <h3 className="text-lg font-bold text-fuchsia-900">
              The 3 Relationship Types &amp; How to Eliminate
            </h3>
            <div className="space-y-3">
              {[
                {
                  type: "Disagree",
                  color: "bg-red-50 border-red-200",
                  badge: "bg-red-600",
                  desc: "Authors have conflicting views on the same topic. Text 1 argues X; Text 2 argues the opposite or Not-X.",
                  elim: 'Eliminate any answer that is positive (e.g., "strongly supported," "generally accurate") or neutral to the point of meaninglessness.',
                },
                {
                  type: "Partially Agree",
                  color: "bg-amber-50 border-amber-200",
                  badge: "bg-amber-600",
                  desc: "Authors share common ground on some aspects but diverge on others.",
                  elim: "Eliminate answers that treat the relationship as purely positive or purely negative — the correct answer acknowledges both what they share and where they differ.",
                },
                {
                  type: "Agree",
                  color: "bg-green-50 border-green-200",
                  badge: "bg-green-600",
                  desc: "Authors reach the same basic conclusion, though they may approach it differently or emphasize different aspects.",
                  elim: "Eliminate answers that overstate the disagreement, or that are accurate for one text but not both.",
                },
              ].map((r) => (
                <div
                  key={r.type}
                  className={`card-tilt border rounded-xl p-4 ${r.color}`}
                >
                  <div className="flex items-center gap-2 mb-2">
                    <span
                      className={`px-3 py-0.5 rounded-full text-white text-xs font-bold ${r.badge}`}
                    >
                      {r.type}
                    </span>
                  </div>
                  <p className="text-sm text-slate-700 mb-1">{r.desc}</p>
                  <p className="text-xs text-slate-500 italic">
                    <span className="font-bold not-italic text-slate-600">
                      To eliminate:{" "}
                    </span>
                    {r.elim}
                  </p>
                </div>
              ))}
            </div>
          </div>

          {/* Words to Watch + Response Patterns */}
          <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">
              Words to Watch &amp; Typical Response Patterns
            </h3>
            <div className="space-y-2 mb-4">
              <p className="text-sm text-slate-600">
                These words in answer choices typically signal incorrect
                answers:
              </p>
              {[
                [
                  '"strongly supported," "proven," "definitively"',
                  "Too positive / too absolute",
                ],
                ['"only possible in," "impossible to"', "Too extreme"],
                ['"highly implausible"', "Usually overstates the disagreement"],
              ].map(([phrase, note]) => (
                <div
                  key={phrase}
                  className="flex gap-3 bg-red-50 border border-red-200 rounded-lg px-4 py-2"
                >
                  <span className="text-red-500 font-bold shrink-0">✗</span>
                  <div>
                    <p className="text-xs font-bold text-red-800 italic">
                      {phrase}
                    </p>
                    <p className="text-xs text-slate-600">{note}</p>
                  </div>
                </div>
              ))}
            </div>
            <p className="text-sm font-semibold text-slate-700 mb-2">
              Typical Response Patterns — tap to reveal example phrasing:
            </p>
            <RevealCardGrid
              cards={RESPONSE_PATTERNS}
              columns={2}
              accentColor="fuchsia"
            />
          </div>

          {/* Scope & Specificity Errors */}
          <div className="scroll-reveal stagger-3 bg-fuchsia-50 border border-fuchsia-200 rounded-2xl p-6 mb-8 space-y-4">
            <h3 className="text-lg font-bold text-fuchsia-900">
              Scope &amp; Specificity Errors — tap to reveal each trap:
            </h3>
            <RevealCardGrid
              cards={SCOPE_ERRORS}
              columns={2}
              accentColor="fuchsia"
            />
          </div>

          <div className="scroll-reveal-scale golden-rule-glow bg-fuchsia-900 text-white rounded-2xl p-5 mb-8">
            <p className="font-bold mb-1">Golden Rule</p>
            <p className="text-sm text-fuchsia-100">
              Summarize each text in one sentence BEFORE reading the question.
              Write it down — do not rely on memory. The question will always be
              about the relationship between those two summaries. If you know
              what each author claims and how they relate, the question becomes
              straightforward.
            </p>
          </div>
        </section>

        {/* ── SECTION 2: 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">
            Connection Finder
          </h2>
          <p className="text-lg text-slate-500 mb-8">
            Find the sentence that directly engages with the other text's
            argument.
          </p>
          <EvidenceHunterWidget
            exercises={EVIDENCE_EXERCISES}
            accentColor="fuchsia"
          />
        </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>
          {CROSS_TEXT_EASY.slice(0, 2).map((q) => (
            <PracticeFromDataset key={q.id} question={q} color="fuchsia" />
          ))}
          {CROSS_TEXT_MEDIUM.slice(0, 1).map((q) => (
            <PracticeFromDataset key={q.id} question={q} color="fuchsia" />
          ))}
          <div className="mt-8 text-center">
            <button
              onClick={onFinish}
              className="px-6 py-3 bg-fuchsia-900 text-white font-bold rounded-full hover:bg-fuchsia-700 transition-colors"
            >
              Finish Lesson ✓
            </button>
          </div>
        </section>
      </div>
    </div>
  );
};

export default EBRWCrossTextLesson;
