const { useState, useEffect, useRef } = React;

/** Correo que recibe el mensaje del formulario (se abre con mailto en el cliente de correo). */
const CONTACT_FORM_EMAIL = 'hola@uzy.agency';
/** WhatsApp en formato internacional sin +: México 52 + 10 dígitos (777 493 3883). */
const WHATSAPP_E164 = '527774933883';

// ---------- Reveal on scroll hook ----------
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); } });
    }, { threshold: 0.12 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
}

// ---------- Arrow icon ----------
const Arrow = ({ size = 16 }) => (
  <svg className="arrow" width={size} height={size} viewBox="0 0 16 16" fill="none">
    <path d="M3 13L13 3M13 3H5M13 3V11" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
  </svg>
);

// ---------- Nav ----------
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 10);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const scrollTo = (id) => (e) => {
    e.preventDefault();
    const el = document.getElementById(id);
    if (el) window.scrollTo({ top: el.offsetTop - 60, behavior: 'smooth' });
  };
  return (
    <div className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="container" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '18px 0' }}>
        <a href="#top" onClick={scrollTo('top')} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ width: 28, height: 28, borderRadius: 8, background: 'var(--ink)', color: 'var(--cream)', display: 'grid', placeItems: 'center', fontWeight: 700, letterSpacing: '-0.05em', fontSize: 15 }}>U</div>
          <span style={{ fontWeight: 600, letterSpacing: '-0.02em', fontSize: 18 }}>Uzy<span style={{ color: 'var(--terra)' }}>.</span>Agency</span>
        </a>
        <nav style={{ display: 'flex', gap: 28, alignItems: 'center' }} className="nav-links">
          <a href="#servicios" onClick={scrollTo('servicios')} className="ulink" style={{ fontSize: 14 }}>Servicios</a>
          <a href="#proceso" onClick={scrollTo('proceso')} className="ulink" style={{ fontSize: 14 }}>Cómo trabajamos</a>
          <a href="#contacto" onClick={scrollTo('contacto')} className="ulink" style={{ fontSize: 14 }}>Contacto</a>
        </nav>
        <CTA to="contacto">Quiero mi sitio</CTA>
      </div>
      <style>{`
        @media (max-width: 860px) {
          .nav-links { display: none !important; }
        }
      `}</style>
    </div>
  );
}

// ---------- CTA (responds to tweaks) ----------
function CTA({ children, to, size = 'md', variant = 'primary' }) {
  const [style, setStyle] = useState(window.__TWEAKS.ctaStyle);
  useEffect(() => {
    const h = (e) => { if (e.detail.key === 'ctaStyle') setStyle(e.detail.val); };
    window.addEventListener('tweakchange', h);
    return () => window.removeEventListener('tweakchange', h);
  }, []);
  const radius = style === 'square' ? 8 : 999;
  const padding = size === 'lg' ? '20px 30px' : '16px 24px';
  const fontSize = size === 'lg' ? 17 : 15;
  const onClick = (e) => {
    if (to) {
      e.preventDefault();
      const el = document.getElementById(to);
      if (el) window.scrollTo({ top: el.offsetTop - 40, behavior: 'smooth' });
    }
  };
  return (
    <button className={`btn btn-${variant}`} style={{ borderRadius: radius, padding, fontSize }} onClick={onClick}>
      {variant === 'primary' && style !== 'arrow' && <span className="dot" />}
      <span>{children}</span>
      {style === 'arrow' && <Arrow />}
    </button>
  );
}

// ---------- Hero ----------
/** Pon en `true` para volver a mostrar la foto del hero y el velo encima. */
const HERO_BACKGROUND_IMAGE_ENABLED = false;

