/* global React, ReactDOM */
/* shared.jsx — componentes y utilidades comunes a todas las páginas */
const { useState, useEffect, useRef } = React;

/* Base de assets resuelta desde la URL de ESTE script (shared.jsx, siempre en la
   raíz del sitio). Hace que las imágenes locales carguen igual en la home y en
   subpáginas como /tu-evento/ (subcarpeta), tanto en local (file://) como en el
   servidor — sin depender de rutas relativas ni de un prefijo fijo. */
const ASSET_BASE = (function () {
  try {
    var s = document.querySelector('script[src*="shared.jsx"]');
    if (s && s.src) return s.src.replace(/[^/]*shared\.jsx.*$/, '');
  } catch (e) {}
  return '';
})();

/* ────────── STOCK IMAGES (Unsplash) ────────── */
const IMG = {
  hero: 'https://images.unsplash.com/photo-1519741497674-611481863552?auto=format&fit=crop&w=2000&q=80',
  hero2: 'https://images.unsplash.com/photo-1464366400600-7168b8af9bc3?auto=format&fit=crop&w=2000&q=80',
  hero3: 'https://images.unsplash.com/photo-1465495976277-4387d4b0b4c6?auto=format&fit=crop&w=2000&q=80',
  sobre: ASSET_BASE + 'uploads/sesion/mom.webp',
  expBoda: 'https://images.unsplash.com/photo-1511795409834-ef04bbd61622?auto=format&fit=crop&w=1400&q=80',
  expRet: 'https://images.unsplash.com/photo-1517457373958-b7bdd4587205?auto=format&fit=crop&w=1400&q=80',
  expInt: 'https://images.unsplash.com/photo-1530023367847-a683933f4172?auto=format&fit=crop&w=1400&q=80',
  espExpl: ASSET_BASE + 'uploads/explanada.webp',
  espJard: ASSET_BASE + 'uploads/jardin.webp',
  espCasa: ASSET_BASE + 'uploads/santuario.webp',
  espAmen: ASSET_BASE + 'uploads/caminos.webp',
  bodas: 'https://images.unsplash.com/photo-1519741497674-611481863552?auto=format&fit=crop&w=2000&q=80',
  intimas: 'https://images.unsplash.com/photo-1530023367847-a683933f4172?auto=format&fit=crop&w=2000&q=80',
  parallax1: 'https://images.unsplash.com/photo-1505373877841-8d25f7d46678?auto=format&fit=crop&w=2400&q=85',
  parallax2: 'https://images.unsplash.com/photo-1465495976277-4387d4b0b4c6?auto=format&fit=crop&w=2400&q=85',
  gal: [],

  blog: [
  'https://images.unsplash.com/photo-1469371670807-013ccf25f16a?auto=format&fit=crop&w=1000&q=80',
  'https://images.unsplash.com/photo-1465495976277-4387d4b0b4c6?auto=format&fit=crop&w=1000&q=80',
  'https://images.unsplash.com/photo-1517457373958-b7bdd4587205?auto=format&fit=crop&w=1000&q=80']

};

/* ────────── CUSTOM CURSOR ────────── */
function CustomCursor() {
  const dotRef = useRef(null);
  const ringRef = useRef(null);
  useEffect(() => {
    let dx = 0,dy = 0,rx = 0,ry = 0,mx = 0,my = 0;
    const move = (e) => {mx = e.clientX;my = e.clientY;};
    window.addEventListener('mousemove', move);
    let raf;
    const loop = () => {
      dx += (mx - dx) * 0.85;
      dy += (my - dy) * 0.85;
      rx += (mx - rx) * 0.18;
      ry += (my - ry) * 0.18;
      if (dotRef.current) dotRef.current.style.transform = `translate(${dx}px, ${dy}px) translate(-50%, -50%)`;
      if (ringRef.current) ringRef.current.style.transform = `translate(${rx}px, ${ry}px) translate(-50%, -50%)`;
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);

    const hover = (e) => {
      const t = e.target;
      if (t.closest && t.closest('.wa-float')) {
        dotRef.current?.classList.remove('hover');
        ringRef.current?.classList.remove('hover');
        dotRef.current?.classList.add('neutral');
        ringRef.current?.classList.add('neutral');
      } else if (t.closest && t.closest('a, button, .btn, .exp-card, .gal-item, .blog-card, input, textarea, select')) {
        dotRef.current?.classList.remove('neutral');
        ringRef.current?.classList.remove('neutral');
        dotRef.current?.classList.add('hover');
        ringRef.current?.classList.add('hover');
      } else {
        dotRef.current?.classList.remove('neutral');
        ringRef.current?.classList.remove('neutral');
        dotRef.current?.classList.remove('hover');
        ringRef.current?.classList.remove('hover');
      }
    };
    window.addEventListener('mouseover', hover);

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('mousemove', move);
      window.removeEventListener('mouseover', hover);
    };
  }, []);
  return (
    <>
      <div ref={ringRef} className="cursor-ring" />
      <div ref={dotRef} className="cursor-dot" />
    </>);

}

