/* chapters.jsx — the dark "performance" chapters that sit between the hero
   and the cream content: a sticky statement with count-up stats, and the
   hover-expand gallery. Exports to window. */
const { useState: useStateC, useEffect: useEffectC, useRef: useRefC } = React;

/* ---------- CountUp: animates 0→end once on scroll-in (rAF, with a
   timeout fallback so the final value always shows even if throttled) ---------- */
function CountUp({ end, suffix = "", dur = 2000 }) {
  const [val, setVal] = useStateC(0);
  const ref = useRefC(null);
  const done = useRefC(false);
  useEffectC(() => {
    const el = ref.current;
    if (!el) return;
    const run = () => {
      if (done.current) return; done.current = true;
      const t0 = performance.now();
      let raf;
      const step = (now) => {
        const t = Math.min(1, (now - t0) / dur);
        const eased = 1 - Math.pow(1 - t, 3);
        setVal(Math.round(eased * end));
        if (t < 1) raf = requestAnimationFrame(step);
      };
      raf = requestAnimationFrame(step);
      setTimeout(() => { cancelAnimationFrame(raf); setVal(end); }, dur + 250);
    };
    const io = new IntersectionObserver((ents) => {
      ents.forEach((e) => { if (e.isIntersecting) { run(); io.disconnect(); } });
    }, { threshold: 0.3 });
    io.observe(el);
    /* fallback: scroll-based check (fires even when IO is throttled) */
    const onScroll = () => {
      const r = el.getBoundingClientRect();
      if (r.top < window.innerHeight * 0.85 && r.bottom > 0) { run(); window.removeEventListener("scroll", onScroll); }
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => { io.disconnect(); window.removeEventListener("scroll", onScroll); };
  }, [end, dur]);
  return <span ref={ref}>{val}{suffix}</span>;
}

const STATS = [
  { end: 180, suffix: "", label: "Program slots" },
  { end: 11,  suffix: "", label: "Classrooms" },
  { end: 5,   suffix: "", label: "Age programs, 6 wks–5 yr" },
  { end: 100, suffix: "%", label: "Organic, locally-sourced meals" },
];

const ST_LINES = [
  <>Every day is shaped around <b>the child</b> —</>,
  <>guided by <b>Missouri DESE standards</b>, nourished by <span className="accent">organic</span> meals,</>,
  <>and connected to families through technology built for <b>trust</b>.</>,
];

function StatementStats({ refEl }) {
  return (
    <section className="statement-wrap" ref={refEl}>
      <div className="statement">
        <div className="st-grain"></div>
        <div className="st-inner">
          <div className="st-main">
            <p className="st-eyebrow">Our discipline</p>
            <p className="st-text">
              {ST_LINES.map((ln, i) => <span className="st-line" key={i}>{ln}</span>)}
            </p>
            <div className="st-stats">
              {STATS.map((s) => (
                <div className="st-stat" key={s.label}>
                  <div className="st-num"><CountUp end={s.end} suffix={s.suffix} /></div>
                  <div className="st-lbl">{s.label}</div>
                </div>
              ))}
            </div>
          </div>
          <div className="st-photo">
            <image-slot id="story-aerial" shape="rect" fit="cover" src="assets/story-aerial.jpg" placeholder="Aerial view of the campus"></image-slot>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Horizontal scroll-through gallery ---------- */
const TILES = [
  { id: "gal-lobby",  cap: "Lobby & Open Classroom", img: "assets/gallery-lobby.jpg" },
  { id: "gal-infant", cap: "Infant Room",            img: "assets/gallery-infant.jpg" },
  { id: "gal-multi",  cap: "Multipurpose Room",      img: "assets/gallery-multipurpose.jpg" },
  { id: "gal-garden", cap: "Community Garden",       img: "assets/gallery-garden.jpg" },
];
const TICKER = "Mini Scholars \u00A0\u00A0\u2014\u00A0\u00A0 ";

function HoverGallery({ refEl }) {
  return (
    <section className="gallery-wrap" ref={refEl}>
      <div className="gallery">
        <div className="ticker-wrap" aria-hidden="true">
          <div className="ticker-track">
            <span>{TICKER.repeat(6)}</span>
            <span>{TICKER.repeat(6)}</span>
          </div>
        </div>
        <div className="g-head">
          <p className="g-eyebrow">Inside Mini Scholars</p>
          <h2 className="g-title">A day full of wonder</h2>
        </div>
        <div className="g-track">
          {TILES.map((t, i) => (
            <figure className="g-card" key={t.id}>
              <image-slot id={t.id} shape="rect" fit="cover" src={t.img} placeholder={t.cap}></image-slot>
              <figcaption className="g-cap">
                <span className="g-num">0{i + 1}</span>
                <span className="dot"></span>{t.cap}
              </figcaption>
            </figure>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { CountUp, StatementStats, HoverGallery });