function Hero() {
  const [variant, setVariant] = useState(window.__TWEAKS.heroVariant);
  const [previewHover, setPreviewHover] = useState(false);
  useEffect(() => {
    const h = (e) => { if (e.detail.key === 'heroVariant') setVariant(e.detail.val); };
    window.addEventListener('tweakchange', h);
    return () => window.removeEventListener('tweakchange', h);
  }, []);
  const v = window.HERO_VARIANTS[variant];
  const openAurelPreview = () => {
    window.open('Aurel Studio.html', '_blank', 'noopener,noreferrer');
  };

  return (
    <section
      id="top"
      style={{
        padding: '56px 0 32px',
        backgroundImage: HERO_BACKGROUND_IMAGE_ENABLED ? "url('uploads/background.png')" : 'none',
        backgroundSize: 'cover',
        backgroundPosition: 'center center',
        position: 'relative',
      }}
    >
      <div
        style={{
          position: 'absolute',
          inset: 0,
          background: HERO_BACKGROUND_IMAGE_ENABLED
            ? 'radial-gradient(ellipse 75% 110% at 14% 48%, rgba(250,247,242,0.94) 0%, rgba(250,247,242,0.52) 42%, rgba(250,247,242,0) 68%), linear-gradient(to right, rgba(250,247,242,0.42) 0%, rgba(250,247,242,0.14) 45%, rgba(250,247,242,0.04) 78%, rgba(250,247,242,0) 100%)'
            : 'transparent',
          zIndex: 0,
          pointerEvents: 'none',
        }}
        className="hero-bg-overlay"
        aria-hidden
      />
      <div style={{ position: 'relative', zIndex: 1 }}>
        <div className="container">
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 56 }}>
            <span className="eyebrow"><span className="sq" /> Agencia de desarrollo · 2026</span>
            <span className="mono" style={{ fontSize: 12, color: 'var(--ink-3)' }}>Remoto</span>
          </div>

          <h1 className="display reveal in">
            {v.a}<br/>
            <em>{v.b}</em>
          </h1>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 40, marginTop: 56, alignItems: 'end' }} className="hero-foot">
            <p style={{ maxWidth: '52ch', fontSize: 'clamp(17px, 1.4vw, 20px)', lineHeight: 1.5, color: 'var(--ink-2)', margin: 0 }}>
              Construimos sitios web y landing pages que cargan rápido, convierten mejor y no te hacen
              perder el tiempo con reuniones interminables. Tú nos cuentas. Nosotros lo hacemos.
            </p>
            <div style={{ display: 'flex', gap: 12 }}>
              <CTA to="contacto" size="lg">Quiero mi sitio web</CTA>
            </div>
          </div>

          <style>{`
            @media (max-width: 820px) {
              .hero-foot { grid-template-columns: 1fr !important; gap: 24px !important; }
            }
          `}</style>
        </div>

        {/* big visual footer: stats + placeholder strip */}
        <div className="container" style={{ marginTop: 88, display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 32 }} >
          <div
            role="link"
            tabIndex={0}
            aria-label="Abrir Aurel Studio en una pestaña nueva. Vista previa en vivo de la página."
            onClick={openAurelPreview}
            onKeyDown={(e) => {
              if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                openAurelPreview();
              }
            }}
            onMouseEnter={() => setPreviewHover(true)}
            onMouseLeave={() => setPreviewHover(false)}
            style={{
              display: 'block',
              aspectRatio: '16/9',
              borderRadius: 28,
              overflow: 'hidden',
              position: 'relative',
              cursor: 'pointer',
            }}
          >
            <div
              style={{
                position: 'absolute',
                inset: 0,
                overflow: 'hidden',
                zIndex: 0,
                borderRadius: 28,
              }}
              aria-hidden
            >
              <iframe
                src="Aurel Studio.html"
                title="Vista previa en vivo de Aurel Studio"
                style={{
                  width: 'calc(100% + 28px)',
                  height: '100%',
                  border: 0,
                  display: 'block',
                  pointerEvents: 'none',
                }}
                loading="lazy"
              />
            </div>
            <div style={{
              position: 'absolute', inset: 0,
              zIndex: 1,
              background: previewHover ? 'rgba(44,26,14,0.55)' : 'rgba(44,26,14,0)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              transition: 'background 0.3s ease',
              pointerEvents: 'none',
            }}
            >
              <span style={{
                fontFamily: 'JetBrains Mono, monospace',
                fontSize: 12,
                letterSpacing: '0.1em',
                textTransform: 'uppercase',
                color: '#FAF7F2',
                opacity: previewHover ? 1 : 0,
                transform: previewHover ? 'translateY(0)' : 'translateY(6px)',
                transition: 'opacity 0.3s ease, transform 0.3s ease',
              }}>Ver proyecto →</span>
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateRows: '1fr 1fr', gap: 20 }}>
            <StatCard number="48h" label="Primer prototipo entrega" detail="Desde el kickoff a la primera versión navegable. En serio." />
            <StatCard number="99" label="Lighthouse score medio" detail="Rápido por defecto. Nada de plantillas pesadas." tone="dark" />
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 640px) {
          #top { background-position: center top !important; }
          ${HERO_BACKGROUND_IMAGE_ENABLED ? `#top .hero-bg-overlay {
            background: linear-gradient(to bottom, rgba(250,247,242,0.94) 0%, rgba(250,247,242,0.88) 38%, rgba(250,247,242,0.55) 72%, rgba(250,247,242,0.2) 100%) !important;
          }` : `#top .hero-bg-overlay {
            background: transparent !important;
          }`}
        }
      `}</style>
    </section>
  );
}

function StatCard({ number, label, detail, tone = 'light' }) {
  const dark = tone === 'dark';
  return (
    <div style={{
      borderRadius: 28,
      padding: '28px 28px',
      background: dark ? 'var(--ink)' : 'var(--cream-2)',
      color: dark ? 'var(--cream)' : 'var(--ink)',
      display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
      border: dark ? 'none' : '1px solid var(--line)'
    }}>
      <div style={{ fontFamily: 'Fraunces, serif', fontSize: 'clamp(48px, 5vw, 72px)', lineHeight: 1, letterSpacing: '-0.03em', fontWeight: 300 }}>
        {number}
      </div>
      <div>
        <div style={{ fontSize: 15, fontWeight: 500, marginTop: 18 }}>{label}</div>
        <div style={{ fontSize: 13, marginTop: 6, color: dark ? 'rgba(250,247,242,0.6)' : 'var(--ink-3)', lineHeight: 1.5 }}>{detail}</div>
      </div>
    </div>
  );
}

// ---------- Marquee ----------
function Marquee() {
  const items = [
    "Diseño que convierte",
    "Código limpio",
    "Entrega en semanas, no meses",
    "Mobile-first de verdad",
    "SEO que no es humo",
    "Accesible por defecto",
    "Analítica incluida",
    "Hosting rápido",
  ];
  const doubled = [...items, ...items];
  return (
    <div className="marquee" aria-hidden>
      <div className="marquee-track">
        {doubled.map((t, i) => (
          <div className="marq-item" key={i}>
            <span style={{ fontFamily: 'Fraunces, serif', fontStyle: 'italic', fontSize: 22, fontWeight: 300 }}>{t}</span>
            <span style={{ color: 'var(--terra)' }}>✦</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ---------- Services ----------
function Services() {
  const items = [
    {
      n: '01', title: 'Diseño web',
      desc: 'Sitios corporativos con personalidad. Identidad visual fuerte, contenido claro y una estructura que guía al visitante a la acción.',
      bullets: ['Hasta 8 páginas', 'CMS opcional', 'Responsivo real']
    },
    {
      n: '02', title: 'Landing pages',
      desc: 'Una página. Un objetivo. Cero distracciones. Optimizadas para campañas, lanzamientos y conversión directa.',
      bullets: ['A/B testing listo', 'Integración CRM', 'Carga < 1s']
    },
    {
      n: '03', title: 'Desarrollo a medida',
      desc: '¿Algo fuera del catálogo? Dashboards, portales, herramientas internas. Si se puede construir, lo construimos.',
      bullets: ['Stack moderno', 'Código tuyo', 'Sin caja negra']
    },
  ];
  return (
    <section id="servicios" style={{ padding: '120px 0 32px' }} className="reveal">
      <div className="container">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 40, marginBottom: 56, alignItems: 'end' }} className="svc-head">
          <div>
            <span className="eyebrow" style={{ marginBottom: 20, display: 'inline-flex' }}><span className="sq" /> Servicios</span>
            <h2 className="section-h" style={{ marginTop: 16 }}>
              Tres formas de <em>trabajar juntos.</em>
            </h2>
          </div>
          <p style={{ fontSize: 17, color: 'var(--ink-2)', lineHeight: 1.55, maxWidth: '42ch', margin: 0, justifySelf: 'end' }}>
            Paquetes claros, precios claros, entregables claros. Lo que ves es lo que pagas.
            Nada de sorpresas a mitad de proyecto.
          </p>
        </div>

        <div>
          {items.map((it) => (
            <div className="svc" key={it.n}>
              <div className="num">{it.n}</div>
              <div className="title">{it.title}</div>
              <div>
                <div className="desc">{it.desc}</div>
                <ul style={{ margin: '16px 0 0', padding: 0, listStyle: 'none', display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                  {it.bullets.map(b => (
                    <li key={b} style={{ fontFamily: 'JetBrains Mono', fontSize: 11, letterSpacing: '0.05em', padding: '4px 10px', border: '1px solid var(--line)', borderRadius: 999, color: 'var(--ink-2)' }}>{b}</li>
                  ))}
                </ul>
              </div>
              <div className="go" aria-hidden>
                <Arrow size={18} />
              </div>
            </div>
          ))}
        </div>
      </div>
      <style>{`
        @media (max-width: 820px) {
          .svc-head { grid-template-columns: 1fr !important; gap: 24px !important; }
          .svc-head p { justify-self: start !important; }
        }
      `}</style>
    </section>
  );
}

// ---------- Process (Cómo trabajamos) ----------
function Process() {
  const items = [
    {
      n: '01', k: 'Nos cuentas',
      t: 'Una llamada o un correo. Punto.',
      d: 'Treinta minutos. Nos dices qué necesitas, nosotros te decimos si podemos ayudarte y cuánto cuesta. Sin catálogos, sin formularios infinitos.',
    },
    {
      n: '02', k: 'Diseñamos y construimos',
      t: 'Prototipo en 48h. Web en semanas.',
      d: 'Te mandamos avances reales — links navegables, no PowerPoints de promesas. Si algo no cuadra, lo cambiamos antes de seguir.',
    },
    {
      n: '03', k: 'Entregas y lanzas',
      t: 'El código es tuyo. Sin letra pequeña.',
      d: 'El hosting lo manejas tú o nosotros, como prefieras. Sin dependencias raras, sin cláusulas de secuestro. Te vas cuando quieras.',
    },
  ];
  return (
    <section id="proceso" style={{ padding: '120px 0', background: 'var(--ink)', color: 'var(--cream)' }} className="reveal">
      <div className="container">
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 64, flexWrap: 'wrap', gap: 20 }}>
          <span className="eyebrow" style={{ color: 'var(--terra-soft)' }}><span className="sq" style={{ background: 'var(--terra)' }} /> Cómo trabajamos</span>
          <span className="mono" style={{ fontSize: 12, color: 'rgba(250,247,242,0.5)' }}>/ 03 pasos</span>
        </div>

        <h2 className="section-h" style={{ color: 'var(--cream)', marginBottom: 72, maxWidth: '18ch' }}>
          Simple.<br/><em style={{ color: 'var(--terra-soft)' }}>En serio.</em>
        </h2>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0 }} className="why-grid">
          {items.map((it, i) => (
            <div key={it.n} style={{
              padding: '40px 28px 40px',
              borderLeft: '1px solid rgba(250,247,242,0.12)',
              borderRight: i === items.length - 1 ? '1px solid rgba(250,247,242,0.12)' : 'none'
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 28 }}>
                <span className="mono" style={{ fontSize: 11, color: 'var(--terra-soft)', letterSpacing: '0.1em' }}>PASO {it.n}</span>
                <span style={{ height: 1, background: 'rgba(250,247,242,0.2)', flex: 1 }} />
                <span className="mono" style={{ fontSize: 11, color: 'rgba(250,247,242,0.4)', letterSpacing: '0.1em' }}>{it.k.toUpperCase()}</span>
              </div>
              <div style={{ fontFamily: 'Fraunces, serif', fontWeight: 300, fontSize: 28, lineHeight: 1.15, letterSpacing: '-0.015em', marginBottom: 16 }}>
                {it.t}
              </div>
              <div style={{ fontSize: 15, color: 'rgba(250,247,242,0.7)', lineHeight: 1.55 }}>{it.d}</div>
            </div>
          ))}
        </div>
      </div>
      <style>{`
        @media (max-width: 820px) {
          .why-grid { grid-template-columns: 1fr !important; }
          .why-grid > div { border-right: none !important; border-bottom: 1px solid rgba(250,247,242,0.12); border-left: none !important; padding: 32px 0 !important; }
        }
      `}</style>
    </section>
  );
}

// ---------- FAQ ----------
function FAQ() {
  const items = [
    {
      q: '¿Cuánto tarda un proyecto?',
      a: 'Una landing: 1-2 semanas. Una web completa: 3-4 semanas. Nada de "depende" sin contexto: en la primera llamada te damos fechas concretas y las cumplimos.',
    },
    {
      q: '¿Cuánto cuesta?',
      a: 'Las landings arrancan desde un precio fijo, las webs completas también. Te damos el número exacto tras una primera llamada de 30 minutos. Sin sorpresas a mitad de proyecto, sin extras escondidos.',
    },
    {
      q: '¿Y si no me gusta el resultado?',
      a: 'No va a pasar, porque trabajamos con prototipos y aprobaciones por etapas. No aparecemos un día con algo terminado que nadie pidió. Validas tú, avanzamos nosotros.',
    },
    {
      q: '¿Necesito saber de tecnología?',
      a: 'Para nada. Tú nos cuentas qué necesitas en castellano normal — "quiero que la gente reserve mesa", "que se vea bien en el móvil" — y nosotros lo traducimos a código.',
    },
    {
      q: '¿El código es mío?',
      a: 'Sí. Todo tuyo. Repositorio, hosting, dominio: tu nombre. Sin licencias raras, sin dependencia de nosotros para cambiar una foto o un precio. Te vas cuando quieras y cómo quieras.',
    },
  ];
  const [open, setOpen] = useState(0);
  return (
    <section id="faq" style={{ padding: '120px 0', background: 'var(--cream-2)', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }} className="reveal">
      <div className="container">
        <div style={{ display: 'grid', gridTemplateColumns: '0.85fr 1.15fr', gap: 80, alignItems: 'start' }} className="faq-grid">
          <div style={{ position: 'sticky', top: 100 }}>
            <span className="eyebrow" style={{ marginBottom: 20, display: 'inline-flex' }}><span className="sq" /> FAQ</span>
            <h2 className="section-h" style={{ marginTop: 16 }}>
              Todo lo que ibas<br/><em>a preguntar.</em>
            </h2>
            <p style={{ fontSize: 16, color: 'var(--ink-2)', lineHeight: 1.55, maxWidth: '36ch', marginTop: 24 }}>
              ¿Falta alguna? Escríbenos directamente y te respondemos sin guion comercial.
            </p>
          </div>

          <div>
            {items.map((it, i) => {
              const isOpen = open === i;
              return (
                <div key={i} style={{ borderTop: i === 0 ? '1px solid var(--line)' : 'none', borderBottom: '1px solid var(--line)' }}>
                  <button
                    onClick={() => setOpen(isOpen ? -1 : i)}
                    style={{
                      width: '100%',
                      background: 'transparent',
                      border: 0,
                      padding: '28px 0',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'space-between',
                      gap: 24,
                      cursor: 'pointer',
                      textAlign: 'left',
                      color: 'var(--ink)',
                    }}
                  >
                    <span style={{ display: 'flex', alignItems: 'baseline', gap: 16 }}>
                      <span className="mono" style={{ fontSize: 12, color: 'var(--ink-3)', letterSpacing: '0.05em' }}>0{i+1}</span>
                      <span style={{ fontSize: 'clamp(20px, 2vw, 26px)', fontWeight: 500, letterSpacing: '-0.015em', lineHeight: 1.25 }}>{it.q}</span>
                    </span>
                    <span style={{
                      width: 36, height: 36, borderRadius: 999,
                      border: '1px solid var(--line)',
                      background: isOpen ? 'var(--terra)' : 'transparent',
                      color: isOpen ? 'var(--cream)' : 'var(--ink)',
                      display: 'grid', placeItems: 'center',
                      flexShrink: 0,
                      transition: 'background .2s ease, color .2s ease, transform .3s ease',
                      transform: isOpen ? 'rotate(45deg)' : 'rotate(0)',
                    }}>
                      <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M7 1V13M1 7H13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" /></svg>
                    </span>
                  </button>
                  <div style={{
                    overflow: 'hidden',
                    maxHeight: isOpen ? 240 : 0,
                    transition: 'max-height .4s cubic-bezier(.2,.7,.2,1), opacity .3s ease, padding .3s ease',
                    opacity: isOpen ? 1 : 0,
                    paddingBottom: isOpen ? 28 : 0,
                  }}>
                    <div style={{ paddingLeft: 40, fontFamily: 'Fraunces, serif', fontWeight: 300, fontSize: 19, lineHeight: 1.5, color: 'var(--ink-2)', maxWidth: '60ch', letterSpacing: '-0.005em' }}>
                      {it.a}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 960px) { .faq-grid { grid-template-columns: 1fr !important; gap: 40px !important; } .faq-grid > div:first-child { position: static !important; } }
      `}</style>
    </section>
  );
}

