/* global React */
const { useEffect, useRef, useState } = React;

/* === Reveal-on-scroll utility (IntersectionObserver) === */
function Reveal({ children, delay = 0, as: Tag = "div", className = "", ...rest }) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => { if (e.isIntersecting) { setSeen(true); io.disconnect(); }});
      },
      { threshold: 0.18 }
    );
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  const cls = `reveal ${seen ? "in" : ""} ${delay ? "d" + delay : ""} ${className}`.trim();
  return <Tag ref={ref} className={cls} {...rest}>{children}</Tag>;
}

/* Mini orb — uses the same chroma-key trick as OrbVideo, smaller */
function MiniOrb({ size = 40 }) {
  return (
    <div style={{ width: size, height: size, position: "relative" }}>
      <OrbVideo />
    </div>
  );
}

/* === Section 1 — Social proof strip === */
function S1Social() {
  const names = ["IB World Schools", "Cambridge Assessment", "British Council", "Colegio Internacional", "Saint George's College", "Lyceum BCN", "Alpha Academy"];
  return (
    <section className="lp-section s1">
      <Reveal>
        <div className="lbl">Trusted in pilots and procurement reviews at</div>
      </Reveal>
      <Reveal delay={1}>
        <div className="row">
          {names.map((n, i) => (
            <React.Fragment key={n}>
              <span className="name">{n}</span>
              {i < names.length - 1 && <span className="dot" aria-hidden />}
            </React.Fragment>
          ))}
        </div>
      </Reveal>
    </section>
  );
}

/* === Section 2 — Why Knora bento === */
function IconMic() {
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
      <rect x="7" y="2" width="6" height="11" rx="3" stroke="currentColor" strokeWidth="1.5"/>
      <path d="M4 10a6 6 0 0012 0M10 16v2M7 18h6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
    </svg>
  );
}
function IconBrain() {
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
      <path d="M7 4.5a2.5 2.5 0 00-2.5 2.5v.5a2.5 2.5 0 000 5V14a2.5 2.5 0 005 0V4.5A2 2 0 007 4.5zM13 4.5a2 2 0 014.5 0V14a2.5 2.5 0 11-5 0V12a2.5 2.5 0 010-5V7" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
    </svg>
  );
}
function IconAdapt() {
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
      <path d="M3 10c2 0 2-4 4-4s2 8 4 8 2-8 4-8 2 4 2 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" fill="none"/>
    </svg>
  );
}
function IconChart() {
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
      <path d="M3 17V7M8 17V3M13 17v-7M18 17v-4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
    </svg>
  );
}

