import { motion } from "framer-motion";
import { BrandscapeShell } from "@/components/BrandscapeShell";
import { PageTransition } from "@/components/PageTransition";
import { OrionSchoolHeaderBlock, WhatIsPbelBlock, WhyWaterWhyNowBlock, PbelCycleBlock, WhatYourChildMightDoBlock, FamiliesExpectHelpBlock, BenefitsForYourChildBlock, ServiceLearningIpardBlock, YearTimelineAtGlanceBlock, HowFamiliesCanHelpBlock, DeepInquiryQuestionsBlock, StayInTheLoopBlock } from "@/components/page-blocks";

const fade = {
  hidden: { opacity: 0, y: 8 },
  visible: (i: number) => ({
    opacity: 1,
    y: 0,
    transition: { delay: i * 0.05, duration: 0.45, ease: "easeOut" as const },
  }),
};

/* ── Reusable tiny components ── */

const StepNumber = ({ n }: { n: number }) => (
  <span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-primary text-primary-foreground text-[11px] font-bold mr-1.5 shrink-0">
    {n}
  </span>
);

const GradeLabel = ({ children, className }: { children: React.ReactNode; className?: string }) => (
  <span className={`inline-block text-[11px] font-bold tracking-wide px-2.5 py-0.5 rounded-full text-white mb-1.5 ${className}`}>
    {children}
  </span>
);

const CheckItem = ({ children }: { children: React.ReactNode }) => (
  <li className="relative pl-5 py-0.5 text-[12.5px] leading-relaxed text-muted-foreground before:content-['✓'] before:absolute before:left-0 before:top-0.5 before:text-accent before:font-extrabold before:text-xs">
    {children}
  </li>
);

const BulletItem = ({ children }: { children: React.ReactNode }) => (
  <li className="relative pl-5 py-0.5 text-[12.5px] leading-relaxed text-muted-foreground before:content-[''] before:absolute before:left-0 before:top-[9px] before:w-1.5 before:h-1.5 before:rounded-full before:bg-primary">
    {children}
  </li>
);

const SectionTitle = ({ icon, children, i }: { icon: string; children: React.ReactNode; i: number }) => (
  <motion.h2
    variants={fade}
    initial="hidden"
    whileInView="visible"
    viewport={{ once: true }}
    custom={i}
    className="font-display text-[17px] font-normal text-primary flex items-center gap-2 mt-6 mb-2"
  >
    <span className="text-base opacity-70">{icon}</span>
    {children}
  </motion.h2>
);

const FadeIn = ({ children, i, className }: { children: React.ReactNode; i: number; className?: string }) => (
  <motion.div
    variants={fade}
    initial="hidden"
    whileInView="visible"
    viewport={{ once: true }}
    custom={i}
    className={className}
  >
    {children}
  </motion.div>
);

/* ── Footer bar ── */
const FooterBar = ({ label, page, i }: { label: string; page: number; i: number }) => (
  <FadeIn i={i} className="mt-auto pt-3.5 border-t border-border flex justify-between items-center text-[11px] text-muted-foreground opacity-70">
    <span>{label}</span>
    <span className="flex items-center gap-1.5">
      Page {page}
      <span className="inline-block w-1.5 h-1.5 rounded-full bg-primary ml-1" />
      <span className="inline-block w-1.5 h-1.5 rounded-full bg-accent" />
      <span className="inline-block w-1.5 h-1.5 rounded-full bg-sunflower" />
    </span>
  </FadeIn>
);

/* ══════════════════════════════════════════
   PAGE 1
   ══════════════════════════════════════════ */
