/* Shared components for the prototype. Exposed on window for other babel scripts. */
const { useState, useEffect, useRef, useCallback } = React;

/* ---- hooks ---- */
function useInView(opts) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    if (typeof IntersectionObserver === "undefined") { setSeen(true); return; }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { setSeen(true); io.unobserve(e.target); } });
    }, { threshold: 0.15, rootMargin: "0px 0px -8% 0px", ...(opts || {}) });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return [ref, seen];
}

/* ---- Reveal: scroll-in wrapper ---- */
function Reveal({ children, delay, as, className = "", ...rest }) {
  const [ref, seen] = useInView();
  const Tag = as || "div";
  return (
    <Tag ref={ref} className={`reveal ${seen ? "is-visible" : ""} ${className}`} data-delay={delay} {...rest}>
      {children}
    </Tag>
  );
}

/* ---- animated counter ---- */
function Counter({ to, suffix = "", text, dur = 1600 }) {
  const [ref, seen] = useInView({ threshold: 0.5 });
  const [val, setVal] = useState(0);
  useEffect(() => {
    if (!seen || text) return;
    let raf, start;
    const step = (ts) => {
      if (!start) start = ts;
      const p = Math.min((ts - start) / dur, 1);
      const eased = 1 - Math.pow(1 - p, 3);
      setVal(Math.round(eased * to));
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [seen, to, text, dur]);
  return (
    <span ref={ref} className="num">
      {text ? text : <>{val}<span className="unit">{suffix}</span></>}
    </span>
  );
}

/* ---- icons (minimal, geometric) ---- */
const Arrow = (p) => (
  <svg className="arrow" width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true" {...p}>
    <path d="M5 12h13M13 6l6 6-6 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
  </svg>
);
const Play = (p) => (
  <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" {...p}><path d="M8 5.5v13l11-6.5z"/></svg>
);

/* ---- image placeholder ---- */
function Ph({ motif, tone = "ph--sage", ratio, className = "", style }) {
  return (
    <div className={`ph ${tone} ${className}`} data-ratio={ratio} style={style} role="img" aria-label={`Bildplatzhalter: ${motif}`}>
      <span className="ph__label"><span className="mono">Bild</span> · {motif}</span>
    </div>
  );
}

/* ---- section heading ---- */
function SecHead({ eyebrow, title, children, center, light, className = "" }) {
  return (
    <Reveal className={`sec-head ${center ? "center" : ""} ${className}`}>
      {eyebrow && <span className="eyebrow">{eyebrow}</span>}
      <h2 style={light ? { color: "#fff" } : null}>{title}</h2>
      {children && <p className="lead" style={light ? { color: "rgba(255,255,255,.82)" } : null}>{children}</p>}
    </Reveal>
  );
}

const SunDivider = () => (
  <div className="sun-divider" aria-hidden="true"><span className="dot"></span></div>
);

/* ---- Header ---- */
function Header({ route }) {
  const [open, setOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  useEffect(() => { setOpen(false); }, [route]);
  const items = window.SITE.nav;
  const go = (e, href) => { setOpen(false); };
  return (
    <header className={`site-header ${scrolled ? "scrolled" : ""}`}>
      <div className="container container-wide header-inner">
        <a className="brand" href="#/" aria-label="Montessori Farm Aulendiebach — Start">
          <img src="assets/logo-mfa.png" alt="Montessori Farm Aulendiebach" />
          <span className="brand-text">
            <b>Montessori Farm</b>
            <span>Aulendiebach</span>
          </span>
        </a>
        <nav className="nav" aria-label="Hauptnavigation">
          {items.map((n) => (
            <a key={n.id} href={n.href} className={route === n.id ? "active" : ""}>{n.label}</a>
          ))}
        </nav>
        <a className="btn btn--primary header-cta" href="#/familien">Hospitieren <Arrow /></a>
        <button className="nav-toggle" aria-label="Menü" aria-expanded={open} onClick={() => setOpen(!open)}>
          <span></span><span></span><span></span>
        </button>
      </div>
      <div className={`mobile-nav ${open ? "open" : ""}`}>
        {items.map((n) => (
          <a key={n.id} href={n.href} onClick={(e) => go(e, n.href)} className={route === n.id ? "active" : ""}>{n.label}</a>
        ))}
        <a className="btn btn--primary" href="#/familien" onClick={() => setOpen(false)}>Hospitieren <Arrow /></a>
      </div>
    </header>
  );
}

/* ---- Footer ---- */
function Footer() {
  const items = window.SITE.nav;
  const Social = ({ t }) => (
    <a href="#/" aria-label={t} title={t}><span style={{ fontWeight: 800, fontSize: ".74rem", letterSpacing: ".02em" }}>{t}</span></a>
  );
  return (
    <footer className="site-footer linen">
      <div className="rays rays--sage" style={{ "--ray-opacity": ".035" }} aria-hidden="true"></div>
      <div className="container container-wide">
        <div className="footer-grid">
          <div>
            <div className="footer-logos">
              <span className="chip"><img src="assets/logo-mfa.png" alt="Montessori Farm Aulendiebach" /></span>
              <span className="chip"><img src="assets/logo-mzb.png" alt="Montessori Zentrum Büdingen" /></span>
            </div>
            <p style={{ color: "var(--ink-soft)", maxWidth: "34ch", margin: 0 }}>
              Außerschulischer Lernort nach dem Erdkinderplan. Teil des Montessori Zentrums Büdingen.
            </p>
            <div className="footer-social">
              <Social t="IG" /><Social t="FB" /><Social t="YT" /><Social t="IN" />
            </div>
          </div>
          <div className="footer-col">
            <h4>Navigation</h4>
            <ul>{items.map((n) => <li key={n.id}><a href={n.href}>{n.label}</a></li>)}</ul>
          </div>
          <div className="footer-col">
            <h4>Lernort</h4>
            <ul>
              <li><a href="#/lernort">Erdkinderplan</a></li>
              <li><a href="#/kooperation">Kooperation</a></li>
              <li><a href="#/film">Der Film</a></li>
              <li><a href="#/aktuelles">Blog</a></li>
            </ul>
          </div>
          <div className="footer-col footer-news">
            <h4>Newsletter</h4>
            <p style={{ color: "var(--ink-soft)", margin: "0 0 14px", fontSize: ".94rem" }}>
              Neues vom Lernort, Infoabende und Hospitationstermine.
            </p>
            <form onSubmit={(e) => e.preventDefault()} style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
              <input type="email" placeholder="E-Mail-Adresse" aria-label="E-Mail-Adresse" />
              <button className="btn btn--primary" type="submit" style={{ width: "100%" }}>Anmelden</button>
            </form>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© {new Date().getFullYear()} Montessori Farm Aulendiebach gGmbH</span>
          <span className="legal">
            <a href="#/impressum">Impressum</a>
            <a href="#/datenschutz">Datenschutz</a>
            <a href="#/kontakt">Kontakt</a>
          </span>
        </div>
      </div>
    </footer>
  );
}

/* ---- CTA band reused across pages ---- */
function CtaBand({ title, text, primary, secondary }) {
  return (
    <section className="section section--olive has-rays">
      <div className="rays" aria-hidden="true"></div>
      <div className="container center" style={{ maxWidth: 760 }}>
        <Reveal>
          <h2 style={{ color: "#fff", fontSize: "clamp(1.9rem,3.4vw,2.8rem)" }}>{title}</h2>
          <p className="lead" style={{ color: "rgba(255,255,255,.85)", marginTop: "1rem" }}>{text}</p>
          <div className="hero-ctas" style={{ justifyContent: "center" }}>
            <a className="btn btn--primary btn--lg" href={primary.href}>{primary.label} <Arrow /></a>
            {secondary && <a className="btn btn--light btn--lg" href={secondary.href}>{secondary.label}</a>}
          </div>
        </Reveal>
      </div>
    </section>
  );
}

Object.assign(window, {
  useInView, Reveal, Counter, Arrow, Play, Ph, SecHead, SunDivider, Header, Footer, CtaBand,
});