function S2Why() {
  return (
    <section className="lp-section s2" id="product">
      <div className="head">
        <Reveal>
          <div>
            <div className="eyebrow">Why Knora</div>
            <h2 className="sec-h2">A tutor that <span className="grad">speaks, listens, adapts.</span></h2>
          </div>
        </Reveal>
        <Reveal delay={1}>
          <p className="sec-sub" style={{ maxWidth: "44ch", textAlign: "right" }}>
            Built for schools deploying AI at scale — pedagogically grounded, curriculum-aligned, observable.
          </p>
        </Reveal>
      </div>

      <div className="grid">
        <Reveal as="div" className="bento lg">
          <div>
            <div className="icon"><IconMic /></div>
          </div>
          <div className="visual">
            <div className="glow" />
            <div className="v-orb"><OrbVideo /></div>
          </div>
          <div>
            <h3>Voice-first learning</h3>
            <p>Students explain what they know out loud. Knora listens, asks the next question, corrects misconceptions in real time.</p>
          </div>
        </Reveal>

        <Reveal as="div" className="bento" delay={1}>
          <div className="icon"><IconBrain /></div>
          <div>
            <h3>Neuroscience-backed</h3>
            <p>Active recall, spaced repetition (FSRS), Socratic questioning. Methods with decades of replication.</p>
          </div>
        </Reveal>

        <Reveal as="div" className="bento" delay={2}>
          <div className="icon"><IconAdapt /></div>
          <div>
            <h3>Adaptive AI</h3>
            <p>Difficulty, pace and depth adjust per student. Knora teaches harder when ready, gentler when stuck.</p>
          </div>
        </Reveal>

        <Reveal as="div" className="bento" delay={1} style={{ gridColumn: "2 / span 2" }}>
          <div className="icon"><IconChart /></div>
          <div>
            <h3>Track mastery, not minutes</h3>
            <p>Per-topic mastery curves, weak-spot reports for teachers, parent-ready summaries — exported to your SIS.</p>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* === Section 3 — How it works (pinned) === */
function S3How() {
  const trackRef = useRef(null);
  const [progress, setProgress] = useState(0); // 0..1 across the track

  useEffect(() => {
    const onScroll = () => {
      const el = trackRef.current;
      if (!el) return;
      const rect = el.getBoundingClientRect();
      const total = rect.height - window.innerHeight;
      const scrolled = -rect.top;
      const p = Math.max(0, Math.min(1, scrolled / total));
      setProgress(p);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  // 3 stages: 0..0.33 step1, 0.33..0.66 step2, 0.66..1 step3
  const step = progress < 0.33 ? 0 : progress < 0.66 ? 1 : 2;
  const steps = [
    {
      eyebrow: "Step 01",
      h: "Talk to Knora",
      p: "A student opens a topic and starts a conversation. No typing, no quizzes — they just speak.",
    },
    {
      eyebrow: "Step 02",
      h: "Learn by doing",
      p: "Knora asks them to explain, hypothesize, predict. Wrong turns become teaching moments — not red marks.",
    },
    {
      eyebrow: "Step 03",
      h: "Remember forever",
      p: "Sessions feed an FSRS-based spaced-review schedule. Concepts surface again exactly when they're about to be forgotten.",
    },
  ];
  const cur = steps[step];

  // Per-segment fill
  const segFill = (i) => {
    if (i < step) return 1;
    if (i > step) return 0;
    const local = (progress - i / 3) / (1 / 3);
    return Math.max(0, Math.min(1, local));
  };

  return (
    <section className="lp-section s3" id="how">
      <div className="s3-pin-track" ref={trackRef}>
        <div className="s3-pin">
          <div className="inner">
            <div className="left">
              <div className="eyebrow">How it works</div>
              <div key={`num-${step}`} className="step-num">{cur.eyebrow}</div>
              <h3 key={`h-${step}`}>{cur.h}</h3>
              <p key={`p-${step}`}>{cur.p}</p>
              <div className="progress-rail">
                {[0,1,2].map((i) => (
                  <div key={i} className="seg">
                    <span className="fill" style={{ transform: `scaleX(${segFill(i)})` }} />
                  </div>
                ))}
              </div>
            </div>
            <div className="stage-vis">
              <S3Vis index={0} on={step === 0} />
              <S3Vis index={1} on={step === 1} />
              <S3Vis index={2} on={step === 2} />
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function S3Vis({ index, on }) {
  // Three visuals: 0 = orb with sound rings; 1 = chat dialogue; 2 = recall curve
  return (
    <div className={"vis " + (on ? "on" : "")}>
      {index === 0 && (
        <div style={{ position: "relative", width: 360, height: 360 }}>
          <div style={{
            position: "absolute", inset: 0,
            background: "var(--iris-conic)", filter: "blur(40px)", opacity: 0.45,
            borderRadius: "50%", animation: "spin 22s linear infinite",
          }} />
          <div style={{ position: "absolute", inset: 30 }}>
            <OrbVideo />
          </div>
        </div>
      )}
      {index === 1 && (
        <div style={{ display: "flex", flexDirection: "column", gap: 12, width: 340 }}>
          <div className="bubble nora in" style={{ maxWidth: "90%" }}>
            <span className="meta">Nora</span>
            What happens to Kc if we raise the temperature?
          </div>
          <div className="bubble user in" style={{ maxWidth: "75%" }}>
            <span className="meta" style={{ color: "rgba(14,26,64,0.55)" }}>You</span>
            It increases for endothermic reactions.
          </div>
          <div className="bubble nora in" style={{ maxWidth: "90%" }}>
            <span className="meta">Nora</span>
            Right — and what about the rates? Are those the same thing?
          </div>
        </div>
      )}
      {index === 2 && (
        <svg viewBox="0 0 360 240" width="360" height="240">
          <defs>
            <linearGradient id="rc" x1="0" x2="1">
              <stop offset="0" stopColor="#92E8C4"/>
              <stop offset="1" stopColor="#5075F1"/>
            </linearGradient>
          </defs>
          {/* axes */}
          <path d="M30 210 H340 M30 30 V210" stroke="rgba(255,255,255,0.18)" strokeWidth="1"/>
          {/* forgetting curve dashed */}
          <path d="M30 60 C 90 200, 200 215, 340 218" stroke="rgba(255,255,255,0.32)" strokeDasharray="4 6" strokeWidth="1.6" fill="none"/>
          {/* spaced-review staircase */}
          <path d="M30 60 C 70 110, 90 115, 110 80 C 130 50, 160 45, 180 70 C 200 90, 230 95, 250 60 C 270 30, 320 28, 340 35" stroke="url(#rc)" strokeWidth="3" fill="none" strokeLinecap="round"/>
          {/* dots at review points */}
          {[110,180,250,340].map((x,i) => <circle key={i} cx={x} cy={[80,70,60,35][i]} r="5" fill="#92E8C4"/>)}
          <text x="32" y="22" fill="rgba(255,255,255,0.55)" fontSize="11" fontFamily="Inter">Memory strength</text>
          <text x="280" y="230" fill="rgba(255,255,255,0.55)" fontSize="11" fontFamily="Inter">Time</text>
        </svg>
      )}
    </div>
  );
}

/* === Section 4 — Conversation demo === */
function S4Demo() {
  const ref = useRef(null);
  const [shown, setShown] = useState(0);
  const lines = [
    { from: "nora", t: "Welcome back, Ana. Last time we left off on chemical equilibrium — ready to keep going?" },
    { from: "user", t: "Yeah, but I'm still a bit lost on Le Chatelier." },
    { from: "nora", t: "Let's get concrete. If we add more reactant, which way does the system shift?" },
    { from: "user", t: "To the right? Towards more product?" },
    { from: "nora", t: "Exactly — and what does that mean for Kc?" },
    { from: "user", t: "Hmm… does Kc change?" },
    { from: "nora", t: "That's the key insight. Kc only changes with temperature. Concentrations shift, but the constant stays put." },
  ];

  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            // animate bubbles in sequence
            lines.forEach((_, i) => {
              setTimeout(() => setShown((s) => Math.max(s, i + 1)), 600 + i * 700);
            });
            io.disconnect();
          }
        });
      },
      { threshold: 0.35 }
    );
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);

  return (
    <section className="lp-section s4" id="demo" ref={ref}>
      <Reveal>
        <div className="eyebrow">See it in action</div>
        <h2 className="sec-h2">A real session, <span className="grad">unscripted.</span></h2>
        <p className="sec-sub">No prompts to memorize. Knora teaches the way good teachers do — by asking, listening, and following the student's reasoning.</p>
      </Reveal>

      <div className="stage">
        <Reveal delay={1}>
          <div className="phone">
            <div className="head">
              <span className="orb-mini" />
              <div>
                <div className="name">Nora</div>
                <div className="sub">IB Chemistry HL · Equilibrium</div>
              </div>
              <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 6, fontSize: 11, color: "var(--iris-mint)" }}>
                <span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--iris-mint)", boxShadow: "0 0 8px var(--iris-mint)" }} />
                Live
              </div>
            </div>
            <div className="feed">
              {lines.map((l, i) => (
                <div key={i} className={`bubble ${l.from} ${i < shown ? "in" : ""}`}>
                  {l.t}
                </div>
              ))}
            </div>
          </div>
        </Reveal>

        <Reveal delay={2}>
          <div>
            <div style={{ fontFamily: "'Sora','Inter',sans-serif", fontWeight: 700, fontSize: 22, marginBottom: 16, letterSpacing: "-0.02em" }}>
              What teachers see
            </div>
            <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "grid", gap: 14 }}>
              {[
                ["Live transcript", "Searchable, exportable, redactable."],
                ["Topic mastery delta", "Before/after per concept, grounded in conversation evidence."],
                ["Misconception trace", "Where the student got stuck and what unlocked them."],
                ["Curriculum tag", "Every turn linked to IB / LOMLOE / IGCSE descriptors."],
              ].map(([h, p]) => (
                <li key={h} style={{
                  display: "grid", gridTemplateColumns: "8px 1fr", gap: 16, alignItems: "start",
                  padding: "16px 0", borderBottom: "1px solid rgba(255,255,255,0.06)",
                }}>
                  <span style={{ width: 8, height: 8, borderRadius: 999, background: "var(--iris-mint)", marginTop: 6 }} />
                  <div>
                    <div style={{ fontSize: 16, fontWeight: 600, color: "#fff", marginBottom: 4 }}>{h}</div>
                    <div style={{ fontSize: 14, color: "rgba(255,255,255,0.65)" }}>{p}</div>
                  </div>
                </li>
              ))}
            </ul>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* === Section 5 — Backed by science === */
