import React, { useRef, useState, useEffect } from "react";
import { ArrowDown, Check, BookOpen, AlertTriangle, Zap } from "lucide-react";
import { PracticeFromDataset } from "../../../components/lessons/LessonShell";
import {
  BOUNDARIES_EASY,
  BOUNDARIES_MEDIUM,
} from "../../../data/rw/boundaries";
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: "Semicolon — Joining Two ICs",
    segments: [
      {
        text: "The experiment was a success",
        type: "ic",
        label: "Independent Clause",
      },
      { text: ";", type: "punct" },
      { text: " the team celebrated", type: "ic", label: "Independent Clause" },
      { text: ".", type: "punct" },
    ],
  },
  {
    title: "Semicolon + Conjunctive Adverb",
    segments: [
      {
        text: "The data was incomplete",
        type: "ic",
        label: "Independent Clause",
      },
      { text: ";", type: "punct" },
      { text: " however", type: "conjunction", label: "Conjunctive Adverb" },
      { text: ",", type: "punct" },
      {
        text: " the conclusions remained valid",
        type: "ic",
        label: "Independent Clause",
      },
      { text: ".", type: "punct" },
    ],
  },
  {
    title: "Colon — Introduction",
    segments: [
      {
        text: "The study revealed one key finding",
        type: "ic",
        label: "Complete Sentence",
      },
      { text: ":", type: "punct" },
      {
        text: " memory improves with spaced repetition",
        type: "ic",
        label: "What the colon introduces",
      },
      { text: ".", type: "punct" },
    ],
  },
];

// ── Decision Tree data ─────────────────────────────────────────────────────
const TREE_ROOT: TreeNode = {
  id: "root",
  question: "Is this a SEMICOLON or COLON question?",
  hint: "Look at the punctuation options: does the question ask about ; or :?",
  yesLabel: "Semicolon (;)",
  noLabel: "Colon (:)",
  yes: {
    id: "semicolon",
    question:
      "Is the word AFTER the semicolon a conjunctive adverb (however, therefore, moreover, thus, consequently, furthermore)?",
    hint: "These are NOT FANBOYS conjunctions. They look like transitions.",
    yesLabel: "Yes — conjunctive adverb follows",
    noLabel: "No — regular sentence follows",
    yes: {
      id: "semi-conjunctive",
      result:
        "✓ Correct use! Semicolon before the conjunctive adverb, comma after it.",
      resultType: "correct",
      ruleRef: "[IC]; [conjunctive adverb], [IC]",
    },
    no: {
      id: "semi-no-conj",
      question: "Can BOTH sides stand alone as complete sentences?",
      yesLabel: "Yes — both are complete sentences",
      noLabel: "No — one side is incomplete",
      yes: {
        id: "semi-both-ic",
        result: "✓ Correct! A semicolon joins two related independent clauses.",
        resultType: "correct",
        ruleRef: "[IC]; [IC]",
      },
      no: {
        id: "semi-fragment",
        result:
          "⚠ Error! A semicolon requires COMPLETE sentences on both sides. If one side is a phrase or clause, the semicolon is wrong.",
        resultType: "warning",
        ruleRef: "Both sides must be independent clauses",
      },
    },
  },
  no: {
    id: "colon",
    question: "Is the part BEFORE the colon a complete sentence on its own?",
    hint: "Cover everything after the colon. Does what's left make a complete sentence?",
    yesLabel: "Yes — complete sentence before colon",
    noLabel: "No — incomplete phrase before colon",
    yes: {
      id: "colon-complete",
      result:
        "✓ Correct! The colon introduces what follows (list, explanation, or quotation).",
      resultType: "correct",
      ruleRef: "[Complete sentence]: [list / explanation / quotation]",
    },
    no: {
      id: "colon-fragment",
      result:
        '⚠ Error! The part before a colon must ALWAYS be a complete sentence. Never use a colon after an incomplete phrase like "The results included:".',
      resultType: "warning",
      ruleRef:
        "[Complete sentence]: [explanation] — left side must be complete",
    },
  },
};

const TREE_SCENARIOS: TreeScenario[] = [
  {
    label: "Sentence 1",
    sentence:
      "The experiment yielded surprising results however the team chose not to revise their hypothesis.",
    tree: TREE_ROOT,
  },
  {
    label: "Sentence 2",
    sentence:
      "The professor outlined three requirements for the assignment a thesis, supporting evidence, and a conclusion.",
    tree: TREE_ROOT,
  },
  {
    label: "Sentence 3",
    sentence:
      "The researchers disagreed; one believed the effect was temporary, the other argued it was permanent.",
    tree: TREE_ROOT,
  },
];

// ── Lesson component ───────────────────────────────────────────────────────
const EBRWSemicolonsColonsLesson: 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="Clause 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">
            Semicolons &amp; Colons
          </h2>
          <p className="text-lg text-slate-500 mb-8">
            Two marks — very different jobs. Master both to avoid the #1
            punctuation error on the SAT.
          </p>

          {/* Rule summary grid */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-8">
            {[
              {
                num: 1,
                rule: "Semicolon between ICs",
                desc: "Use a semicolon to join two independent clauses without a conjunction. Both sides must be complete sentences.",
              },
              {
                num: 2,
                rule: "Semicolon + Conjunctive Adverb",
                desc: "Use a semicolon BEFORE conjunctive adverbs (however, therefore, moreover, consequently). They are NOT FANBOYS.",
              },
              {
                num: 3,
                rule: "Colon for Explanation/List",
                desc: "Use a colon when the left side is a complete sentence that introduces a list, explanation, or quotation. Never colon if left side is incomplete.",
              },
              {
                num: 4,
                rule: "No comma for conjunctive adverbs",
                desc: 'Never use a comma alone before "however," "therefore," etc. That creates a comma splice.',
              },
            ].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">
            Sentence 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"
          />

          <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">
              A semicolon requires a <em>complete sentence on both sides</em>. A
              colon requires a <em>complete sentence on the left</em> only.
              Conjunctive adverbs like "however" and "therefore" are NOT FANBOYS
              — they always need a semicolon before them, not a comma.
            </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 grammar logic one question at a time. Click your
            answer at each step.
          </p>

          {/* Trap callouts */}
          <div className="space-y-3 mb-8">
            {[
              {
                label: "Conjunctive Adverb Trap",
                desc: 'Students confuse "however," "therefore," etc. with FANBOYS. These words need a semicolon before them, not a comma. "The data was good, however, we needed more" is a comma splice.',
              },
              {
                label: "Colon After Incomplete Phrase",
                desc: 'Never: "The categories include: A, B, C." The word "include" makes it incomplete. Correct: "There are three categories: A, B, C."',
              },
              {
                label: "Two Semicolons in One Clause",
                desc: "If the question has answer choices with extra semicolons in the middle of a clause, they are always wrong.",
              },
            ].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>

          <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>
          {BOUNDARIES_EASY.slice(2, 4).map((q) => (
            <PracticeFromDataset key={q.id} question={q} color="purple" />
          ))}
          {BOUNDARIES_MEDIUM.slice(1, 2).map((q) => (
            <PracticeFromDataset key={q.id} question={q} color="purple" />
          ))}
          <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 EBRWSemicolonsColonsLesson;
