/* === Kids Kingdom — App.jsx (single-file React app) === */
const { useState, useEffect, useRef, useMemo } = React;

/* ---------- Hooks ---------- */
function useScrolled(threshold = 30) {
  const [s, setS] = useState(false);
  useEffect(() => {
    const onS = () => setS(window.scrollY > threshold);
    onS();
    window.addEventListener("scroll", onS, { passive: true });
    return () => window.removeEventListener("scroll", onS);
  }, [threshold]);
  return s;
}

function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add("show");
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.15, rootMargin: "0px 0px -60px 0px" });
    els.forEach((el) => io.observe(el));

    // Respaldo para recargas, cambios de viewport y navegación mediante hash:
    // IntersectionObserver puede no emitir una entrada inicial en algunos
    // navegadores si el layout cambia mientras React termina de montar.
    const showVisible = () => {
      els.forEach((el) => {
        const rect = el.getBoundingClientRect();
        if (rect.bottom >= 0 && rect.top <= window.innerHeight) {
          el.classList.add("show");
          io.unobserve(el);
        }
      });
    };
    const raf = requestAnimationFrame(showVisible);
    const fallback = window.setTimeout(showVisible, 350);
    window.addEventListener("hashchange", showVisible);

    return () => {
      cancelAnimationFrame(raf);
      window.clearTimeout(fallback);
      window.removeEventListener("hashchange", showVisible);
      io.disconnect();
    };
  }, []);
}