function S5Science() {
  const cards = [
    {
      n: "01",
      h: "Active recall outperforms re-reading",
      p: "Students who self-explain produce ~50% better long-term retention than those who restudy notes — across STEM and humanities.",
      cite: "Karpicke & Blunt, Science (2011)",
    },
    {
      n: "02",
      h: "Desirable difficulties make learning stick",
      p: "Inserting struggle — varied retrieval, interleaved problems — slows initial gains but compounds retention over weeks.",
      cite: "Bjork & Bjork, Psychology of Learning (2011)",
    },
    {
      n: "03",
      h: "Spaced review beats forgetting",
      p: "FSRS modeling reduces required review by ~30% to reach the same retention vs. fixed Anki schedules — at scale.",
      cite: "Wozniak / Ebbinghaus, FSRS-4.5 (2024)",
    },
  ];
  return (
    <section className="lp-section s5">
      <Reveal>
        <div className="eyebrow">Backed by science</div>
        <h2 className="sec-h2">Decades of replication, <span className="grad">not vibes.</span></h2>
        <p className="sec-sub">Every pedagogical choice in Knora is anchored to peer-reviewed work. Here are three you can verify before procurement.</p>
      </Reveal>
      <div className="grid">
        {cards.map((c, i) => (
          <Reveal as="div" className="card" key={c.n} delay={i + 1}>
            <div className="num">{c.n}</div>
            <h3>{c.h}</h3>
            <p>{c.p}</p>
            <div className="cite">{c.cite}</div>
          </Reveal>
        ))}
      </div>
    </section>
  );
}