const Page1 = () => (
  <BrandscapeShell variant="narrow" paddingY className="relative overflow-hidden">
    {/* Decorative watermarks */}
    <div className="absolute -top-20 -right-20 w-80 h-80 rounded-full bg-[radial-gradient(circle,hsl(var(--primary)/0.05)_0%,transparent_70%)] pointer-events-none" />
    <div className="absolute -bottom-16 -left-16 w-60 h-60 rounded-full bg-[radial-gradient(circle,hsl(var(--accent)/0.05)_0%,transparent_70%)] pointer-events-none" />

    <FadeIn i={0}>
      <OrionSchoolHeaderBlock
        content={{
          label: "Orion STEM Schools",
          title: "Learning by Solving Real Problems",
          subtitle: "This year's theme: Water — Every Drop Counts 💧",
          showBack: true,
          backLabel: "Back",
          backHref: "/grade/kg",
        }}
      />
    </FadeIn>

    {/* What is PBEL callout — reusable block */}
    <FadeIn i={2}>
      <WhatIsPbelBlock
        content={{
          title: "What is PBEL?",
          body: "Problem‑Based Experiential Learning is where students learn by tackling real community challenges. They investigate needs, design and test solutions, measure impact, and share results — building academic skills through meaningful action.",
        }}
      />
    </FadeIn>

    {/* Why Water? Why Now? — reusable block */}
    <FadeIn i={3}>
      <WhyWaterWhyNowBlock
        content={{
          title: "Why Water? Why Now?",
          icon: "🌊",
          body: "Many families around the world cannot access safe water at home. Here at home, our water arrives by pipe — but every drop still matters. We can reduce waste, stop leaks, and protect our creeks and rivers. PBEL helps students connect global challenges to local action.",
        }}
      />
    </FadeIn>

    {/* How It Works — The PBEL Cycle — reusable block */}
    <FadeIn i={5}>
      <PbelCycleBlock
        content={{
          title: "How It Works — The PBEL Cycle",
          icon: "🔄",
          steps: [
            { number: 1, title: "Investigate & Empathize", description: "Observe, interview, and collect baseline data — restroom taps left on, cafeteria pour‑offs, storm‑drain litter." },
            { number: 2, title: "Define & Ideate", description: "Craft \"How might we…?\" questions and brainstorm solutions that are desirable, feasible, and impactful." },
            { number: 3, title: "Prototype & Test", description: "Build simple models (signage, sensors, barrels) and run small pilots to see what truly works." },
            { number: 4, title: "Implement & Serve", description: "With partners, students implement solutions — drain adoption, leak checks, rain‑barrel installation — and track results." },
            { number: 5, title: "Reflect & Demonstrate", description: "Present data‑backed stories at our Innovation & Impact Showcase and hand off maintenance plans." },
          ],
          footerLabel: "One Theme · K–12",
          footerBody: "Our whole school studies the same theme, with developmentally appropriate projects for each grade band.",
        }}
      />
    </FadeIn>

    {/* What Your Child Might Do — reusable block */}
    <FadeIn i={7}>
      <WhatYourChildMightDoBlock
        content={{
          title: "What Your Child Might Do",
          icon: "🎒",
          gradeBands: [
            { label: "K–2", color: "salmon", items: ["Handwashing \"water‑off‑while‑scrubbing\" routines", "Bathroom \"drip detective\" tallies", "Reminder decals & songs for younger peers"] },
            { label: "3–5", color: "accent", items: ["Cafeteria pour‑off audits & nudge signs", "Adopt‑a‑Drain mapping & maintenance", "Rain‑barrel placement for the garden"] },
            { label: "6–8", color: "sunflower", items: ["Leak‑detection checks with simple sensors", "Sensor‑guided irrigation scheduling", "Low‑cost emergency filter demos (no drinking)"] },
            { label: "9–12", color: "moss", items: ["Watershed & runoff hotspot mapping", "Smart meter retrofit prototypes & ROI tests", "Partner pilots and scale‑up plans"] },
          ],
          safetyTitle: "🛡️ Safety & Ethics",
          safetyItems: ["Age‑appropriate tools and supervision", "Water + electricity separation; PPE in labs", "Consent & privacy for interviews/data", "On‑campus service for K–2; approved sites for older grades"],
          successTitle: "📊 What Success Looks Like",
          successSubtitle: "Real savings. Real habits. Real pride.",
          successItems: ["Liters saved each week", "Leaks found and fixed", "Cleaner drains and gardens", "Students who can explain the science, math, and choices behind their solution"],
        }}
      />
    </FadeIn>

    <FooterBar label="Orion STEM Schools · PBEL Family Flyer (Water)" page={1} i={10} />
  </BrandscapeShell>
);

/* ══════════════════════════════════════════
   PAGE 2
   ══════════════════════════════════════════ */
