/* global React, Icon, WAButton, CallButton, waLink */
const { useState, useEffect, useRef } = React;

// ============================================================
// WhatsApp floating button
// ============================================================
function WAFloat() {
  return (
    <a className="wa-float" href={waLink("Olá! Preciso de atendimento urgente.")} target="_blank" rel="noopener" aria-label="WhatsApp">
      <Icon.WA />
    </a>
  );
}

// ============================================================
// Sticky mobile bar
// ============================================================
function StickyMobile() {
  return (
    <div className="sticky-mobile">
      <a className="btn btn-wa" href={waLink("Olá! Preciso de atendimento urgente.")} target="_blank" rel="noopener">
        <Icon.WA /> WhatsApp
      </a>
      <a className="btn btn-urgent" href="tel:+5562992910049">
        <Icon.Phone /> Ligar
      </a>
    </div>
  );
}

// ============================================================
// Realtime fake notifications (toasts)
// ============================================================
function RealtimeToasts({ enabled = true }) {
  const events = useRef([
    { who: "João R.", where: "Setor Bueno", what: "acabou de chamar para vaso sanitário", time: "agora" },
    { who: "Síndica M.", where: "Edifício Aurora", what: "agendou hidrojateamento", time: "há 12 min" },
    { who: "Marcelo F.", where: "Aparecida", what: "solicitou orçamento de caixa de gordura", time: "há 28 min" },
    { who: "Patrícia A.", where: "Jardim Goiás", what: "abriu chamado de esgoto entupido", time: "há 45 min" },
    { who: "Restaurante Sul", where: "Trindade", what: "renovou contrato preventivo", time: "há 1h" },
  ]).current;
  const [idx, setIdx] = useState(-1);
  const [out, setOut] = useState(false);

  useEffect(() => {
    if (!enabled) return;
    let i = Math.floor(Math.random() * events.length);
    let mounted = true;
    let timers = [];
    // Random delays — first toast shows up after a longer gap (services, not products)
    const firstDelay = 18000 + Math.random() * 22000; // 18–40s
    function cycle() {
      if (!mounted) return;
      setOut(false);
      setIdx(i % events.length);
      const visibleFor = 5500 + Math.random() * 2000; // 5.5–7.5s
      timers.push(setTimeout(() => setOut(true), visibleFor));
      timers.push(setTimeout(() => {
        if (!mounted) return;
        setIdx(-1);
        i = (i + 1 + Math.floor(Math.random() * 2)) % events.length;
        const gap = 35000 + Math.random() * 55000; // 35–90s between toasts
        timers.push(setTimeout(cycle, gap));
      }, visibleFor + 500));
    }
    timers.push(setTimeout(cycle, firstDelay));
    return () => { mounted = false; timers.forEach(clearTimeout); };
  }, [enabled, events.length]);

  if (idx < 0) return null;
  const e = events[idx];
  return (
    <div className={`toast ${out ? "out" : ""}`} role="status">
      <div className="av"><Icon.WA /></div>
      <div>
        <div><b>{e.who}</b> em {e.where}</div>
        <div>{e.what}</div>
        <div className="time">{e.time}</div>
      </div>
    </div>
  );
}

// ============================================================
// Exit intent popup
// ============================================================
function ExitPopup({ enabled = true }) {
  const [open, setOpen] = useState(false);
  const fired = useRef(false);

  useEffect(() => {
    if (!enabled) return;
    function onLeave(e) {
      if (fired.current) return;
      if (e.clientY < 10) {
        fired.current = true;
        setOpen(true);
      }
    }
    // Also fire after 30s of inactivity scroll as a backup
    const backup = setTimeout(() => {
      if (!fired.current) { fired.current = true; setOpen(true); }
    }, 45000);
    document.addEventListener("mouseleave", onLeave);
    return () => {
      document.removeEventListener("mouseleave", onLeave);
      clearTimeout(backup);
    };
  }, [enabled]);

  return (
    <div className="exit-popup" aria-hidden={!open} style={{ display: open ? "" : "none" }} onClick={() => setOpen(false)}>
      <div className="exit-popup-card" onClick={e => e.stopPropagation()}>
        <button className="close" onClick={() => setOpen(false)}><Icon.X style={{width:14,height:14}}/></button>
        <div className="eyebrow"><span className="dot" style={{background:'var(--urgent)'}} />ESPERA — ROTA AINDA ABERTA</div>
        <h3>Última chamada da rota de hoje.</h3>
        <p>Ainda temos equipes disponíveis na sua região agora. Toque abaixo e fale direto com o atendimento prioritário.</p>
        <a className="btn btn-urgent btn-lg" href={waLink("Olá! Vi o aviso no site, quero atendimento prioritário.")} target="_blank" rel="noopener">
          <Icon.WA /> CHAMAR EQUIPE AGORA
        </a>
        <div style={{marginTop: 14, fontFamily:'var(--mono)', fontSize: 11, color: 'var(--ink-3)', letterSpacing:'0.14em', textTransform:'uppercase'}}>
          Ou ligue: (62) 99291-0049
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { WAFloat, StickyMobile, RealtimeToasts, ExitPopup });