/* === Section 6 — Trusted-by stats with counters === */
function StatNum({ to, suffix = "", duration = 1600, prefix = "" }) {
  const ref = useRef(null);
  const [v, setV] = useState(0);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            const start = performance.now();
            const tick = (now) => {
              const t = Math.min(1, (now - start) / duration);
              const eased = 1 - Math.pow(1 - t, 3);
              setV(eased * to);
              if (t < 1) requestAnimationFrame(tick);
            };
            requestAnimationFrame(tick);
            io.disconnect();
          }
        });
      },
      { threshold: 0.5 }
    );
    io.observe(ref.current);
    return () => io.disconnect();
  }, [to, duration]);

  const display = Number.isInteger(to) ? Math.round(v) : v.toFixed(1);
  return <span ref={ref}>{prefix}{display}{suffix}</span>;
}

function S6Stats() {
  return (
    <section className="lp-section s6" id="for-schools">
      <Reveal>
        <div className="eyebrow" style={{ justifyContent: "center" }}>Grounded in research</div>
        <h2 className="sec-h2" style={{ marginLeft: "auto", marginRight: "auto", textAlign: "center", maxWidth: "20ch" }}>
          Methods that <span className="grad">withstand scrutiny.</span>
        </h2>
      </Reveal>
      <div className="stats">
        <Reveal as="div" className="stat" delay={1}>
          <div className="num"><StatNum to={50} suffix="%" /></div>
          <div className="lbl">Higher recall with active recall vs. re-reading after one week — the testing effect (Roediger &amp; Karpicke)</div>
        </Reveal>
        <Reveal as="div" className="stat" delay={2}>
          <div className="num"><StatNum to={100} suffix="%" /></div>
          <div className="lbl">of practice captured per concept — teachers see exactly where each student is stuck</div>
        </Reveal>
        <Reveal as="div" className="stat" delay={3}>
          <div className="num">∞</div>
          <div className="lbl">Curricula supported — IB, LOMLOE, IGCSE, AP and more</div>
        </Reveal>
      </div>
    </section>
  );
}

