// Exit-intent modal — pra quem vai sair sem agendar. Oferece WhatsApp (íntimo) como ponte.
// Triggers: desktop = mouse sai pelo topo · mobile = scroll-up rápido após 20s.
// Anti-spam: 1x por sessão (sessionStorage), só dispara após 15s na página.
function ExitIntent() {
  const [open, setOpen] = React.useState(false);
  const [closing, setClosing] = React.useState(false);
  const fired = React.useRef(false);

  const dismiss = React.useCallback(() => {
    setClosing(true);
    setTimeout(() => { setOpen(false); setClosing(false); }, 250);
  }, []);

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

  React.useEffect(() => {
    // só ativa depois de 15s na página (evita disparo precoce)
    const armTimer = setTimeout(() => {
      // Desktop: mouseleave pelo topo
      const onLeave = (e) => {
        if (e.clientY <= 0 && (!e.relatedTarget && !e.toElement)) trigger();
      };
      // Mobile: scroll-up rápido (>40px em <300ms) após chegar bem no topo
      let lastY = window.scrollY, lastT = Date.now();
      const onScroll = () => {
        const y = window.scrollY, t = Date.now();
        if (y < 80 && lastY - y > 40 && t - lastT < 300) trigger();
        lastY = y; lastT = t;
      };
      // Esc fecha
      const onKey = (e) => { if (e.key === 'Escape') dismiss(); };
      document.addEventListener('mouseout', onLeave);
      window.addEventListener('scroll', onScroll, { passive: true });
      document.addEventListener('keydown', onKey);
      return () => {
        document.removeEventListener('mouseout', onLeave);
        window.removeEventListener('scroll', onScroll);
        document.removeEventListener('keydown', onKey);
      };
    }, 15000);
    return () => clearTimeout(armTimer);
  }, [trigger, dismiss]);

  if (!open) return null;

  return (
    <div onClick={dismiss} style={{
      position: 'fixed', inset: 0, zIndex: 60, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
      background: 'rgba(15, 23, 21, .55)', backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
      animation: closing ? 'mfFadeOut .25s var(--ease-out) forwards' : 'mfFadeIn .35s var(--ease-out)',
    }}>
      <div onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" aria-labelledby="mf-exit-title" style={{
        position: 'relative', maxWidth: 480, width: '100%', background: '#fff',
        borderRadius: 'var(--r-2xl)', padding: '40px 36px 32px', boxShadow: 'var(--shadow-lg)',
        animation: closing ? 'mfPopOut .25s var(--ease-out) forwards' : 'mfPopIn .45s var(--ease-out)',
      }}>
        <button onClick={dismiss} aria-label="Fechar" style={{
          position: 'absolute', top: 14, right: 14, width: 34, height: 34, borderRadius: 999, border: '1px solid var(--line)',
          background: 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" style={{ stroke: 'var(--muted)' }} strokeWidth="2" strokeLinecap="round"><path d="M18 6 6 18M6 6l12 12" /></svg>
        </button>

        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 18 }}>
          <img src="logo-mf-symbol-sm.png" alt="" style={{ display: 'block', height: 56, width: 'auto' }} />
        </div>

        <h2 id="mf-exit-title" style={{
          fontFamily: 'var(--font-display)', fontSize: 'clamp(24px, 4vw, 30px)', fontWeight: 500, lineHeight: 1.2,
          letterSpacing: '-.015em', color: 'var(--ink-2)', textAlign: 'center', margin: 0,
        }}>
          Tá com dúvida? <span style={{ fontStyle: 'italic', color: 'var(--brand)' }}>Conversa primeiro.</span>
        </h2>
        <p style={{ fontSize: 15.5, lineHeight: 1.6, color: 'var(--muted)', textAlign: 'center', margin: '14px 0 26px', maxWidth: '34ch', marginLeft: 'auto', marginRight: 'auto' }}>
          Antes de marcar uma sessão, manda uma mensagem. Tira qualquer dúvida, sem compromisso — eu respondo pessoalmente.
        </p>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <a href={window.WHATSAPP} target="_blank" rel="noopener" onClick={dismiss} className="btn btn-wa btn-lg" style={{ justifyContent: 'center', width: '100%' }}>
            <Icon name="whatsapp" size={18} color="#fff" /> Conversar pelo WhatsApp
          </a>
          <a href={window.DOCTORALIA} target="_blank" rel="noopener" onClick={dismiss} className="btn btn-ghost" style={{ justifyContent: 'center', width: '100%' }}>
            <Icon name="calendar" size={16} /> Prefiro agendar direto pelo Doctoralia
          </a>
        </div>

        <p style={{ fontSize: 12, color: 'var(--muted)', textAlign: 'center', marginTop: 18 }}>
          Sigilo profissional garantido · CRP 08/11383
        </p>
      </div>

      <style>{`
        @keyframes mfFadeIn { from{opacity:0} to{opacity:1} }
        @keyframes mfFadeOut { from{opacity:1} to{opacity:0} }
        @keyframes mfPopIn { from{opacity:0;transform:translateY(20px) scale(.95)} to{opacity:1;transform:none} }
        @keyframes mfPopOut { from{opacity:1;transform:none} to{opacity:0;transform:translateY(10px) scale(.97)} }
      `}</style>
    </div>
  );
}

window.ExitIntent = ExitIntent;
