// exit-popup.jsx — exit-intent modal with device-specific triggers

const ExitPopup = ({ onTriggerForce }) => {
  const [open, setOpen] = React.useState(false);
  const firedRef = React.useRef(false);

  // Detect device once
  const isMobile = React.useMemo(() => {
    if (typeof window === 'undefined') return false;
    return window.matchMedia('(max-width: 820px)').matches
      || ('ontouchstart' in window && window.innerWidth <= 1024);
  }, []);

  const trigger = React.useCallback(() => {
    if (firedRef.current) return;
    if (sessionStorage.getItem('exit_popup_shown') === '1') return;
    firedRef.current = true;
    sessionStorage.setItem('exit_popup_shown', '1');
    setOpen(true);
  }, []);

  // Allow Tweaks panel / external code to force-open for testing
  React.useEffect(() => {
    if (!onTriggerForce) return;
    onTriggerForce(() => {
      firedRef.current = false;
      sessionStorage.removeItem('exit_popup_shown');
      trigger();
    });
  }, [onTriggerForce, trigger]);

  // Desktop trigger: mouse leaves top of viewport, after 8s grace period
  React.useEffect(() => {
    if (isMobile) return;
    let armed = false;
    const armTimer = setTimeout(() => { armed = true; }, 8000);

    const onLeave = (e) => {
      if (!armed) return;
      // Only fire when leaving from the TOP of the viewport
      if (e.clientY <= 0 && e.relatedTarget == null) {
        trigger();
      }
    };
    document.addEventListener('mouseout', onLeave);
    return () => {
      clearTimeout(armTimer);
      document.removeEventListener('mouseout', onLeave);
    };
  }, [isMobile, trigger]);

  // Mobile trigger: scrolled past 60% AND idle (no scroll) for 30s
  React.useEffect(() => {
    if (!isMobile) return;
    let idleTimer = null;
    let pastThreshold = false;

    const checkScroll = () => {
      const scrollY = window.scrollY || window.pageYOffset;
      const docH = document.documentElement.scrollHeight - window.innerHeight;
      if (docH <= 0) return;
      const pct = scrollY / docH;
      pastThreshold = pct >= 0.6;

      // Reset idle timer on every scroll event
      if (idleTimer) clearTimeout(idleTimer);
      if (pastThreshold) {
        idleTimer = setTimeout(() => {
          // Still on page, still past threshold → fire
          trigger();
        }, 30000);
      }
    };

    // Also stop firing if tab becomes hidden (don't fire on a backgrounded tab)
    const onVis = () => {
      if (document.hidden && idleTimer) {
        clearTimeout(idleTimer);
        idleTimer = null;
      } else if (!document.hidden && pastThreshold) {
        // Re-arm when they come back
        if (idleTimer) clearTimeout(idleTimer);
        idleTimer = setTimeout(trigger, 30000);
      }
    };

    window.addEventListener('scroll', checkScroll, { passive: true });
    document.addEventListener('visibilitychange', onVis);
    checkScroll();

    return () => {
      window.removeEventListener('scroll', checkScroll);
      document.removeEventListener('visibilitychange', onVis);
      if (idleTimer) clearTimeout(idleTimer);
    };
  }, [isMobile, trigger]);

  // Lock body scroll when open
  React.useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = prev; };
  }, [open]);

  // Esc to close
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);

  if (!open) return null;

  const handleCta = () => {
    setOpen(false);
    // Smooth-scroll handler will pick this up
    setTimeout(() => {
      const target = document.getElementById('oferta');
      if (target) {
        const y = target.getBoundingClientRect().top + window.scrollY - 72;
        window.scrollTo({ top: Math.max(0, y), behavior: 'smooth' });
      }
    }, 100);
  };

  return (
    <div
      className="exit-popup"
      role="dialog"
      aria-modal="true"
      aria-labelledby="exit-popup-title"
      onClick={(e) => { if (e.target === e.currentTarget) setOpen(false); }}
    >
      <div className="exit-popup__card">
        <button
          className="exit-popup__close"
          onClick={() => setOpen(false)}
          aria-label="Cerrar"
        >
          <svg viewBox="0 0 24 24" fill="none" width="20" height="20" aria-hidden="true">
            <path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>
          </svg>
        </button>

        <div className="exit-popup__alert">
          <svg viewBox="0 0 24 24" fill="none" width="14" height="14" aria-hidden="true">
            <path d="M12 3l10 17H2L12 3z" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round"/>
            <path d="M12 10v4" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>
            <circle cx="12" cy="17" r="0.9" fill="currentColor"/>
          </svg>
          ESPERA UN SEGUNDO
        </div>

        <h2 className="exit-popup__title" id="exit-popup-title">
          Estás a punto de perder<br/>acceso a <em>todo esto</em>:
        </h2>
        <p className="exit-popup__sub">
          Las plazas son limitadas. Una vez cerrado el lote, no reabrimos inscripciones.
        </p>

        <div className="exit-popup__assets">
          <div className="exit-asset">
            <div className="exit-asset__icon" aria-hidden="true">
              <svg viewBox="0 0 24 24" fill="none">
                <circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="1.5"/>
                <path d="M12 3v18M3 12h18" stroke="currentColor" strokeWidth="1.5"/>
              </svg>
            </div>
            <div className="exit-asset__body">
              <div className="exit-asset__title">Método O.P.E.T.™</div>
              <div className="exit-asset__desc">El sistema de 4 fases para crear tu producto digital en 48 horas.</div>
            </div>
          </div>

          <div className="exit-asset">
            <div className="exit-asset__icon" aria-hidden="true">
              <svg viewBox="0 0 24 24" fill="none">
                <rect x="4" y="4" width="16" height="16" rx="3" stroke="currentColor" strokeWidth="1.5"/>
                <circle cx="9" cy="10" r="1.2" fill="currentColor"/>
                <circle cx="15" cy="10" r="1.2" fill="currentColor"/>
                <path d="M8 15c1 1.2 2.4 1.8 4 1.8s3-.6 4-1.8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
                <path d="M12 4V2M5 4l-1.4-1.4M19 4l1.4-1.4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
              </svg>
            </div>
            <div className="exit-asset__body">
              <div className="exit-asset__title">Agentes de IA listos para usar</div>
              <div className="exit-asset__desc">Hacen el trabajo técnico por ti — sin escribir una línea de código.</div>
            </div>
          </div>

          <div className="exit-asset">
            <div className="exit-asset__icon" aria-hidden="true">
              <svg viewBox="0 0 24 24" fill="none">
                <path d="M3 12h4l3-7 4 14 3-7h4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </div>
            <div className="exit-asset__body">
              <div className="exit-asset__title">16h en vivo + grabaciones</div>
              <div className="exit-asset__desc">Acompañamiento paso a paso. Aprendes haciendo, no mirando.</div>
            </div>
          </div>
        </div>

        <div className="exit-popup__urgency">
          <div className="urgency-strip__row">
            <span className="urgency-strip__dot" aria-hidden="true"></span>
            <span className="urgency-strip__text">Lote 1 · <strong>99% ocupado</strong></span>
          </div>
          <div className="loadbar" aria-hidden="true">
            <div className="loadbar__fill"></div>
          </div>
        </div>

        <button className="btn btn--primary btn--xl exit-popup__cta" onClick={handleCta}>
          Quiero asegurar mi plaza <span className="btn-arrow">→</span>
        </button>

        <button
          className="exit-popup__decline"
          onClick={() => setOpen(false)}
        >
          No, prefiero perderlo
        </button>
      </div>
    </div>
  );
};

window.ExitPopup = ExitPopup;
