/* ══════════════════════════════════════════════════
   LAYOUT — page chrome: navbar and the floating CTA.
══════════════════════════════════════════════════ */

/* Hover lives in CSS (.wa-fab), not in onMouseEnter: a touch browser
   fires the enter handler on tap and never fires leave, which left the
   button stuck at scale(1.1) after every visit to WhatsApp. */
const FloatingWA = () => (
  <a href={WA_URL} target="_blank" rel="noopener noreferrer" aria-label="Falar no WhatsApp" className="wa-fab"
     style={{ position:'fixed', zIndex:9000, width:56, height:56, borderRadius:'50%',
              background:T.wa, color:'#fff', display:'flex', alignItems:'center', justifyContent:'center',
              boxShadow:'0 6px 20px rgba(37,211,102,.42)', textDecoration:'none',
              animation:'waPulse 2.4s ease-out infinite' }}>
    <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none"
         stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/>
    </svg>
  </a>
);

const Ham = ({ open }) => (
  <div style={{ width:24, height:18, position:'relative', cursor:'pointer' }}>
    {[{top:open?'50%':0,mt:open?-1:0,rot:open?45:0},
      {top:'50%',mt:-1,rot:0,hide:open},
      {top:open?'50%':'100%',mt:open?-1:-2,rot:open?-45:0}].map((s,i)=>(
      <span key={i} style={{ display:'block', width:'100%', height:2, background:T.ink, borderRadius:2,
                             position:'absolute', top:s.top, marginTop:s.mt, transform:`rotate(${s.rot}deg)`,
                             opacity:s.hide?0:1, transition:'all .3s cubic-bezier(.16,1,.3,1)' }}/>
    ))}
  </div>
);

/* Reused by the navbar and the mobile menu. */
const WhatsAppLink = ({ sz = 15, fontSize = 14, onClick }) => (
  <a href={WA_URL} target="_blank" rel="noopener noreferrer" onClick={onClick} className="wa-link"
     style={{ color:T.wa, textDecoration:'none', fontSize, fontWeight:700,
              display:'inline-flex', alignItems:'center', gap:7, transition:'opacity .18s',
              minHeight:44 }}>
    <WAIco sz={sz}/> Fale Conosco
  </a>
);

/* One link per chapter worth jumping to — not one per section. */
const NAV_LINKS = [
  ['Como funciona','#fluxo'], ['Rastreamento','#rastreamento'], ['Evidências','#evidencia'],
  ['Operação','#operacao'], ['Demonstração','#video'],
];

const Navbar = ({ onDemo }) => {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const fn = () => setScrolled(window.scrollY > 28);
    window.addEventListener('scroll', fn);
    return () => window.removeEventListener('scroll', fn);
  }, []);

  /* While the menu is open the page behind it must not scroll — otherwise
     a swipe on the overlay drags the page and the menu ends up floating
     over the middle of the document. Escape closes it for keyboards; the
     scrim below closes it for thumbs. */
  useEffect(() => {
    if (!open) return;
    document.body.classList.add('menu-open');
    const esc = e => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', esc);
    return () => { document.body.classList.remove('menu-open'); window.removeEventListener('keydown', esc); };
  }, [open]);

  /* A viewport that crosses back into desktop with the menu still open
     would leave the overlay stranded on top of the full nav. */
  useEffect(() => {
    const mq = window.matchMedia('(min-width: 1025px)');
    const fn = e => { if (e.matches) setOpen(false); };
    mq.addEventListener('change', fn);
    return () => mq.removeEventListener('change', fn);
  }, []);

  const solid = scrolled || open;
  return (
    <>
      <nav className="nav-shell"
           style={{ position:'fixed', top:0, left:0, right:0, zIndex:999,
                    background: solid ? 'rgba(251,247,241,.88)' : 'transparent',
                    backdropFilter: solid ? 'blur(18px)' : 'none',
                    WebkitBackdropFilter: solid ? 'blur(18px)' : 'none',
                    borderBottom: solid ? `1px solid ${T.line}` : '1px solid transparent',
                    transition:'background .35s ease, border-color .35s ease' }}>
        <div className="nav-inner" style={{ maxWidth:1180, margin:'0 auto', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <a href="#hero" aria-label="Início" style={{ display:'flex', alignItems:'center', minHeight:44 }}>
            <img src={IMAGES.logo} alt="entregga" className="logo-ink" style={{ height:32, objectFit:'contain' }}/>
          </a>
          <div className="nav-links" style={{ display:'flex', gap:30, alignItems:'center' }}>
            {NAV_LINKS.map(([lbl,href])=><a key={lbl} href={href} className="nav-lnk">{lbl}</a>)}
            <WhatsAppLink/>
          </div>
          <button className="nav-toggle" onClick={()=>setOpen(o=>!o)}
                  aria-label="Menu" aria-expanded={open} aria-controls="nav-menu"
                  style={{ background:'none', border:'none', padding:0, cursor:'pointer', display:'none',
                           alignItems:'center', justifyContent:'center' }}>
            <Ham open={open}/>
          </button>
        </div>
      </nav>

      {open && <div className="nav-scrim" aria-hidden="true" onClick={()=>setOpen(false)}/>}

      {open && (
        <div id="nav-menu" className="nav-menu"
             style={{ position:'fixed', left:0, right:0, zIndex:998, background:'rgba(251,247,241,.98)',
                      backdropFilter:'blur(18px)', WebkitBackdropFilter:'blur(18px)',
                      paddingLeft:'var(--sec-pad-x)', paddingRight:'var(--sec-pad-x)', paddingTop:14,
                      borderBottom:`1px solid ${T.line}`, animation:'menuSlide .3s cubic-bezier(.16,1,.3,1)' }}>
          {NAV_LINKS.map(([lbl,href],i)=>(
            <a key={lbl} href={href} onClick={()=>setOpen(false)}
               style={{ display:'flex', alignItems:'center', minHeight:52, color:T.ink, textDecoration:'none',
                        fontSize:16.5, fontWeight:600, borderBottom:`1px solid ${T.line}`,
                        animation:`menuItemIn .4s ease ${i*.06}s both` }}>{lbl}</a>
          ))}
          <div style={{ borderBottom:`1px solid ${T.line}`, display:'flex', alignItems:'center', minHeight:52 }}>
            <WhatsAppLink sz={18} fontSize={16.5} onClick={()=>setOpen(false)}/>
          </div>
          <button className="btn-brand btn-shine" onClick={()=>{ setOpen(false); onDemo(); }}
                  style={{ width:'100%', padding:'16px', borderRadius:T.rBtn, fontSize:16, marginTop:18 }}>
            Falar com especialista
          </button>
        </div>
      )}
    </>
  );
};