/* ────────── REVEAL OBSERVER ────────── */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal, .reveal-stagger, .split-line, .manifiesto, .curtain, .ornament, .draw-underline, .mask-reveal');
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {if (e.isIntersecting) e.target.classList.add('in');});
    }, { threshold: 0.15 });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

/* ────────── PARALLAX ────────── */
function useParallax() {
  useEffect(() => {
    const els = document.querySelectorAll('[data-parallax]');
    const onScroll = () => {
      els.forEach((el) => {
        const speed = parseFloat(el.dataset.parallax) || 0.3;
        const rect = el.getBoundingClientRect();
        const center = rect.top + rect.height / 2 - window.innerHeight / 2;
        el.style.transform = `translateY(${center * -speed}px)`;
      });
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
}

/* ────────── BG PARALLAX (background-image style) ────────── */
function useBgParallax() {
  useEffect(() => {
    const els = document.querySelectorAll('[data-bg-parallax]');
    const onScroll = () => {
      els.forEach((el) => {
        const speed = parseFloat(el.dataset.bgParallax) || 0.2;
        const rect = el.getBoundingClientRect();
        const center = rect.top + rect.height / 2 - window.innerHeight / 2;
        el.style.backgroundPosition = `center calc(50% + ${center * speed}px)`;
      });
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
}

/* ────────── SOCIAL LINKS (reutilizable en nav y overlay móvil) ────────── */
function SocialLinks({ className = 'nav-socials' }) {
  return (
    <div className={className}>
      <a href="https://www.instagram.com/quintamompani/" target="_blank" rel="noopener noreferrer" className="nav-social" aria-label="Instagram">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 1 0 0 12.324 6.162 6.162 0 0 0 0-12.324zM12 16a4 4 0 1 1 0-8 4 4 0 0 1 0 8zm6.406-11.845a1.44 1.44 0 1 0 0 2.881 1.44 1.44 0 0 0 0-2.881z"/></svg>
      </a>
      <a href="https://www.facebook.com/profile.php?id=100054273050682" target="_blank" rel="noopener noreferrer" className="nav-social" aria-label="Facebook">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M24 12.073C24 5.446 18.627 0 12 0S0 5.446 0 12.073c0 6.03 4.388 11.02 10.125 11.927v-8.434H7.078v-3.493h3.047V9.43c0-3.025 1.792-4.697 4.533-4.697 1.312 0 2.686.235 2.686.235v2.97h-1.514c-1.491 0-1.956.93-1.956 1.886v2.247h3.328l-.532 3.493h-2.796v8.434C19.612 23.093 24 18.103 24 12.073z"/></svg>
      </a>
    </div>);
}

/* ────────── NAV ────────── */
function Nav({ home = '/' }) {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 80);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  useEffect(() => {
    document.body.style.overflow = menuOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [menuOpen]);
  const close = () => setMenuOpen(false);
  const links = [
    ['/', 'Inicio'],
    ['/tu-evento', 'Tu evento'],
    ['/#galeria', 'Galería'],
    ['/blog', 'Blog'],
    ['/#contacto', 'Contacto']];
  return (
    <>
      <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
        <a href={home} className="nav-logo" aria-label="Quinta Mompaní">
          <img src={`${ASSET_BASE}uploads/logo.png`} alt="Quinta Mompaní" className="logo-img" />
        </a>
        <div className="nav-links">
          {links.map(([h, t]) => <a key={h} href={h}>{t}</a>)}
        </div>
        <SocialLinks />
        <a href="https://wa.link/vtlfzu" target="_blank" rel="noopener noreferrer" className="nav-cta">Hablemos</a>
        <button className="nav-burger" aria-label="Abrir menú" onClick={() => setMenuOpen(true)}>
          <span></span><span></span><span></span>
        </button>
      </nav>
      <div className={`nav-mobile ${menuOpen ? 'open' : ''}`} role="dialog" aria-modal="true" aria-hidden={!menuOpen}>
        <button className="nav-mobile-close" aria-label="Cerrar menú" onClick={close}><span></span><span></span></button>
        <nav className="nav-mobile-links">
          {links.map(([h, t], i) =>
            <a key={h} href={h} onClick={close} style={{ transitionDelay: `${0.12 + i * 0.06}s` }}>{t}</a>)}
        </nav>
        <a href="https://wa.link/vtlfzu" target="_blank" rel="noopener noreferrer" className="btn btn-light nav-mobile-cta" onClick={close}>Hablemos <span className="arrow"></span></a>
        <SocialLinks className="nav-mobile-socials" />
      </div>
    </>);

}

/* ────────── HELPERS ────────── */
function splitWords(text) {
  return text.split(' ').map((w, i) => <span key={i} className="word">{w}&nbsp;</span>);
}

function Particles({ count = 14 }) {
  const arr = Array.from({ length: count });
  return (
    <div className="particles">
      {arr.map((_, i) =>
      <span key={i} className="particle" style={{
        left: `${Math.random() * 100}%`,
        animationDelay: `${Math.random() * 12}s`,
        animationDuration: `${10 + Math.random() * 8}s`,
        width: `${2 + Math.random() * 3}px`,
        height: `${2 + Math.random() * 3}px`
      }} />
      )}
    </div>);

}

function MagneticBtn({ children, ...props }) {
  const ref = useRef(null);
  const onMove = (e) => {
    const r = ref.current.getBoundingClientRect();
    const x = e.clientX - r.left - r.width / 2;
    const y = e.clientY - r.top - r.height / 2;
    ref.current.style.transform = `translate(${x * 0.25}px, ${y * 0.35}px)`;
  };
  const onLeave = () => {ref.current.style.transform = 'translate(0,0)';};
  return (
    <span className="magnetic" onMouseMove={onMove} onMouseLeave={onLeave} ref={ref}>
      <a {...props}>{children}</a>
    </span>);

}

/* ────────── MARQUEE ────────── */
function Ornament({ glyph = '❧' }) {
  return (
    <div className="ornament reveal">
      <span className="glyph">{glyph}</span>
    </div>);

}

function Marquee({ items }) {
  const list = [...items, ...items];
  return (
    <div className="marquee">
      <div className="marquee-track">
        {list.map((item, i) =>
        <React.Fragment key={i}>
            <span className={item.it ? 'it' : ''}>{item.text}</span>
            <span className="star">✦</span>
          </React.Fragment>
        )}
      </div>
    </div>);

}

/* ────────── PARALLAX BG SECTION ────────── */
/* Sección con imagen full-bleed como background y overlay con texto */
function ParallaxSection({ image, overlay = 'light', minHeight = 90, speed = 0.18, padding = '128px 40px', children, className = '' }) {
  const overlayStyle = overlay === 'dark'
    ? { position: 'absolute', inset: 0, zIndex: 1, pointerEvents: 'none',
        background: 'linear-gradient(to top, rgba(5,3,2,0.92) 0%, rgba(5,3,2,0.60) 40%, rgba(5,3,2,0.28) 100%)' }
    : { position: 'absolute', inset: 0, zIndex: 1, pointerEvents: 'none',
        background: 'linear-gradient(135deg, rgba(250,248,244,0.88) 0%, rgba(243,239,232,0.72) 100%)' };
  return (
    <section
      className={`parallax-bg ${overlay === 'dark' ? 'overlay-dark' : 'overlay-light'} ${className}`}
      style={{ position: 'relative', backgroundImage: `url(${image})`, backgroundSize: 'cover', backgroundPosition: 'center', minHeight: `${minHeight}vh`, padding, margin: 0 }}
      data-bg-parallax={speed}>

      <div style={overlayStyle}></div>
      <div className="parallax-content container" style={{ position: 'relative', zIndex: 2 }}>
        {children}
      </div>
    </section>);

}

/* ────────── SUB-HERO compacto para LP titulares ────────── */
function PageHero({ image, eyebrow, title, lead, cta }) {
  const imgRef = useRef(null);
  useEffect(() => {
    const onScroll = () => {
      if (!imgRef.current) return;
      const y = window.scrollY;
      imgRef.current.style.transform = `translateY(${y * 0.32}px) scale(1.05)`;
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <section className="page-hero" data-screen-label="01 Hero">
      <div className="hero-bg">
        <img ref={imgRef} className="hero-img" src={image} alt="" />
      </div>
      <Particles count={14} />
      <div className="hero-content">
        <div className="hero-text">
          <div className="tag reveal"><span className="float-label">{eyebrow}</span></div>
          <h1 className="display split-line">
            <span className="line-row">{title}</span>
          </h1>
          <p className="reveal" style={{ transitionDelay: '0.6s', maxWidth: '620px' }}>{lead}</p>
          {cta &&
          <div className="hero-actions reveal" style={{ transitionDelay: '0.8s' }}>
              <MagneticBtn href="https://wa.link/vtlfzu" target="_blank" rel="noopener noreferrer" className="btn btn-light">{cta} <span className="arrow"></span></MagneticBtn>
            </div>
          }
        </div>
      </div>
      <div className="scroll-indicator">Scroll<div className="line"></div></div>
    </section>);

}

/* ────────── CONTACTO ────────── */
function Contacto() {
  const WA_PHONE = '5214421715407';
  const loadedAt = useRef(Date.now());
  const sendWhatsApp = (e) => {
    e.preventDefault();
    const f = e.currentTarget;
    const get = (n) => ((f.elements[n] && f.elements[n].value) || '').trim();
    // Anti-bot: si el campo trampa (honeypot) está lleno, o el envío es casi
    // instantáneo tras cargar, lo ignoramos en silencio (comportamiento de bot).
    if (get('empresa')) return;
    if (Date.now() - loadedAt.current < 2500) return;
    const nombre = get('nombre');
    const correo = get('correo');
    const tipo = get('tipo');
    const fecha = get('fecha');
    const msg = get('mensaje');
    const lines = [
      'Hola, me gustaría más información sobre Quinta Mompaní.',
      '',
      `*Nombre:* ${nombre}`,
      `*Correo:* ${correo}`,
      `*Tipo de evento:* ${tipo}`];
    if (fecha) lines.push(`*Fecha tentativa:* ${fecha}`);
    if (msg) lines.push(`*Mensaje:* ${msg}`);
    const url = `https://wa.me/${WA_PHONE}?text=${encodeURIComponent(lines.join('\n'))}`;
    window.open(url, '_blank', 'noopener,noreferrer');
  };
  return (
    <section className="contacto" id="contacto" data-screen-label="Contacto">
      <div className="container">
        <div className="contacto-grid">
          <div className="reveal-stagger">
            <div className="eyebrow" style={{ color: 'var(--gold)' }}>Hablemos</div>
            <h2 className="display" style={{ marginTop: '1.5rem' }}>¿Listo para <br /><span className="it">empezar a soñar?</span></h2>
            <p className="contacto-info">
              Platicar con nosotros es fácil. Nuestro asistente virtual está disponible 24/7 para darte respuestas al instante sobre fechas y paquetes. Si detecta que estás listo, te canalizará con un anfitrión humano de inmediato.
            </p>
            <a href="https://wa.link/vtlfzu" target="_blank" rel="noopener noreferrer" className="btn btn-light">Hablemos. Respuestas al instante. <span className="arrow"></span></a>

            <div className="contact-meta">
              <div>
                <span className="lbl">Correo</span>
                <span className="val"><a href="#">quintamompani@gmail.com</a></span>
              </div>
              <div>
                <span className="lbl">Horario</span>
                <span className="val">Martes a sábado de 9 a 5</span>
              </div>
            </div>
          </div>

          <form className="contacto-form reveal" onSubmit={sendWhatsApp}>
            <span className="form-eyebrow">— Formulario rápido</span>
            <h3>Cuéntanos de tu visión.</h3>
            {/* honeypot anti-bot: oculto para humanos, los bots tienden a rellenarlo */}
            <div className="hp-field" aria-hidden="true">
              <label>Empresa</label>
              <input type="text" name="empresa" tabIndex="-1" autoComplete="off" />
            </div>
            <div className="fld">
              <label>Nombre</label>
              <input type="text" name="nombre" required />
            </div>
            <div className="fld">
              <label>Correo</label>
              <input type="email" name="correo" required />
            </div>
            <div className="fld">
              <label>Tipo de evento</label>
              <select name="tipo">
                <option>Celebraciones Íntimas | Entre Semana</option>
                <option>Celebraciones Sociales y Bodas</option>
                <option>Otro</option>
              </select>
            </div>
            <div className="fld">
              <label>Fecha tentativa</label>
              <input type="text" name="fecha" placeholder="Ej. Otoño 2026" />
            </div>
            <div className="fld">
              <label>Cuéntanos más</label>
              <textarea name="mensaje" rows="3"></textarea>
            </div>
            <button type="submit" className="btn btn-light" style={{ marginTop: '1rem' }}>Enviar mensaje <span className="arrow"></span></button>
          </form>
        </div>
      </div>
    </section>);

}

/* ────────── FOOTER ────────── */
function Footer() {
  return (
    <footer>
      <div className="footer-grid">
        <div>
          <div className="footer-brand"><img src={`${ASSET_BASE}uploads/logo.png`} alt="Quinta Mompaní" className="footer-logo" /></div>
          <div className="footer-tag">El refugio donde el tiempo se detiene para que las conexiones florezcan.</div>
        </div>
        <div className="footer-col">
          <h5>Experiencias</h5>
          <ul>
            <li><a href="/tu-evento">Tu evento</a></li>
          </ul>
        </div>
        <div className="footer-col">
          <h5>Refugio</h5>
          <ul>
            <li><a href="/#refugio">Los Espacios</a></li>
            <li><a href="/#filosofia">Filosofía</a></li>
            <li><a href="/#galeria">Galería</a></li>
            <li><a href="/#blog">Blog</a></li>
          </ul>
        </div>
        <div className="footer-col">
          <h5>Contacto</h5>
          <ul>
            <li>Visitas con cita</li>
            <li><a href="https://wa.link/vtlfzu" target="_blank" rel="noopener noreferrer">WhatsApp</a></li>
            <li><a href="https://www.instagram.com/quintamompani/" target="_blank" rel="noopener noreferrer">Instagram</a></li>
            <li><a href="https://www.facebook.com/profile.php?id=100054273050682" target="_blank" rel="noopener noreferrer">Facebook</a></li>
          </ul>
        </div>
      </div>
      <div className="footer-bot">
        <span>© 2026 Quinta Mompaní</span>
        <span>La conexión empieza aquí.</span>
      </div>
    </footer>);

}

/* ────────── WHATSAPP FLOATING ────────── */
function WhatsAppFloat() {
  return (
    <a href="https://wa.link/vtlfzu" target="_blank" rel="noopener noreferrer" className="wa-float" aria-label="Hablemos por WhatsApp">
      <span className="wa-tooltip"><span className="it">Hablemos.</span>Respuestas al instante</span>
      <span className="wa-bubble">
        <svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg"><path d="M16 .4C7.4.4.4 7.4.4 16c0 2.8.7 5.5 2.1 7.9L.3 31.6l7.8-2c2.3 1.3 5 1.9 7.9 1.9 8.6 0 15.6-7 15.6-15.6S24.6.4 16 .4zm0 28.5c-2.5 0-5-.7-7.1-1.9l-.5-.3-5.3 1.4 1.4-5.2-.3-.5C2.9 20.3 2.2 18.2 2.2 16 2.2 8.4 8.4 2.2 16 2.2c7.6 0 13.8 6.2 13.8 13.8S23.6 28.9 16 28.9zm7.6-10.4c-.4-.2-2.5-1.2-2.8-1.4-.4-.1-.7-.2-.9.2s-1.1 1.4-1.3 1.7c-.2.2-.5.3-.9.1-.4-.2-1.7-.6-3.3-2-1.2-1.1-2-2.4-2.2-2.8s0-.7.2-.8c.2-.2.4-.5.6-.7.2-.2.3-.4.4-.7.1-.3.1-.5 0-.7s-.9-2.2-1.3-3c-.3-.8-.7-.7-.9-.7-.2 0-.5 0-.8 0s-.7.1-1.1.5c-.4.4-1.5 1.4-1.5 3.5s1.5 4 1.7 4.3c.2.3 3 4.6 7.3 6.4 1 .4 1.8.7 2.4.9.9.3 1.8.3 2.4.2.7-.1 2.5-1 2.8-2 .3-1 .3-1.8.2-2-.1-.2-.4-.3-.8-.5z" /></svg>
      </span>
    </a>);

}

/* Expose to other Babel scripts */
Object.assign(window, {
  IMG, CustomCursor, useReveal, useParallax, useBgParallax,
  Nav, Hero: null, splitWords, Particles, MagneticBtn, Ornament,
  Marquee, ParallaxSection, PageHero, Contacto, Footer, WhatsAppFloat
});