// === LIMPMIL — Overlays: WhatsApp float, sticky mobile, fake notifs, exit popup ===

function WAFloat() {
  return (
    <a className="wa-float pht-whatsapp" data-widget="3395" href={buildWA()} target="_blank" rel="noopener" onClick={() => waClick("float_widget")}>
      <span className="wa-float-icon">💬</span>
      <span className="wa-float-text">
        <span>Falar no WhatsApp</span>
        <small>Atendimento 24h · resposta em 2 min</small>
      </span>
    </a>
  );
}

function StickyMobileBar() {
  return (
    <div className="sticky-mobile">
      <a className="btn btn-primary" href={`tel:+${COMPANY.phoneDigits}`} onClick={() => trackEvent("phone_click", { source: "sticky_mobile" })}>
        <span>📞</span> Ligar
      </a>
      <a className="btn btn-whatsapp pht-whatsapp" data-widget="3395" href={buildWA()} target="_blank" rel="noopener" onClick={() => waClick("sticky_mobile")}>
        <span>💬</span> WhatsApp
      </a>
    </div>
  );
}

const FAKE_NOTIFS = [
  { name: "Ricardo S.", initials: "RS", place: "Jardim América", service: "desentupimento de pia" },
  { name: "Mariana L.", initials: "ML", place: "Setor Bueno", service: "limpeza de caixa de gordura" },
  { name: "Anderson P.", initials: "AP", place: "Flamboyant", service: "desentupimento de esgoto" },
  { name: "Júlia R.", initials: "JR", place: "Setor Oeste", service: "desentupimento de vaso" },
  { name: "Bruno C.", initials: "BC", place: "Jardim Goiás", service: "hidrojateamento" },
  { name: "Camila F.", initials: "CF", place: "Aparecida de Goiânia", service: "desobstrução de ralo" },
  { name: "Pedro M.", initials: "PM", place: "Eldorado", service: "limpa fossa" },
  { name: "Fernanda V.", initials: "FV", place: "Setor Marista", service: "desentupimento residencial" },
];

function FakeNotifs() {
  const [current, setCurrent] = React.useState(null);
  const [idx, setIdx] = React.useState(0);
  const [exit, setExit] = React.useState(false);

  React.useEffect(() => {
    let timeout;
    // Visible time: 9-13s, then a longer random gap (25-55s) before the next one.
    const visibleMs = 9000 + Math.random() * 4000;
    const gapMs = 25000 + Math.random() * 30000;
    const firstDelay = idx === 0 ? 18000 + Math.random() * 12000 : gapMs;

    const cycle = () => {
      setExit(false);
      setCurrent(FAKE_NOTIFS[idx % FAKE_NOTIFS.length]);
      timeout = setTimeout(() => {
        setExit(true);
        timeout = setTimeout(() => {
          setCurrent(null);
          setIdx(i => i + 1);
        }, 400);
      }, visibleMs);
    };
    const start = setTimeout(cycle, firstDelay);
    return () => { clearTimeout(start); clearTimeout(timeout); };
  }, [idx]);

  if (!current) return null;
  return (
    <a className={`notif-toast ${exit ? "exit" : ""}`} href={buildWA()} target="_blank" rel="noopener" onClick={() => waClick("fake_notif")}>
      <div className="notif-icon">{current.initials}</div>
      <div className="notif-text">
        <strong>{current.name}</strong> no <strong>{current.place}</strong> acabou de solicitar {current.service}
        <small>há instantes · via WhatsApp</small>
      </div>
      <button className="notif-close" onClick={(e) => { e.preventDefault(); e.stopPropagation(); setExit(true); setTimeout(() => setCurrent(null), 350); }}>×</button>
    </a>
  );
}

function ExitIntent() {
  const [open, setOpen] = React.useState(false);
  const triggered = React.useRef(false);

  React.useEffect(() => {
    function onLeave(e) {
      if (triggered.current) return;
      if (e.clientY <= 0) {
        triggered.current = true;
        setOpen(true);
        trackEvent("exit_intent_shown", { trigger: "mouse_leave" });
      }
    }
    // Fallback: show after 60s if not triggered on mobile
    const t = setTimeout(() => {
      if (!triggered.current && window.innerWidth < 900) {
        triggered.current = true;
        setOpen(true);
        trackEvent("exit_intent_shown", { trigger: "mobile_timeout" });
      }
    }, 60000);
    document.addEventListener("mouseleave", onLeave);
    return () => { document.removeEventListener("mouseleave", onLeave); clearTimeout(t); };
  }, []);

  return (
    <div className="modal-backdrop" aria-hidden={!open} style={{ display: open ? "" : "none" }} onClick={() => setOpen(false)}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={() => setOpen(false)}>×</button>
        <div className="modal-head">
          <div className="modal-head-inner">
            <span className="modal-eyebrow">⚡ Antes de você ir embora</span>
            <h3>Cupom exclusivo de 10% para sua primeira chamada</h3>
            <p>Mostre o código no WhatsApp e ganhe desconto no orçamento.</p>
          </div>
        </div>
        <div className="modal-body">
          <div className="coupon">
            <div className="coupon-label">SEU CUPOM</div>
            <div className="coupon-code">PRIMEIRA10</div>
            <div className="coupon-discount">10% de desconto · válido só hoje</div>
          </div>
          <a
            className="btn btn-whatsapp btn-large"
            href={buildWA("Olá! Quero usar o cupom PRIMEIRA10 para meu primeiro atendimento.")}
            target="_blank"
            rel="noopener"
            onClick={() => { trackEvent("coupon_redeem", { code: "PRIMEIRA10" }); waClick("exit_intent_coupon"); setOpen(false); }}
          >
            <span>💬</span> Resgatar cupom no WhatsApp
          </a>
          <p style={{ textAlign: "center", marginTop: 12, fontSize: 12, color: "var(--ink-soft)" }}>
            Sem taxa de visita · Resposta em até 2 minutos
          </p>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { WAFloat, StickyMobileBar, FakeNotifs, ExitIntent });
