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

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

// ── Clause Breakdown data ──────────────────────────────────────────────────
const CLAUSE_EXAMPLES: ClauseExample[] = [
  {
    title: "Contrast Transition",
    segments: [
      { text: "The sample size was large", type: "ic", label: "First idea" },
      { text: ";", type: "punct" },
      {
        text: " however",
        type: "conjunction",
        label: "Contrast: 'however' shows opposition",
      },
      { text: ",", type: "punct" },
      {
        text: " the results were inconclusive",
        type: "ic",
        label: "Contrasting idea",
      },
      { text: ".", type: "punct" },
    ],
  },
  {
    title: "Cause-Effect Transition",
    segments: [
      {
        text: "The experiment was repeated three times",
        type: "ic",
        label: "Cause / reason",
      },
      { text: ";", type: "punct" },
      {
        text: " therefore",
        type: "conjunction",
        label: "Result: 'therefore' = as a result",
      },
      { text: ",", type: "punct" },
      {
        text: " the team was confident in the data",
        type: "ic",
        label: "Effect / result",
      },
      { text: ".", type: "punct" },
    ],
  },
  {
    title: "Addition Transition",
    segments: [
      {
        text: "The study confirmed the main hypothesis",
        type: "ic",
        label: "First point",
      },
      { text: ";", type: "punct" },
      {
        text: " furthermore",
        type: "conjunction",
        label: "Addition: 'furthermore' adds supporting info",
      },
      { text: ",", type: "punct" },
      {
        text: " it revealed two secondary effects",
        type: "ic",
        label: "Additional point",
      },
      { text: ".", type: "punct" },
    ],
  },
];

// ── Decision Tree data ─────────────────────────────────────────────────────
const TRANSITION_TREE: TreeNode = {
  id: "root",
  question:
    "What is the LOGICAL RELATIONSHIP between the two ideas being connected?",
  hint: "Read both sentences carefully. Does the second idea contradict the first? Follow from it? Add to it? Give an example of it?",
  yesLabel:
    "The second idea CONTRASTS or surprises (despite, however, although)",
  noLabel: "The second idea follows, adds to, or supports",
  yes: {
    id: "contrast",
    question:
      "Is the contrast a direct OPPOSITION (the opposite is true), or just a surprising or unexpected result?",
    yesLabel: "Direct opposition — completely opposite",
    noLabel: "Unexpected or surprising despite circumstances",
    yes: {
      id: "direct-contrast",
      result:
        "✓ Use a strong contrast word: however, on the other hand, in contrast, conversely, yet, but.",
      resultType: "correct",
      ruleRef: "Strong contrast: however / in contrast / conversely",
    },
    no: {
      id: "concession",
      result:
        "✓ Use a concession/nuance word: nevertheless, nonetheless, still, even so, although X, Y.",
      resultType: "correct",
      ruleRef: "Concession/nuance: nevertheless / nonetheless / even so",
    },
  },
  no: {
    id: "not-contrast",
    question:
      "Does the second sentence present a RESULT, CONSEQUENCE, or CONCLUSION from the first?",
    yesLabel: "Yes — cause and effect relationship",
    noLabel: "No — adding information, example, or sequence",
    yes: {
      id: "cause-effect",
      result:
        "✓ Use a cause-effect word: therefore, thus, consequently, as a result, hence.",
      resultType: "correct",
      ruleRef: "Cause-effect: therefore / thus / consequently / as a result",
    },
    no: {
      id: "addition-example",
      question: "Is the second sentence an EXAMPLE that illustrates the first?",
      yesLabel: "Yes — gives a specific example",
      noLabel: "No — adds more supporting information",
      yes: {
        id: "example",
        result:
          "✓ Use an example word: for example, for instance, specifically, in particular.",
        resultType: "correct",
        ruleRef: "Example: for example / for instance / in particular",
      },
      no: {
        id: "addition",
        result:
          "✓ Use an addition word: furthermore, moreover, in addition, additionally, also.",
        resultType: "correct",
        ruleRef:
          "Addition: furthermore / moreover / in addition / additionally",
      },
    },
  },
};

const TREE_SCENARIOS: TreeScenario[] = [
  {
    label: "Sentence 1",
    sentence:
      "The researchers had conducted extensive trials. _____, the medication was approved for widespread use.",
    tree: TRANSITION_TREE,
  },
  {
    label: "Sentence 2",
    sentence:
      "The new policy reduced costs significantly. _____, employee satisfaction dropped by 30%.",
    tree: TRANSITION_TREE,
  },
  {
    label: "Sentence 3",
    sentence:
      "The findings align with previous research. _____, they support the theory proposed in 2018.",
    tree: TRANSITION_TREE,
  },
];