function useCounter(target, duration = 1600, trigger) {
  const [val, setVal] = useState(0);
  useEffect(() => {
    if (!trigger) return;
    let raf, start;
    const step = (t) => {
      if (!start) start = t;
      const p = Math.min((t - start) / duration, 1);
      setVal(Math.floor(target * (0.5 - Math.cos(p * Math.PI) / 2)));
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [target, duration, trigger]);
  return val;
}

/* ---------- Brand mark (Kids Kingdom logo) ---------- */
function BrandMark({ size = 36 }) {
  return (
    <span className="crown" style={{ width: size, height: size, display: "inline-block" }}>
      <svg viewBox="0 0 64 64" width={size} height={size}>
        {/* Stars above */}
        <path d="M16 8 L18 12 L22 13 L18 14 L16 18 L14 14 L10 13 L14 12 Z" fill="#B8860B"/>
        <path d="M32 4 L34 9 L39 10 L34 11 L32 16 L30 11 L25 10 L30 9 Z" fill="#B8860B"/>
        <path d="M48 8 L50 12 L54 13 L50 14 L48 18 L46 14 L42 13 L46 12 Z" fill="#B8860B"/>
        {/* Left tower (green) */}
        <path d="M10 22 L16 14 L22 22 L22 42 L10 42 Z" fill="#5FB06A"/>
        <rect x="14" y="30" width="4" height="6" fill="#FBF7F0"/>
        <path d="M16 14 L16 11 L20 13 Z" fill="#A83749"/>
        {/* Center tower (dark) - main keep */}
        <path d="M24 18 L24 12 L28 12 L28 16 L32 16 L32 10 L36 10 L36 16 L40 16 L40 12 L44 12 L44 18 L44 42 L24 42 Z" fill="#2A2530"/>
        <path d="M32 30 Q34 26 36 30 L36 38 L32 38 Z" fill="#FBF7F0"/>
        <rect x="29" y="22" width="3" height="4" fill="#FBF7F0"/>
        <rect x="36" y="22" width="3" height="4" fill="#FBF7F0"/>
        {/* Right tower (blue) */}
        <path d="M42 22 L48 14 L54 22 L54 42 L42 42 Z" fill="#4B4591"/>
        <rect x="46" y="30" width="4" height="6" fill="#FBF7F0"/>
        <path d="M48 14 L48 11 L52 13 Z" fill="#A83749"/>
        {/* Book base */}
        <path d="M6 44 Q32 38 58 44 L58 52 Q32 46 6 52 Z" fill="#B8860B"/>
        <path d="M6 44 L6 52 M58 44 L58 52" stroke="#A83749" strokeWidth="2"/>
        <path d="M30 42 L34 42 L34 56 L30 56 Z" fill="#A83749"/>
      </svg>
    </span>
  );
}

/* ---------- NAV ---------- */
function Nav() {
  const scrolled = useScrolled(30);
  const [open, setOpen] = useState(false);
  const links = [
    ["#nosotros", "Nosotros"],
    ["#edades", "Edades"],
    ["#modelo", "Modelo"],
    ["#galeria", "Espacios"],
    ["#faq", "FAQ"],
  ];
  return (
    <>
      <nav className={"nav " + (scrolled ? "scrolled" : "")}>
        <a href="#top" className="logo">
          <BrandMark size={30} />
          <span>Kids Kingdom</span>
        </a>
        <div className="menu">
          {links.map(([h, l]) => (
            <a key={h} href={h}>{l}</a>
          ))}
        </div>
        <div className="nav-actions" style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <a href="/login/" style={{
            fontSize: 14, fontWeight: 700, color: "var(--kk-ink)",
            border: "1.5px solid rgba(26,17,24,0.18)", borderRadius: 12,
            padding: "8px 18px", transition: "all 0.2s", textDecoration: "none",
          }}
          onMouseEnter={e => { e.currentTarget.style.background = "var(--kk-purple)"; e.currentTarget.style.color = "white"; e.currentTarget.style.borderColor = "var(--kk-purple)"; }}
          onMouseLeave={e => { e.currentTarget.style.background = ""; e.currentTarget.style.color = "var(--kk-ink)"; e.currentTarget.style.borderColor = "rgba(26,17,24,0.18)"; }}
          >
            Portal
          </a>
          <a href="#contacto" className="cta">
            Admisiones <Icon.Arrow size={14}/>
          </a>
        </div>
        <button className="burger" onClick={() => setOpen(true)} aria-label="Menú">
          <Icon.Menu />
        </button>
      </nav>
      <div className={"drawer " + (open ? "open" : "")}>
        <button className="close" onClick={() => setOpen(false)} aria-label="Cerrar"><Icon.X /></button>
        {links.map(([h, l]) => (
          <a key={h} href={h} onClick={() => setOpen(false)}>{l}</a>
        ))}
        <a href="/login/" onClick={() => setOpen(false)} style={{ marginTop: 16, display: "inline-flex", alignItems: "center", gap: 8, fontWeight: 700, color: "var(--kk-purple)" }}>
          Ingresar al portal →
        </a>
        <a href="#contacto" onClick={() => setOpen(false)} className="cta" style={{ marginTop: 12, display: "inline-flex" }}>
          Admisiones abiertas <Icon.Arrow size={14}/>
        </a>
      </div>
    </>
  );
}

/* ---------- HERO ---------- */
function Hero() {
  // tilt parallax
  const wrapRef = useRef(null);
  const cardRef = useRef(null);
  useEffect(() => {
    const onMove = (e) => {
      if (!wrapRef.current || !cardRef.current) return;
      const r = wrapRef.current.getBoundingClientRect();
      const x = (e.clientX - r.left) / r.width - 0.5;
      const y = (e.clientY - r.top) / r.height - 0.5;
      cardRef.current.style.transform = `rotateY(${x * 6}deg) rotateX(${-y * 6}deg)`;
    };
    const onLeave = () => { if (cardRef.current) cardRef.current.style.transform = ""; };
    const node = wrapRef.current;
    if (node) {
      node.addEventListener("mousemove", onMove);
      node.addEventListener("mouseleave", onLeave);
    }
    return () => {
      if (node) {
        node.removeEventListener("mousemove", onMove);
        node.removeEventListener("mouseleave", onLeave);
      }
    };
  }, []);

  // stars
  const stars = useMemo(() => (
    Array.from({ length: 28 }).map((_, i) => ({
      l: Math.random() * 100, t: Math.random() * 100,
      d: (Math.random() * 3).toFixed(2), s: 2 + Math.random() * 3,
    }))
  ), []);

  return (
    <section className="hero" id="top">
      {/* deco shapes */}
      <span className="deco s1 spin" aria-hidden>
        <svg width="80" height="80" viewBox="0 0 80 80">
          <path d="M40 6l9 22 23 2-18 14 6 22-20-12-20 12 6-22L8 30l23-2z" fill="#B8860B" opacity="0.85"/>
        </svg>
      </span>
      <span className="deco s2" aria-hidden>
        <svg width="60" height="60" viewBox="0 0 60 60">
          <circle cx="30" cy="30" r="24" fill="#5FB06A" opacity="0.85"/>
          <circle cx="30" cy="30" r="14" fill="#FBF7F0"/>
        </svg>
      </span>
      <span className="deco s3 bounce" aria-hidden>
        <svg width="64" height="64" viewBox="0 0 64 64">
          <rect x="6" y="6" width="52" height="52" rx="18" fill="#A83749" transform="rotate(15 32 32)"/>
        </svg>
      </span>
      <span className="deco s4 spin" aria-hidden>
        <svg width="110" height="110" viewBox="0 0 110 110">
          <circle cx="55" cy="55" r="50" fill="none" stroke="#4B4591" strokeWidth="2" strokeDasharray="4 8"/>
        </svg>
      </span>

      <div>
        <span className="hero-eyebrow reveal">
          <span className="dot"><Icon.Star size={12}/></span>
          Jardín infantil bilingüe · Admisiones 2026
        </span>
        <h1 className="reveal reveal-d1">
          Donde cada niño{" "}
          <span className="underline-wave">aprende</span>
          {" "}<span className="accent">jugando</span>.
        </h1>
        <p className="lead reveal reveal-d2">
          Un modelo educativo flexible que combina lo mejor de Montessori,
          Reggio Emilia, Waldorf y el aprendizaje por proyectos —
          centrado en la curiosidad, el afecto y la autonomía de los más pequeños.
        </p>
        <div className="hero-ctas reveal reveal-d3">
          <a href="#contacto" className="btn btn-primary">
            Agenda una visita
            <span className="arrow"><Icon.Arrow size={14}/></span>
          </a>
          <a href="#modelo" className="btn btn-ghost">
            <span className="arrow"><Icon.Play size={12}/></span>
            Nuestro modelo
          </a>
        </div>
        <div className="hero-stats reveal reveal-d4">
          <Stat n={12} suf="+" l="Años de experiencia"/>
          <Stat n={7}        l="Modelos pedagógicos"/>
          <Stat n={98} suf="%" l="Familias que recomiendan"/>
        </div>
      </div>

      <div className="hero-visual" ref={wrapRef}>
        <div className="castle-card" ref={cardRef} style={{ transition: "transform 0.3s ease", transformStyle: "preserve-3d" }}>
          <div className="castle-stars">
            {stars.map((s, i) => (
              <span key={i} style={{ left: `${s.l}%`, top: `${s.t}%`, animationDelay: `${s.d}s`, width: s.s, height: s.s }}/>
            ))}
          </div>
          {/* Castle SVG */}
          <svg className="castle-svg" viewBox="0 0 300 280" fill="currentColor">
            {/* base */}
            <rect x="30" y="170" width="240" height="80" rx="4" />
            {/* main keep */}
            <rect x="115" y="100" width="70" height="100" rx="2"/>
            {/* towers */}
            <rect x="40" y="120" width="55" height="80" rx="2"/>
            <rect x="205" y="120" width="55" height="80" rx="2"/>
            {/* roofs */}
            <path d="M115 100 L150 50 L185 100 Z"/>
            <path d="M40 120 L67 80 L95 120 Z"/>
            <path d="M205 120 L232 80 L260 120 Z"/>
            {/* flags */}
            <rect x="148" y="20" width="2.5" height="32"/>
            <path d="M150 22 L168 30 L150 38 Z" fill="#B8860B"/>
            <rect x="65" y="55" width="2" height="25"/>
            <path d="M67 56 L80 62 L67 68 Z" fill="#5FB06A"/>
            <rect x="231" y="55" width="2" height="25"/>
            <path d="M233 56 L246 62 L233 68 Z" fill="#A83749"/>
            {/* door */}
            <path d="M138 175 Q150 152 162 175 L162 200 L138 200 Z" fill="#4B4591"/>
            <circle cx="158" cy="188" r="1.5" fill="#B8860B"/>
            {/* windows */}
            <rect x="56" y="140" width="10" height="14" rx="5" fill="#4B4591"/>
            <rect x="78" y="140" width="10" height="14" rx="5" fill="#4B4591"/>
            <rect x="219" y="140" width="10" height="14" rx="5" fill="#4B4591"/>
            <rect x="241" y="140" width="10" height="14" rx="5" fill="#4B4591"/>
            {/* battlements */}
            <g fill="currentColor">
              <rect x="40" y="115" width="8" height="8"/><rect x="55" y="115" width="8" height="8"/>
              <rect x="70" y="115" width="8" height="8"/><rect x="85" y="115" width="8" height="8"/>
              <rect x="205" y="115" width="8" height="8"/><rect x="220" y="115" width="8" height="8"/>
              <rect x="235" y="115" width="8" height="8"/><rect x="250" y="115" width="8" height="8"/>
            </g>
            {/* ground line */}
            <path d="M20 250 Q150 240 280 250" stroke="currentColor" strokeWidth="0" fill="none"/>
          </svg>
        </div>

        <div className="hero-badge b1">
          <span className="ic" style={{background: "var(--kk-green)"}}><Icon.Heart size={20}/></span>
          <div>
            <div className="t">+250</div>
            <div className="s">niños felices</div>
          </div>
        </div>
        <div className="hero-badge b2">
          <span className="ic" style={{background: "var(--kk-purple)"}}><Icon.Book size={18}/></span>
          <div>
            <div className="t">Bilingüe</div>
            <div className="s">desde caminadores</div>
          </div>
        </div>
        <div className="hero-badge b3">
          <span className="ic" style={{background: "var(--kk-red)"}}><Icon.Sparkle size={18}/></span>
          <div>
            <div className="t">STEAM</div>
            <div className="s">y aula invertida</div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Stat({ n, suf = "", l }) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  const showImmediately = window.matchMedia(
    "(max-width: 860px), (prefers-reduced-motion: reduce)"
  ).matches;
  useEffect(() => {
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setSeen(true); io.disconnect(); }
    }, { threshold: 0.5 });
    if (ref.current) io.observe(ref.current);
    const checkVisible = () => {
      if (!ref.current) return;
      const rect = ref.current.getBoundingClientRect();
      if (rect.bottom >= 0 && rect.top <= window.innerHeight) {
        setSeen(true);
        io.disconnect();
      }
    };
    const raf = requestAnimationFrame(checkVisible);
    const fallback = window.setTimeout(checkVisible, 350);
    return () => {
      cancelAnimationFrame(raf);
      window.clearTimeout(fallback);
      io.disconnect();
    };
  }, []);
  const v = useCounter(n, 1500, seen);
  return (
    <div className="stat" ref={ref}>
      <div className="n">{showImmediately ? n : v}{suf}</div>
      <div className="l">{l}</div>
    </div>
  );
}