/* === Section 7 — Curriculum cards === */
function S7Curricula() {
  const items = [
    { tag: "International Baccalaureate", name: "IB", meta: "MYP · DP · CP · all six subject groups", accent: "rgba(146,232,196,0.45)" },
    { tag: "Spain · National", name: "LOMLOE", meta: "Primaria · ESO · Bachillerato — competencias clave", accent: "rgba(244,95,136,0.45)" },
    { tag: "Cambridge Assessment", name: "IGCSE", meta: "Lower Secondary, IGCSE, AS & A Level", accent: "rgba(80,117,241,0.5)" },
    { tag: "College Board", name: "AP", meta: "37 AP courses · CED-aligned · exam practice", accent: "rgba(233,137,58,0.45)" },
  ];
  return (
    <section className="lp-section s7" id="curricula">
      <Reveal>
        <div className="eyebrow">Built for your curriculum</div>
        <h2 className="sec-h2">Aligned to <span className="grad">what your school already teaches.</span></h2>
        <p className="sec-sub">Every Knora session tags to descriptors, syllabus codes and assessment objectives — so progress maps cleanly onto your existing reporting.</p>
      </Reveal>
      <div className="row">
        {items.map((c, i) => (
          <Reveal as="div" className="ccard" key={c.name} delay={i + 1}
            style={{ "--accent": c.accent }}>
            <div className="glow" />
            <div className="tag">{c.tag}</div>
            <div className="name">{c.name}</div>
            <div className="meta">{c.meta}</div>
          </Reveal>
        ))}
      </div>
    </section>
  );
}

/* === Section 8 — Final CTA === */
function S8CTA() {
  return (
    <section className="lp-section s8" id="pricing">
      <div className="ring-bg" aria-hidden>
        <OrbVideo />
      </div>
      <Reveal>
        <h2 className="h">
          Bring Knora to <span className="grad" style={{
            background: "linear-gradient(110deg, #A6F2D6, #9AD8FF 38%, #CFBEFF 64%, #FFAACB 90%)",
            backgroundSize: "200% 100%",
            WebkitBackgroundClip: "text", backgroundClip: "text",
            WebkitTextFillColor: "transparent",
            animation: "shimmer 8s ease-in-out infinite",
          }}>your school.</span>
        </h2>
        <p className="sub">Pilot a cohort this term. Free for the first 30 students. Onboarding, training and pedagogical support included.</p>
        <div className="ctas">
          <a className="cta-primary" href="/login" target="_top"><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M2 7h10M8 3l4 4-4 4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg> Book a pilot</a>
          <a className="cta-ghost" href="/login" target="_top">Talk to sales</a>
        </div>
      </Reveal>
    </section>
  );
}

/* === Footer === */
function Footer() {
  return (
    <footer className="lp-footer" id="about">
      <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
        <img src="assets/knora-wordmark.png" alt="knora." style={{ height: 22 }} />
        <span>© 2026 · Knora Education</span>
      </div>
      <div style={{ display: "flex", gap: 28 }}>
        <a href="/privacy" target="_top" style={{ color: "inherit", textDecoration: "none" }}>Privacy</a>
        <a href="/terms" target="_top" style={{ color: "inherit", textDecoration: "none" }}>Terms</a>
        <a href="/contact" target="_top" style={{ color: "inherit", textDecoration: "none" }}>Contact</a>
      </div>
    </footer>
  );
}

/* Export */
Object.assign(window, { S1Social, S2Why, S3How, S4Demo, S5Science, S6Stats, S7Curricula, S8CTA, Footer, Reveal });