// ---------- Contact ----------
function Contact() {
  const [form, setForm] = useState({ nombre: '', correo: '', mensaje: '' });
  const [errors, setErrors] = useState({});
  const [sent, setSent] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  const validate = () => {
    const e = {};
    if (!form.nombre.trim()) e.nombre = 'Hace falta tu nombre';
    if (!form.correo.trim()) e.correo = 'Falta tu correo';
    else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.correo)) e.correo = 'Ese correo no es válido';
    if (!form.mensaje.trim()) e.mensaje = 'Cuéntanos algo, lo que sea';
    else if (form.mensaje.trim().length < 10) e.mensaje = 'Un poco más, porfa';
    return e;
  };

  const submit = (e) => {
    e.preventDefault();
    const errs = validate();
    setErrors(errs);
    if (Object.keys(errs).length) return;
    setSubmitting(true);
    const subject = encodeURIComponent(`[UzyAgency] Contacto · ${form.nombre.trim()}`);
    const body = encodeURIComponent(
      `Nombre: ${form.nombre.trim()}\nCorreo para responderte: ${form.correo.trim()}\n\n${form.mensaje.trim()}`
    );
    const mailUrl = `mailto:${CONTACT_FORM_EMAIL}?subject=${subject}&body=${body}`;
    setTimeout(() => {
      window.location.href = mailUrl;
      setSubmitting(false);
      setSent(true);
    }, 200);
  };

  return (
    <section id="contacto" style={{ padding: '120px 0 40px' }} className="reveal">
      <div className="container">
        <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 80 }} className="contact-grid">
          <div>
            <span className="eyebrow" style={{ marginBottom: 20, display: 'inline-flex' }}><span className="sq" /> Contacto</span>
            <h2 className="section-h" style={{ marginTop: 16 }}>
              ¿Lo <em>hacemos?</em>
            </h2>
            <p style={{ fontSize: 18, color: 'var(--ink-2)', lineHeight: 1.55, maxWidth: '36ch', marginTop: 24 }}>
              Cuéntanos qué necesitas. Te respondemos en menos de 24h con ideas, referencias y un
              presupuesto honesto. Sin catálogos de 40 páginas.
            </p>

            <div style={{ marginTop: 48, display: 'grid', gap: 24 }}>
              <div>
                <div className="mono" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-3)', marginBottom: 6 }}>Correo directo</div>
                <a href={`mailto:${CONTACT_FORM_EMAIL}`} className="ulink" style={{ fontSize: 22, fontFamily: 'Fraunces, serif', fontStyle: 'italic', fontWeight: 300 }}>{CONTACT_FORM_EMAIL}</a>
              </div>
              <div>
                <div className="mono" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-3)', marginBottom: 6 }}>Otras vías</div>
                <div style={{ display: 'flex', gap: 20, fontSize: 15 }}>
                  <a href={`https://wa.me/${WHATSAPP_E164}`} target="_blank" rel="noopener noreferrer" className="ulink" aria-label="WhatsApp +52 777 493 3883">WhatsApp</a>
                </div>
              </div>
            </div>
          </div>

          <div style={{
            background: 'var(--cream-2)',
            border: '1px solid var(--line)',
            borderRadius: 28,
            padding: 40,
            position: 'relative',
            minHeight: 520,
          }}>
            {sent ? (
              <div style={{ height: '100%', display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 20 }}>
                <div style={{ width: 56, height: 56, borderRadius: 999, background: 'var(--terra)', color: 'var(--cream)', display: 'grid', placeItems: 'center' }}>
                  <svg width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M5 12l5 5 9-11" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>
                </div>
                <div style={{ fontFamily: 'Fraunces, serif', fontSize: 36, fontWeight: 300, letterSpacing: '-0.02em', lineHeight: 1.1 }}>
                  Mensaje recibido,<br/><em>{form.nombre.split(' ')[0] || 'crack'}.</em>
                </div>
                <p style={{ color: 'var(--ink-2)', fontSize: 16, lineHeight: 1.55, maxWidth: '40ch', margin: 0 }}>
                  Debería haberse abierto tu correo con el mensaje listo para enviar a <strong>{CONTACT_FORM_EMAIL}</strong>.
                  Pulsa <strong>Enviar</strong> en esa ventana. Si no se abrió, copia el texto y escríbenos a ese correo.
                  Te respondemos a <strong>{form.correo}</strong> en menos de 24h.
                </p>
                <button onClick={() => { setSent(false); setForm({ nombre: '', correo: '', mensaje: '' }); }} style={{ justifySelf: 'start', alignSelf: 'start', background: 'transparent', border: 'none', color: 'var(--terra-deep)', fontSize: 14, cursor: 'pointer', padding: 0, textDecoration: 'underline', marginTop: 8 }}>Enviar otro</button>
              </div>
            ) : (
              <form onSubmit={submit} style={{ display: 'grid', gap: 28 }} noValidate>
                <div className={`field ${errors.nombre ? 'err' : ''}`}>
                  <label>01 · Tu nombre</label>
                  <input
                    type="text"
                    placeholder="María García"
                    value={form.nombre}
                    onChange={(e) => setForm({ ...form, nombre: e.target.value })}
                  />
                  <div className="hint">{errors.nombre || ''}</div>
                </div>

                <div className={`field ${errors.correo ? 'err' : ''}`}>
                  <label>02 · Correo</label>
                  <input
                    type="email"
                    placeholder="maria@tuempresa.com"
                    value={form.correo}
                    onChange={(e) => setForm({ ...form, correo: e.target.value })}
                  />
                  <div className="hint">{errors.correo || ''}</div>
                </div>

                <div className={`field ${errors.mensaje ? 'err' : ''}`}>
                  <label>03 · Qué necesitas</label>
                  <textarea
                    rows={4}
                    placeholder="Una web para mi estudio, una landing para un lanzamiento, no tengo ni idea pero necesito algo…"
                    value={form.mensaje}
                    onChange={(e) => setForm({ ...form, mensaje: e.target.value })}
                  />
                  <div className="hint">{errors.mensaje || ''}</div>
                </div>

                <button type="submit" className="btn btn-primary" disabled={submitting} style={{ justifySelf: 'start', padding: '18px 28px', fontSize: 16 }}>
                  <span className="dot" />
                  <span>{submitting ? 'Enviando…' : 'Hablemos'}</span>
                  <Arrow />
                </button>
              </form>
            )}
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 960px) { .contact-grid { grid-template-columns: 1fr !important; gap: 40px !important; } }
      `}</style>
    </section>
  );
}

// ---------- Footer ----------
function Footer() {
  return (
    <footer style={{ padding: '80px 0 40px', borderTop: '1px solid var(--line)', marginTop: 40 }}>
      <div className="container">
        <div style={{
          fontFamily: 'DM Sans, sans-serif',
          fontWeight: 500,
          fontSize: 'clamp(80px, 15vw, 240px)',
          letterSpacing: '-0.055em',
          lineHeight: 0.9,
          color: 'var(--ink)',
        }}>
          Uzy<em className="serif" style={{ fontWeight: 300, color: 'var(--terra)' }}>.</em>Agency
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 40, flexWrap: 'wrap', gap: 20 }}>
          <div style={{ fontSize: 13, color: 'var(--ink-3)' }} className="mono">© 2026 UzyAgency · Hecho con cariño · Remoto</div>
          <div style={{ display: 'flex', gap: 24, fontSize: 13 }} className="mono">
            <a href="#" className="ulink">Privacidad</a>
            <a href="#" className="ulink">Cookies</a>
            <a href="#" className="ulink">Aviso legal</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ---------- App ----------
function App() {
  useReveal();
  return (
    <>
      <Nav />
      <Hero />
      <Marquee />
      <Services />
      <Process />
      <FAQ />
      <Contact />
      <Footer />
    </>
  );
}

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