const Page2 = () => (
  <BrandscapeShell variant="narrow" paddingY className="relative overflow-hidden">
    <div className="absolute -top-20 -right-20 w-80 h-80 rounded-full bg-[radial-gradient(circle,hsl(var(--primary)/0.05)_0%,transparent_70%)] pointer-events-none" />
    <div className="absolute -bottom-16 -left-16 w-60 h-60 rounded-full bg-[radial-gradient(circle,hsl(var(--accent)/0.05)_0%,transparent_70%)] pointer-events-none" />

    <FadeIn i={0}>
      <FamiliesExpectHelpBlock
        content={{
          label: "Orion STEM Schools",
          title: "What Families Can Expect — and How You Can Help",
          subtitle: "PBEL · Water — Every Drop Counts 💧",
        }}
      />
    </FadeIn>

    {/* Benefits for Your Child — reusable block */}
    <FadeIn i={1}>
      <BenefitsForYourChildBlock
        content={{
          title: "Benefits for Your Child",
          icon: "🌟",
          cards: [
            { title: "Academic Growth", color: "primary", items: ["Applies science & math to real measurements and data", "Builds literacy through research and clear communication", "Introduces coding, sensors, and design skills"] },
            { title: "Life & Leadership", color: "accent", items: ["Teamwork with rotating roles (lead, builder, data, liaison)", "Growth mindset through testing and iteration", "Community contribution and empathy"] },
          ],
        }}
      />
    </FadeIn>

    {/* Our Service Learning Plan (IPARDE) — reusable block */}
    <FadeIn i={2}>
      <ServiceLearningIpardBlock
        content={{
          title: "Our Service Learning Plan (IPARDE)",
          icon: "🔗",
          stepLabels: ["Investigate", "Prepare", "Action", "Reflect", "Demo", "Evaluate"],
          items: [
            "**Investigation:** Baseline audits & interviews (campus and neighborhood)",
            "**Action:** Leak checks, drain adoption, rain‑barrel installs, irrigation improvements",
            "**Demonstration:** Students share results and hand off maintenance plans to partners",
          ],
        }}
      />
    </FadeIn>

    {/* Year Timeline at a Glance — reusable block */}
    <FadeIn i={3}>
      <YearTimelineAtGlanceBlock
        content={{
          title: "Year Timeline at a Glance",
          icon: "📅",
          cycles: [
            { title: "Cycle 1 · Sep–Oct — Discover & Define", color: "primary", items: ["Investigations & empathy interviews", "Baseline data collected", "Early \"quick‑win\" nudges"] },
            { title: "Cycle 2 · Nov–Jan — Prototype & Pilot", color: "sunflower", items: ["Build simple models and test", "One short pilot per team"] },
            { title: "Cycle 3 · Feb–May — Implement & Demonstrate", color: "accent", items: ["Scale what works with partners", "Track savings & adoption", "Innovation & Impact Showcase (May)"] },
          ],
          portraitTraits: ["Resilient Problem Solver", "Caring Citizen", "Respectful Relationship Builder", "Inspiring Communicator", "Bold Visionary Leader", "Balanced Person"],
        }}
      />
    </FadeIn>

    {/* How Families Can Help — reusable block */}
    <FadeIn i={4}>
      <HowFamiliesCanHelpBlock
        content={{
          title: "How Families Can Help",
          icon: "🏡",
          columns: [
            ["Try the student's water‑saving tips at home", "Send back quick \"what worked\" notes or photos", "Join a drain‑clean or garden day if you can"],
            ["Talk about where your water comes from", "Celebrate small wins (shorter showers, no‑drip taps)", "Ask your child to teach you one thing they learned"],
          ],
        }}
      />
    </FadeIn>

    {/* Deep Inquiry Questions — reusable block */}
    <FadeIn i={5}>
      <DeepInquiryQuestionsBlock
        content={{
          title: "Deep Inquiry Questions",
          icon: "🔍",
          questions: [
            { q: "How does solving a real water problem change the way my child thinks about science and math?", a: "When students measure leaks, calculate water savings, or analyze data from sensors, they experience science and math as tools for impact — not just subjects to study. This builds deeper understanding and lasting motivation." },
            { q: "What happens when a student's solution doesn't work — and why is that valuable?", a: "Failure is designed into the PBEL cycle. When a prototype falls short, students revisit their data, rethink assumptions, and iterate. This builds resilience, critical thinking, and the confidence to tackle complex problems." },
            { q: "How will my child's work actually affect our community — not just the classroom?", a: "Students partner with real organizations, adopt real drains, fix real leaks, and present real data. Their solutions are handed off with maintenance plans so impact continues beyond the school year." },
            { q: "How does studying one theme across K–12 create a different kind of learning culture?", a: "When older students mentor younger ones and every grade contributes to the same mission, students see themselves as part of a larger community of problem-solvers — building empathy, purpose, and school-wide collaboration." },
          ],
        }}
      />
    </FadeIn>

    {/* Stay in the Loop — reusable block (contact bar) */}
    <FadeIn i={6}>
      <StayInTheLoopBlock
        content={{
          leftTitle: "Stay in the Loop",
          leftBody: "Scan the tour QR to see current projects on our Digital Venture Wall and subscribe to Nova, our news update.",
          leftNote: "QR / link placeholder for school use",
          rightTitle: "Questions?",
          rightBody: "We'd love to talk during your tour. You can also reach our team at:",
          rightContactLine: "Email: [your school email] · Phone: [school phone] · Web: [school site]",
          rightNote: "Replace placeholders with your contact info before printing.",
        }}
      />
    </FadeIn>

    <FooterBar label="Orion STEM Schools · PBEL Family Flyer (Water) · Print double‑sided" page={2} i={12} />
  </BrandscapeShell>
);

/* ══════════════════════════════════════════
   MAIN PAGE
   ══════════════════════════════════════════ */
const PbelOverview = () => {
  return (
    <PageTransition>
      <div className="min-h-full bg-background">
        <Page1 />
        <div className="border-t border-border" />
        <Page2 />
      </div>
    </PageTransition>
  );
};

export default PbelOverview;