// ── Lesson component ───────────────────────────────────────────────────────
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());
  }, []);

  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-purple-50" : "hover:bg-slate-50"}`}
      >
        <div
          className={`w-8 h-8 rounded-full flex items-center justify-center shrink-0
          ${isActive ? "bg-purple-600 text-white" : isPast ? "bg-purple-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-purple-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="Transition Anatomy" icon={BookOpen} />
          <SectionMarker
            index={1}
            title="Decision Tree Lab"
            icon={AlertTriangle}
          />
          <SectionMarker index={2} title="Practice Questions" icon={Zap} />
        </nav>
      </aside>

      <div className="flex-1 lg:ml-64 p-6 md:p-12 max-w-4xl mx-auto">
        {/* Section 0 — Concept + Clause Breakdown */}
        <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-purple-100 text-purple-700 px-3 py-1 rounded-full text-xs font-bold uppercase tracking-wider mb-4 w-fit">
            Standard English Conventions
          </div>
          <h2 className="text-4xl font-extrabold text-slate-900 mb-2">
            Transitions & Logical Connections
          </h2>
          <p className="text-lg text-slate-500 mb-8">
            See how transitions connect ideas — then learn to pick the right one
            every time.
          </p>

          {/* Rule summary grid */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-8">
            {[
              {
                num: 1,
                rule: "Contrast",
                desc: "however, in contrast, on the other hand, conversely, yet — second idea OPPOSES first.",
              },
              {
                num: 2,
                rule: "Concession",
                desc: "nevertheless, nonetheless, even so, still — unexpected result despite circumstances.",
              },
              {
                num: 3,
                rule: "Cause-Effect",
                desc: "therefore, thus, consequently, as a result — second idea RESULTS from first.",
              },
              {
                num: 4,
                rule: "Addition / Example",
                desc: "furthermore, moreover, additionally / for example, for instance — adds to or illustrates.",
              },
            ].map((r) => (
              <div
                key={r.num}
                className="bg-purple-50 border border-purple-200 rounded-xl p-4"
              >
                <div className="flex items-center gap-2 mb-1">
                  <span className="w-6 h-6 rounded-full bg-purple-600 text-white flex items-center justify-center text-xs font-bold shrink-0">
                    {r.num}
                  </span>
                  <span className="font-bold text-purple-900 text-sm">
                    {r.rule}
                  </span>
                </div>
                <p className="text-xs text-slate-600 ml-8">{r.desc}</p>
              </div>
            ))}
          </div>

          {/* Clause Breakdown */}
          <h3 className="text-xl font-bold text-slate-800 mb-3">
            Transition Anatomy
          </h3>
          <p className="text-sm text-slate-500 mb-4">
            Hover over any colored span to see its label. Use the tabs to switch
            between examples.
          </p>
          <ClauseBreakdownWidget
            examples={CLAUSE_EXAMPLES}
            accentColor="purple"
          />

          {/* Trap callouts */}
          <div className="space-y-3 mt-8 mb-2">
            {[
              {
                label: "Contrast vs. Concession",
                desc: "'however' and 'nevertheless' both show contrast, but 'nevertheless' implies overcoming an obstacle. Don't use them interchangeably.",
              },
              {
                label: "Therefore ≠ Furthermore",
                desc: "'Therefore' means AS A RESULT. 'Furthermore' means IN ADDITION. These are NOT interchangeable. Test: does idea 2 follow FROM idea 1, or just add to it?",
              },
              {
                label: "Wrong Transition Tone",
                desc: "'for example' requires that the second sentence gives a specific INSTANCE of the first claim. 'Moreover' adds more evidence. Mix-up = wrong tone.",
              },
            ].map((t) => (
              <div
                key={t.label}
                className="flex gap-3 bg-red-50 border border-red-200 rounded-xl px-4 py-3"
              >
                <AlertTriangle className="w-4 h-4 text-red-500 shrink-0 mt-0.5" />
                <div>
                  <p className="text-sm font-bold text-red-800">{t.label}</p>
                  <p className="text-xs text-slate-600 mt-0.5">{t.desc}</p>
                </div>
              </div>
            ))}
          </div>

          <div className="mt-6 bg-purple-900 text-white rounded-2xl p-5">
            <p className="font-bold mb-1">Golden Rule</p>
            <p className="text-sm text-purple-100">
              Test every transition by reading both sentences and asking: does
              idea 2 oppose, result from, add to, or illustrate idea 1? Pick the
              category first, then the specific word. Never guess transitions by
              sound — logic is everything.
            </p>
          </div>

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

        {/* Section 1 — Decision Tree */}
        <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">
            Decision Tree Lab
          </h2>
          <p className="text-lg text-slate-500 mb-8">
            Work through the transition logic one question at a time. Click your
            answer at each step.
          </p>

          <DecisionTreeWidget scenarios={TREE_SCENARIOS} accentColor="purple" />

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

        {/* Section 2 — 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 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-purple-900 text-white font-bold rounded-full hover:bg-purple-700 transition-colors"
            >
              Finish Lesson ✓
            </button>
          </div>
        </section>
      </div>
    </div>
  );
};

export default EBRWTransitionsLesson;
