/* ═══════════════════════════════════════════════════════════
   FLUTUANTES — WhatsApp, sticky CTA (mobile) e exit-intent
   Gatilhos do exit-popup preservados da v1: só aparece depois de
   45s + 35% de rolagem, para não interromper a leitura.
   ═══════════════════════════════════════════════════════════ */

const floatingStyles = {
  waBtn: { position: 'relative' },
};

/* ── Botão flutuante do WhatsApp ─────────────────────────── */
function WhatsAppFloat() {
  const [tip, setTip] = React.useState(false);
  const scrollY = useScrollY();

  // Em telas estreitas o botão fica sobre o texto do hero: só aparece
  // depois que o usuário passa da primeira tela.
  const narrow = typeof window !== 'undefined' && window.innerWidth <= 760;
  const hidden = narrow && scrollY < window.innerHeight * 0.6;

  React.useEffect(() => {
    const show = setTimeout(() => setTip(true), 9000);
    const hide = setTimeout(() => setTip(false), 17000);
    return () => {
      clearTimeout(show);
      clearTimeout(hide);
    };
  }, []);

  return (
    <div className={`wa-float${hidden ? ' hidden' : ''}`}>
      <div className={`wa-tooltip${tip ? ' show' : ''}`}>
        <strong>Fale com a gente agora!</strong>
        <br />
        Tire dúvidas sobre planos ou peça uma demonstração ao vivo.
      </div>
      <a
        href={LINKS.waInfo}
        target="_blank"
        rel="noopener"
        className="btn wa-btn"
        aria-label="Falar no WhatsApp"
        style={floatingStyles.waBtn}
        onMouseEnter={() => setTip(true)}
        onMouseLeave={() => setTip(false)}
      >
        <svg viewBox="0 0 32 32" aria-hidden="true">
          <path d="M16 2C8.27 2 2 8.27 2 16c0 2.44.65 4.73 1.79 6.71L2 30l7.53-1.75A13.9 13.9 0 0 0 16 30c7.73 0 14-6.27 14-14S23.73 2 16 2zm0 25.5c-2.2 0-4.26-.6-6.03-1.64l-.43-.26-4.47 1.04 1.07-4.35-.28-.45A11.44 11.44 0 0 1 4.5 16C4.5 9.6 9.6 4.5 16 4.5S27.5 9.6 27.5 16 22.4 27.5 16 27.5zm6.3-8.54c-.34-.17-2.02-1-2.34-1.11-.32-.11-.55-.17-.78.17-.23.34-.9 1.11-1.1 1.34-.2.23-.4.26-.74.09-.34-.17-1.44-.53-2.74-1.69-1.01-.9-1.7-2.01-1.9-2.35-.2-.34-.02-.52.15-.69.15-.15.34-.4.51-.6.17-.2.23-.34.34-.57.11-.23.06-.43-.03-.6-.08-.17-.78-1.88-1.07-2.57-.28-.67-.57-.58-.78-.59h-.67c-.23 0-.6.09-.91.43-.32.34-1.21 1.18-1.21 2.88s1.24 3.34 1.41 3.57c.17.23 2.44 3.73 5.91 5.23.83.36 1.47.57 1.97.73.83.26 1.58.22 2.18.13.66-.1 2.02-.83 2.31-1.63.28-.8.28-1.49.2-1.63-.09-.15-.32-.23-.67-.4z" />
        </svg>
        <span className="wa-badge" aria-hidden="true">
          1
        </span>
      </a>
    </div>
  );
}

/* ── Barra fixa de CTA no mobile ─────────────────────────── */
function StickyCTA() {
  const scrollY = useScrollY();
  const show = scrollY > 700;

  return (
    <div className={`sticky-cta${show ? ' show' : ''}`}>
      <div className="sticky-cta-text">
        <strong>15 dias grátis</strong>
        <span>Sem cartão de crédito</span>
      </div>
      <a href={LINKS.cadastro} className="btn btn-primary">
        Começar grátis
      </a>
    </div>
  );
}

/* sessionStorage lança em file://, Safari privado e quando cookies de
   terceiros estão bloqueados — nunca acessar sem proteção. */
const memoryStore = {};

function safeStorage(key, value) {
  try {
    if (value === undefined) return window.sessionStorage.getItem(key);
    window.sessionStorage.setItem(key, value);
    return value;
  } catch (e) {
    if (value === undefined) return memoryStore[key] || null;
    memoryStore[key] = value;
    return value;
  }
}

/* ── Exit-intent ─────────────────────────────────────────── */
function ExitPopup() {
  const [open, setOpen] = React.useState(false);
  const doneRef = React.useRef(false);

  React.useEffect(() => {
    if (safeStorage('klyvo-exit-seen')) {
      doneRef.current = true;
      return;
    }

    let elapsed = false;
    const timer = setTimeout(() => {
      elapsed = true;
    }, 45000);

    const scrolledEnough = () => {
      const max = document.body.scrollHeight - window.innerHeight;
      return max > 0 && window.scrollY / max > 0.35;
    };

    const trigger = () => {
      if (doneRef.current || !elapsed || !scrolledEnough()) return;
      doneRef.current = true;
      safeStorage('klyvo-exit-seen', '1');
      setOpen(true);
    };

    // Desktop: mouse sai pelo topo da viewport
    const onLeave = (e) => {
      if (e.clientY <= 0) trigger();
    };

    // Mobile: usuário volta rapidamente ao topo (sem gatilho de inatividade)
    let lastY = window.scrollY;
    const onScroll = () => {
      const y = window.scrollY;
      if (lastY - y > 260 && y < 420) trigger();
      lastY = y;
    };

    document.addEventListener('mouseout', onLeave);
    window.addEventListener('scroll', onScroll, { passive: true });

    return () => {
      clearTimeout(timer);
      document.removeEventListener('mouseout', onLeave);
      window.removeEventListener('scroll', onScroll);
    };
  }, []);

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

  const close = () => setOpen(false);

  return (
    <div
      className={`exit-overlay${open ? ' show' : ''}`}
      role="dialog"
      aria-modal="true"
      aria-label="Oferta especial"
      aria-hidden={!open}
      onClick={(e) => e.target === e.currentTarget && close()}
    >
      <div className="exit-modal">
        <button className="exit-close" onClick={close} aria-label="Fechar">
          ✕
        </button>

        <div className="exit-mark">
          <Icon d={ICONS.tooth} fill="currentColor" strokeWidth={0} />
        </div>

        <h3>Antes de sair…</h3>
        <p>
          Você ainda não testou o Klyvo. São 15 dias grátis, sem cartão e sem compromisso — dá pra
          ver tudo funcionando na sua rotina hoje mesmo.
        </p>

        <div className="exit-offer">
          <strong>Feito por quem atende</strong>
          O Klyvo foi fundado por uma equipe de dentistas. Cada módulo nasceu de um problema real de
          consultório — não de um manual de software.
        </div>

        <a href={LINKS.cadastro} className="btn btn-primary btn-lg btn-block" onClick={close}>
          Começar meus 15 dias grátis →
        </a>
        <p className="exit-dismiss" onClick={close}>
          Agora não
        </p>
      </div>
    </div>
  );
}

Object.assign(window, { WhatsAppFloat, StickyCTA, ExitPopup });