/* ---------- TICKER ---------- */
function Ticker() {
  const items = ["Curiosidad", "✦", "Afecto", "✦", "Autonomía", "✦", "Juego", "✦", "Creatividad", "✦", "Bilingüismo", "✦", "Naturaleza", "✦"];
  return (
    <div className="ticker" aria-hidden="true">
      <div className="ticker-track">
        <span>{items.concat(items).map((t, i) => (
          <React.Fragment key={i}>
            {t === "✦" ? <span className="dot"/> : <span>{t}</span>}
          </React.Fragment>
        ))}</span>
      </div>
    </div>
  );
}

/* ---------- ABOUT ---------- */
function About() {
  const feats = [
    { ic: <Icon.Heart size={20}/>, c: "var(--kk-red)",    h: "Educación con afecto", p: "Cada vínculo cuenta: docentes formados para acompañar y leer las emociones." },
    { ic: <Icon.Bulb size={20}/>,  c: "var(--kk-gold)",   h: "Aprender haciendo",    p: "Proyectos reales, materiales sensoriales y experimentación constante." },
    { ic: <Icon.Tree size={20}/>,  c: "var(--kk-green)",  h: "Libertad con límites", p: "Ambientes seguros, claros y estimulantes para explorar con confianza." },
  ];
  return (
    <section id="nosotros" className="kk-section">
      <div className="about-grid">
        <div className="about-img-wrap reveal">
          <img src={(window.KK_IMAGES || "static/images/") + "welcome-castle.jpg"} alt="Mural Welcome to our Kids Kingdom Castle" loading="lazy" decoding="async"/>
          <div className="corner-badge">
            <small>Bienvenido a</small>
            Nuestro reino
          </div>
        </div>
        <div>
          <span className="kk-eyebrow reveal">Nosotros</span>
          <h2 className="kk-h2 reveal reveal-d1">
            Un jardín que se siente como un{" "}
            <span style={{color: "var(--kk-red)", fontStyle: "italic"}}>castillo encantado</span>.
          </h2>
          <p className="kk-sub reveal reveal-d2">
            Kids Kingdom es un jardín infantil donde la pedagogía no se sigue al pie
            de la letra: se construye con lo mejor de cada corriente. Tomamos lo más
            valioso de Montessori, Reggio Emilia, Waldorf, el constructivismo y el
            humanismo para acompañar el desarrollo integral de niñas y niños.
          </p>
          <div className="about-features">
            {feats.map((f, i) => (
              <div key={i} className={"about-feature reveal reveal-d" + (i+2)}>
                <span className="ic" style={{ background: f.c }}>{f.ic}</span>
                <div>
                  <h4>{f.h}</h4>
                  <p>{f.p}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- MODELO / APPROACH TABS ---------- */
function Modelo() {
  const tabs = [
    {
      key: "filosofia",
      ic: <Icon.Compass size={18}/>, color: "var(--kk-purple)",
      title: "Filosofía ecléctica",
      h: "No nos casamos con una sola teoría",
      body: "Adoptamos lo mejor de cada corriente según la edad y el momento del niño. Nuestro marco se nutre del constructivismo, el humanismo, el modelo por competencias y modelos alternativos como Montessori, Reggio Emilia y Waldorf.",
      items: ["Constructivismo: aprendizaje activo y significativo", "Humanismo: desarrollo emocional", "Aula invertida y proyectos reales", "Educación tecnológica"]
    },
    {
      key: "docente",
      ic: <Icon.Heart size={18}/>, color: "var(--kk-red)",
      title: "Rol del docente",
      h: "Guía, mentor y diseñador de experiencias",
      body: "El docente no transmite, acompaña. Es facilitador del aprendizaje, mentor emocional y académico, capaz de adaptar su rol según el momento y la necesidad de cada estudiante.",
      items: ["Facilitador y guía", "Diseñador de experiencias significativas", "Mentor emocional y académico", "Observador atento del proceso"]
    },
    {
      key: "evaluacion",
      ic: <Icon.Star size={18}/>, color: "var(--kk-gold)",
      title: "Evaluación viva",
      h: "Formativa, continua y por desempeño",
      body: "Combinamos lo cualitativo y lo cuantitativo. Más que calificar, observamos procesos a través de rúbricas, portafolios, autoevaluación y coevaluación.",
      items: ["Rúbricas y portafolios", "Productos funcionales y proyectos finales", "Autoevaluación y coevaluación", "Retroalimentación continua"]
    },
    {
      key: "curriculo",
      ic: <Icon.Puzzle size={18}/>, color: "var(--kk-green)",
      title: "Currículo flexible",
      h: "Diseñado por proyectos y problemas reales",
      body: "Una planeación interdisciplinaria, transversal y adaptable a mallas curriculares nacionales y locales. Aprender resolviendo retos auténticos.",
      items: ["Enfoque interdisciplinario", "Proyectos, temas y problemas reales", "Adaptable y transversal", "Aprendizaje significativo (ABP)"]
    },
    {
      key: "ambiente",
      ic: <Icon.Tree size={18}/>, color: "var(--kk-purple)",
      title: "Ambiente preparado",
      h: "Estímulo sensorial con libertad y límites",
      body: "Espacios pensados desde Reggio y Montessori: cálidos, seguros, afectivos y colaborativos. Integramos lo físico y lo digital para enriquecer la experiencia.",
      items: ["Estímulo sensorial", "Espacios seguros y afectivos", "Libertad con límites claros", "Integración del entorno físico y digital"]
    },
  ];
  const [active, setActive] = useState(tabs[0].key);
  const cur = tabs.find(t => t.key === active);

  return (
    <section id="modelo" className="kk-section" style={{paddingTop: 60}}>
      <div className="modelo">
        <div className="modelo-header reveal">
          <span className="kk-eyebrow">Modelo educativo integral</span>
          <h2 className="kk-h2" style={{margin: "18px auto 16px"}}>
            Un enfoque <span style={{color: "var(--kk-red)", fontStyle: "italic"}}>flexible</span> centrado en el estudiante.
          </h2>
          <p className="kk-sub">
            Orientado al desarrollo integral — cognitivo, emocional, social y creativo.
            Una mezcla cuidadosamente curada de las mejores tradiciones pedagógicas del mundo.
          </p>
        </div>

        <div className="approach reveal">
          <div className="tabs">
            {tabs.map(t => (
              <button
                key={t.key}
                className={"tab-btn " + (active === t.key ? "active" : "")}
                onClick={() => setActive(t.key)}
              >
                <span className="ic" style={{ background: t.color }}>{t.ic}</span>
                {t.title}
              </button>
            ))}
          </div>
          <div className="tab-panel" key={active} style={{animation: "pop 0.4s ease"}}>
            <div className="panel-badge">0{tabs.findIndex(t => t.key === active)+1}</div>
            <h3>{cur.h}</h3>
            <div className="body">{cur.body}</div>
            <ul>
              {cur.items.map((it, i) => <li key={i}>{it}</li>)}
            </ul>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- PILARES ---------- */
function Pilares() {
  const pillars = [
    { ic: <Icon.Bulb/>,    c: "var(--kk-purple)", t: "Desarrollo cognitivo",        d: "Bases teóricas sólidas a través del constructivismo y métodos tradicionales cuando es necesario.", tags: ["Constructivismo", "Tradicional"] },
    { ic: <Icon.Compass/>, c: "var(--kk-red)",    t: "Autonomía y autorregulación", d: "Espacios y rutinas inspirados en Montessori y aula invertida para que cada niño dirija su aprendizaje.", tags: ["Montessori", "Flipped"] },
    { ic: <Icon.Brush/>,   c: "var(--kk-gold)",   t: "Creatividad y expresión",     d: "Reggio Emilia, Waldorf y STEAM se entrelazan para liberar la imaginación con materiales nobles.", tags: ["Reggio", "Waldorf", "STEAM"] },
    { ic: <Icon.Heart/>,   c: "var(--kk-green)",  t: "Vínculo emocional",            d: "Inspirados en Rogers y Maslow: motivación, autoestima y un acompañamiento humano y cálido.", tags: ["Humanismo"] },
    { ic: <Icon.Puzzle/>,  c: "var(--kk-purple)", t: "Aprendizaje significativo",   d: "Aprendizaje Basado en Proyectos (ABP): el conocimiento se construye resolviendo retos reales.", tags: ["ABP"] },
    { ic: <Icon.Star/>,    c: "var(--kk-red)",    t: "Competencias para la vida",   d: "Modelo por competencias y STEM para preparar a los niños para los retos de su tiempo.", tags: ["Competencias", "STEM"] },
  ];
  return (
    <section id="pilares" className="kk-section">
      <div style={{maxWidth: 700, marginBottom: 50}}>
        <span className="kk-eyebrow reveal">Pilares</span>
        <h2 className="kk-h2 reveal reveal-d1">
          Seis pilares que sostienen{" "}
          <span style={{color: "var(--kk-gold)", fontStyle:"italic"}}>una experiencia integral</span>.
        </h2>
      </div>
      <div className="modelo-grid">
        {pillars.map((p, i) => (
          <div key={i} className="pilar reveal" style={{transitionDelay: `${i * 70}ms`}}>
            <span className="num">0{i+1}</span>
            <span className="ic" style={{ background: p.c }}>{p.ic}</span>
            <h3>{p.t}</h3>
            <p>{p.d}</p>
            <div className="tags">
              {p.tags.map((t, j) => <span key={j}>{t}</span>)}
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ---------- GALLERY ---------- */
function Gallery() {
  const tiles = [
    { src: (window.KK_IMAGES || "static/images/") + "welcome-castle.jpg",   l: "Bienvenida",    cls: "t1" },
    { src: (window.KK_IMAGES || "static/images/") + "sala-mesas.jpg",       l: "Aulas",         cls: "t2" },
    { src: (window.KK_IMAGES || "static/images/") + "sala-cocina.jpg",      l: "Juego de roles",cls: "t3" },
    { src: (window.KK_IMAGES || "static/images/") + "sala-rayas.jpg",       l: "Pasillos",      cls: "t4" },
    { src: (window.KK_IMAGES || "static/images/") + "sala-imaginacion.jpg", l: "Imaginación",   cls: "t5" },
  ];
  return (
    <section id="galeria" className="kk-section">
      <div className="gallery-head">
        <div>
          <span className="kk-eyebrow reveal">Nuestros espacios</span>
          <h2 className="kk-h2 reveal reveal-d1" style={{margin: "16px 0 12px"}}>
            Cada rincón fue pensado para{" "}
            <span style={{color: "var(--kk-green)", fontStyle:"italic"}}>despertar</span>.
          </h2>
          <p className="kk-sub reveal reveal-d2">
            Color, luz, formas y texturas — ambientes diseñados para que los niños
            quieran volver mañana.
          </p>
        </div>
        <a href="#contacto" className="btn btn-ghost reveal reveal-d3">
          <span className="arrow"><Icon.Arrow size={14}/></span>
          Agenda un tour
        </a>
      </div>
      <div className="gallery-grid">
        {tiles.map((t, i) => (
          <div key={i} className={"tile reveal " + t.cls} style={{transitionDelay: `${i * 80}ms`}}>
            <img src={t.src} alt={t.l} loading="lazy"/>
            <div className="overlay"/>
            <div className="label">{t.l}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ---------- ADMISIONES / CONTACT ---------- */
function Admisiones() {
  const [f, setF] = useState({
    nombre: "", apellido: "", telefono: "", email: "",
    edad: "", interes: "", mensaje: "", acepta: false,
  });
  const [errs, setErrs] = useState({});
  const [state, setState] = useState("idle"); // idle | sending | sent
  const set = (k, v) => setF({ ...f, [k]: v });

  const validate = () => {
    const e = {};
    if (!f.nombre.trim()) e.nombre = "Cuéntanos tu nombre";
    if (!f.apellido.trim()) e.apellido = "Falta el apellido";
    if (!/^[0-9 +\-()]{7,}$/.test(f.telefono)) e.telefono = "Teléfono no válido";
    if (!/^\S+@\S+\.\S+$/.test(f.email)) e.email = "Correo no válido";
    if (!f.edad) e.edad = "Selecciona la edad";
    if (!f.interes) e.interes = "¿Cómo podemos ayudarte?";
    if (!f.acepta) e.acepta = "Debes aceptar la política";
    setErrs(e);
    return Object.keys(e).length === 0;
  };

  const submit = async (e) => {
    e.preventDefault();
    if (!validate()) return;
    setState("sending");
    const csrfToken = document.cookie
      .split("; ")
      .find(row => row.startsWith("csrftoken="))
      ?.split("=")[1];
    try {
      const response = await fetch(window.KK_INFORMATION_REQUEST_URL, {
        method: "POST",
        credentials: "same-origin",
        headers: {"Content-Type": "application/json", "X-CSRFToken": csrfToken || ""},
        body: JSON.stringify({
          first_name: f.nombre,
          last_name: f.apellido,
          phone: f.telefono,
          email: f.email,
          child_age: f.edad,
          interest: f.interes,
          message: f.mensaje,
          privacy_accepted: f.acepta,
        }),
      });
      const result = await response.json();
      if (!response.ok) {
        const serverErrors = result.errors || {};
        setErrs({
          nombre: serverErrors.first_name?.message,
          apellido: serverErrors.last_name?.message,
          telefono: serverErrors.phone?.message,
          email: serverErrors.email?.message,
          edad: serverErrors.child_age?.message,
          interes: serverErrors.interest?.message,
          acepta: serverErrors.privacy_accepted?.message,
          general: result.error || (!Object.keys(serverErrors).length ? "No pudimos enviar la solicitud." : ""),
        });
        setState("idle");
        return;
      }
      setState("sent");
      if (typeof fireConfetti === "function") fireConfetti();
    } catch (error) {
      setErrs({...errs, general: "No pudimos conectar. Intenta nuevamente en unos minutos."});
      setState("idle");
    }
  };

  return (
    <section id="contacto" className="kk-section">
      <div className="admisiones-wrap">
        <span className="blob b1"/>
        <span className="blob b2"/>
        <div className="admisiones-grid">
          <div className="info reveal">
            <span className="kk-eyebrow">Admisiones abiertas 2026</span>
            <h2>Reserva un cupo en el reino.</h2>
            <p>
              Déjanos tus datos y te contactaremos para una asesoría personalizada,
              un recorrido por nuestras instalaciones y resolver todas tus dudas.
            </p>
            <div className="contact-list">
              <div className="contact-item">
                <span className="ic"><Icon.Phone/></span>
                <div className="text">
                  <small>Llámanos</small>
                  <strong>+57 310 284 1536</strong>
                </div>
              </div>
              <div className="contact-item">
                <span className="ic"><Icon.Mail/></span>
                <div className="text">
                  <small>Escríbenos</small>
                  <strong>info@kidskingdomcastle.com</strong>
                </div>
              </div>
              <div className="contact-item">
                <span className="ic"><Icon.Pin/></span>
                <div className="text">
                  <small>Visítanos</small>
                  <strong>Carrera 114c #75c-34, Bogotá</strong>
                </div>
              </div>
              <div className="contact-item">
                <span className="ic" style={{background: "rgba(95,176,106,0.4)"}}><Icon.Whats/></span>
                <div className="text">
                  <small>WhatsApp directo</small>
                  <strong>Lunes a viernes, 7am – 5pm</strong>
                </div>
              </div>
            </div>
          </div>

          <div className="form reveal reveal-d2">
            {state === "sent" ? (
              <div className="form-success">
                <div className="check"><Icon.Check size={36}/></div>
                <h3>¡Gracias, {f.nombre}!</h3>
                <p>Hemos recibido tu solicitud. Te contactaremos pronto.</p>
              </div>
            ) : (
              <form onSubmit={submit} noValidate>
                <h3 style={{fontFamily:"var(--font-display)", fontSize:26, margin:"0 0 6px"}}>Cuéntanos sobre ti</h3>
                <p style={{margin:"0 0 22px", color: "var(--kk-gray)", fontSize: 14}}>
                  Respuesta en menos de 24 horas hábiles.
                </p>
                <div className="form-grid">
                  <div className={"field " + (errs.nombre ? "err" : "")}>
                    <label>Nombre *</label>
                    <input value={f.nombre} onChange={e => set("nombre", e.target.value)} placeholder="María"/>
                    {errs.nombre && <span className="err-msg">{errs.nombre}</span>}
                  </div>
                  <div className={"field " + (errs.apellido ? "err" : "")}>
                    <label>Apellido *</label>
                    <input value={f.apellido} onChange={e => set("apellido", e.target.value)} placeholder="González"/>
                    {errs.apellido && <span className="err-msg">{errs.apellido}</span>}
                  </div>
                  <div className={"field " + (errs.telefono ? "err" : "")}>
                    <label>Celular *</label>
                    <input value={f.telefono} onChange={e => set("telefono", e.target.value)} placeholder="+57 300 000 0000"/>
                    {errs.telefono && <span className="err-msg">{errs.telefono}</span>}
                  </div>
                  <div className={"field " + (errs.email ? "err" : "")}>
                    <label>Correo *</label>
                    <input value={f.email} onChange={e => set("email", e.target.value)} placeholder="tucorreo@ejemplo.com"/>
                    {errs.email && <span className="err-msg">{errs.email}</span>}
                  </div>
                  <div className={"field " + (errs.edad ? "err" : "")}>
                    <label>Edad del niño/a *</label>
                    <select value={f.edad} onChange={e => set("edad", e.target.value)}>
                      <option value="">Selecciona</option>
                      <option>Caminadores (1-2 años)</option>
                      <option>Párvulos (2-3 años)</option>
                      <option>Pre-jardín (3-4 años)</option>
                      <option>Jardín (4-5 años)</option>
                      <option>Transición (5-6 años)</option>
                    </select>
                    {errs.edad && <span className="err-msg">{errs.edad}</span>}
                  </div>
                  <div className={"field " + (errs.interes ? "err" : "")}>
                    <label>¿Cómo podemos ayudarte? *</label>
                    <select value={f.interes} onChange={e => set("interes", e.target.value)}>
                      <option value="">Selecciona</option>
                      <option>Información general</option>
                      <option>Agendar visita guiada</option>
                      <option>Costos y matrícula</option>
                      <option>Proceso de admisión</option>
                      <option>Programa bilingüe</option>
                    </select>
                    {errs.interes && <span className="err-msg">{errs.interes}</span>}
                  </div>
                  <div className="field full">
                    <label>Mensaje (opcional)</label>
                    <textarea value={f.mensaje} onChange={e => set("mensaje", e.target.value)} placeholder="Cuéntanos lo que necesitas saber..."/>
                  </div>
                  <div className="full">
                    <label className={"checkbox-row " + (errs.acepta ? "err" : "")}>
                      <input type="checkbox" checked={f.acepta} onChange={e => set("acepta", e.target.checked)}/>
                      <span>He leído y acepto la <a href="#" style={{color: "var(--kk-purple)", fontWeight: 700}}>política de tratamiento de datos</a> de Kids Kingdom.</span>
                    </label>
                    {errs.acepta && <span className="err-msg" style={{marginLeft: 28}}>{errs.acepta}</span>}
                  </div>
                  <button type="submit" className="submit full" disabled={state === "sending"}>
                    {state === "sending" ? "Enviando..." : (<>Enviar solicitud <Icon.Arrow size={16}/></>)}
                  </button>
                  {errs.general && <span className="err-msg full" role="alert" style={{textAlign:"center"}}>{errs.general}</span>}
                </div>
              </form>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- FOOTER ---------- */
function Footer() {
  return (
    <footer className="footer">
      <div className="footer-wave"/>
      <div className="footer-grid">
        <div>
          <div className="brand-line">
            <BrandMark size={36}/>
            Kids Kingdom
          </div>
          <p className="small">
            Jardín infantil con un modelo educativo integral, flexible y ecléctico.
            Donde aprender se siente como jugar y cada niño es protagonista.
          </p>
          <div className="socials">
            <a href="#" aria-label="Instagram"><Icon.Insta/></a>
            <a href="#" aria-label="Facebook"><Icon.Fb/></a>
            <a href="#" aria-label="WhatsApp"><Icon.Whats/></a>
          </div>
        </div>
        <div>
          <h5>Explorar</h5>
          <ul>
            <li><a href="#nosotros">Nosotros</a></li>
            <li><a href="#modelo">Modelo educativo</a></li>
            <li><a href="#pilares">Pilares</a></li>
            <li><a href="#galeria">Espacios</a></li>
          </ul>
        </div>
        <div>
          <h5>Admisiones</h5>
          <ul>
            <li><a href="#contacto">Solicitar información</a></li>
            <li><a href="#contacto">Agendar visita</a></li>
            <li><a href="#contacto">Costos 2026</a></li>
            <li><a href="#contacto">Proceso</a></li>
          </ul>
        </div>
        <div>
          <h5>Contacto</h5>
          <ul>
            <li>+57 310 284 1536</li>
            <li>info@kidskingdomcastle.com</li>
            <li>Carrera 114c #75c-34</li>
            <li>Bogotá, Colombia</li>
          </ul>
        </div>
      </div>
      <div className="copy">
        <span>© {new Date().getFullYear()} Jardín Kids Kingdom. Todos los derechos reservados.</span>
        <span>Hecho con <span style={{color:"var(--kk-red)"}}>♥</span> en Bogotá</span>
      </div>
    </footer>
  );
}

/* ---------- ROOT ---------- */
function App() {
  useReveal();
  return (
    <>
      <ScrollProgress/>
      <AmbientBlobs/>
      <Nav/>
      <Hero/>
      <Ticker/>

      <div className="section-stage">
        <MaskedDeco kind="Crown" place="right" color="var(--kk-gold)" style={{top: "5%", right: "-100px"}}/>
        <About/>
      </div>

      <GaleriaCarrusel/>

      <WaveDivider color="paper" />
      <div className="tint-paper">
        <div className="section-stage">
          <MaskedDeco kind="Scroll" place="left" color="var(--kk-purple)" style={{top: "5%", left: "-120px"}}/>
          <MaskedDeco kind="Star" place="right" color="var(--kk-gold)" style={{bottom: "10%", right: "-80px", top:"auto"}}/>
          <GruposReino/>
        </div>
      </div>
      <WaveDivider color="cream" flip/>

      <Modelo/>

      <div className="section-stage">
        <MaskedDeco kind="Sword" place="left" color="var(--kk-red)" style={{top: "15%", left: "-30px"}}/>
        <MaskedDeco kind="Shield" place="right" color="var(--kk-green)" style={{bottom: "10%", right: "-50px", top: "auto"}}/>
        <Pilares/>
      </div>

      <WaveDivider color="paper" />
      <div className="tint-paper">
        <div className="section-stage">
          <MaskedDeco kind="Scroll" place="left" color="var(--kk-purple)" style={{top: "8%", left: "-100px"}}/>
          <MaskedDeco kind="Star" place="right" color="var(--kk-gold)" style={{bottom: "10%", right: "-60px", top: "auto"}}/>
          <Neuropsicologia/>
        </div>
      </div>
      <WaveDivider color="cream" flip/>

      <WaveDivider color="green" />
      <div className="tint-green">
        <div className="section-stage">
          <MaskedDeco kind="Tower" place="right" color="var(--kk-purple)" style={{top: "10%", right: "-40px"}}/>
          <MaskedDeco kind="Key" place="left" color="var(--kk-gold)" style={{bottom: "15%", left: "-40px", top: "auto"}}/>
          <DiaEnReino/>
        </div>
      </div>
      <WaveDivider color="cream" flip/>

      <div className="section-stage">
        <MaskedDeco kind="Pennant" place="left" color="var(--kk-purple)" style={{top: "20%", left: "-60px"}}/>
        <Testimonios/>
      </div>

      <FAQ/>
      <Certificaciones/>
      <Admisiones/>
      <Footer/>
      <FloatingWhats/>
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
