// v2/conversion.jsx — Sticky CTA móvil + Exit-intent popup
const { useState: useStateC, useEffect: useEffectC } = React;

// =====================================================
// Sticky CTA móvil
//   - Solo visible en móvil (CSS)
//   - Aparece al pasar el hero
//   - Se oculta cuando el formulario / CTA final está a la vista
// =====================================================
function V2StickyCTA() {
  const [show, setShow] = useStateC(false);

  useEffectC(() => {
    const onScroll = () => {
      const past = window.scrollY > 700;
      // Ocultar si la sección de contacto o el CTA final están visibles
      let nearForm = false;
      const targets = [document.getElementById('contacto')];
      const finalCta = document.querySelector('[data-screen-label="13 Final CTA"]');
      if (finalCta) targets.push(finalCta);
      for (const el of targets) {
        if (!el) continue;
        const r = el.getBoundingClientRect();
        if (r.top < window.innerHeight * 0.9 && r.bottom > 0) { nearForm = true; break; }
      }
      setShow(past && !nearForm);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
  }, []);

  return (
    <div className={`v-sticky-cta ${show ? 'show' : ''}`}>
      <div className="v-sticky-info">
        <span className="v-sticky-flame">🔥</span>
        <div>
          <div className="v-sticky-t">50% OFF este mes</div>
          <div className="v-sticky-s">Solo quedan 47 cupos</div>
        </div>
      </div>
      <a className="v-btn v-btn-primary" href="#contacto">Empezar gratis →</a>
    </div>
  );
}

// =====================================================
// Exit-intent popup
//   - Desktop: mouse sale por arriba (hacia cerrar/URL)
//   - Móvil: scroll brusco hacia arriba cerca del top
//   - Una vez por sesión
// =====================================================
function V2ExitIntent() {
  const [open, setOpen] = useStateC(false);
  const [done, setDone] = useStateC(false);
  const [email, setEmail] = useStateC('');

  useEffectC(() => {
    if (sessionStorage.getItem('vendi_exit_shown')) return;

    let lastY = window.scrollY;
    let armed = false;
    // Armar después de unos segundos para no disparar al instante
    const armTimer = setTimeout(() => { armed = true; }, 4000);

    const trigger = () => {
      if (!armed) return;
      if (sessionStorage.getItem('vendi_exit_shown')) return;
      sessionStorage.setItem('vendi_exit_shown', '1');
      setOpen(true);
    };

    const onMouseOut = (e) => {
      if (e.clientY <= 0 && !e.relatedTarget) trigger();
    };
    const onScroll = () => {
      const y = window.scrollY;
      // Móvil: scroll rápido hacia arriba cerca del inicio
      if (y < 300 && lastY - y > 60) trigger();
      lastY = y;
    };

    document.addEventListener('mouseout', onMouseOut);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => {
      clearTimeout(armTimer);
      document.removeEventListener('mouseout', onMouseOut);
      window.removeEventListener('scroll', onScroll);
    };
  }, []);

  function close() { setOpen(false); }
  function submit(e) {
    e.preventDefault();
    setDone(true);
  }

  if (!open) return null;

  return (
    <div className="v-exit-overlay" onClick={close}>
      <div className="v-exit-modal" onClick={e => e.stopPropagation()}>
        <button className="v-exit-close" onClick={close} aria-label="Cerrar">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
        </button>

        <div className="v-exit-mesh v-mesh"></div>

        {done ? (
          <div className="v-exit-body" style={{textAlign:'center'}}>
            <div style={{fontSize:48}}>🎉</div>
            <h3 style={{fontSize:26,marginTop:8}}>¡Tu cupón está reservado!</h3>
            <p style={{color:'var(--v-fg-3)',marginTop:12,fontSize:15}}>
              Te enviamos a <strong style={{color:'var(--v-fg)'}}>{email}</strong> el código con tu <strong style={{color:'var(--v-fg)'}}>50% OFF</strong>. Revísalo antes de que se agoten los cupos.
            </p>
            <a className="v-btn v-btn-primary v-btn-lg" href="#contacto" onClick={close} style={{marginTop:24}}>
              Empezar ahora →
            </a>
          </div>
        ) : (
          <div className="v-exit-body">
            <span className="v-urgency-pill warm" style={{margin:'0 auto'}}>
              <span className="pulse-dot"><span></span><span></span></span>
              <span>⏰ Antes de que te vayas…</span>
            </span>
            <h3 style={{fontSize:28,marginTop:18,textAlign:'center'}}>
              No dejes tu <span className="v-gradient-text">50% OFF</span> sobre la mesa
            </h3>
            <p style={{color:'var(--v-fg-3)',marginTop:12,fontSize:15,textAlign:'center'}}>
              Quedan <strong style={{color:'var(--v-fg)'}}>47 cupos</strong> con medio precio los primeros 3 meses. Déjanos tu correo y te guardamos el tuyo ahora mismo.
            </p>
            <form onSubmit={submit} style={{marginTop:22}}>
              <input
                required type="email" value={email} onChange={e=>setEmail(e.target.value)}
                placeholder="tu@correo.com"
                style={{
                  width:'100%', fontSize:15, padding:'14px 16px', borderRadius:12,
                  background:'rgba(255,255,255,0.04)', border:'1px solid var(--v-line-2)',
                  color:'var(--v-fg)', textAlign:'center'
                }}
              />
              <button type="submit" className="v-btn v-btn-primary v-btn-lg" style={{width:'100%',marginTop:12}}>
                Reservar mi 50% OFF →
              </button>
            </form>
            <button onClick={close} style={{
              display:'block', margin:'14px auto 0', background:'none', border:0,
              color:'var(--v-fg-5)', fontSize:13, cursor:'pointer', textDecoration:'underline'
            }}>No gracias, prefiero pagar precio completo</button>
          </div>
        )}
      </div>
    </div>
  );
}

window.V2StickyCTA = V2StickyCTA;
window.V2ExitIntent = V2ExitIntent;
