// Nav + Cart drawer + Login modal

function CartThumb({ image, cat, hue }) {
  const [err, setErr] = useState(false);
  const src = image;
  if (src && !err) {
    return (
      <img
        src={src}
        alt=""
        onError={() => setErr(true)}
        style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
      />
    );
  }
  return <JewelArt cat={cat} hue={hue} tone="soft" />;
}

function Nav({ onSearch, onLogin, announcement = 'default', visibleCategories }) {
  const cart = useCart();
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const ALL_LINKS = [
    { label: 'Brincos',   href: 'categoria.html?cat=brincos' },
    { label: 'Colares',   href: 'categoria.html?cat=colares' },
    { label: 'Pulseiras', href: 'categoria.html?cat=pulseiras' },
    { label: 'Chokers',   href: 'categoria.html?cat=chokers' },
  ];
  const visible = Array.isArray(visibleCategories) ? visibleCategories : null;
  const links = visible
    ? ALL_LINKS.filter(l => visible.includes(l.label))
    : ALL_LINKS;

  return (
    <>
      {/* Announcement bar */}
      {announcement === 'namorados' ? (
        <ValentinesStrip/>
      ) : announcement === 'maes' ? (
        <MaesStrip/>
      ) : (
        <div style={{
          background: 'var(--grad-deep)', color: 'white', textAlign: 'center',
          fontSize: 12, letterSpacing: '0.06em', padding: '8px 12px',
          fontFamily: 'var(--mono)',
        }}>
          FEITO À MÃO EM SALVADOR · BAHIA · GARANTIA 90 DIAS · PARCELE EM 6X
        </div>
      )}

      <header style={{
        position: 'sticky', top: 0, zIndex: 40,
        background: scrolled ? 'rgba(255,255,255,0.85)' : 'white',
        backdropFilter: scrolled ? 'saturate(160%) blur(14px)' : 'none',
        borderBottom: '1px solid ' + (scrolled ? 'var(--line)' : 'transparent'),
        transition: 'all .25s ease',
      }}>
        <div className="container" style={{
          display: 'grid',
          gridTemplateColumns: 'auto 1fr auto',
          alignItems: 'center',
          gap: 24,
          height: 76,
        }}>
          <a href="/" aria-label="Lua Azul" onClick={(e) => {
            // Se já está na home, evita reload e leva pro topo absoluto.
            if (location.pathname === '/' || location.pathname.endsWith('/index.html')) {
              e.preventDefault();
              window.scrollTo({ top: 0, behavior: 'smooth' });
              if (location.hash) history.replaceState(null, '', location.pathname + location.search);
            }
          }}>
            <Logo size={22} />
          </a>

          <nav style={{ display: 'flex', gap: 28, justifyContent: 'center' }} className="nav-links">
            {links.map(l => (
              <a key={l.label} href={l.href}
                style={{ fontSize: 14, color: 'var(--ink-2)', position: 'relative' }}
                onMouseEnter={(e)=> e.currentTarget.style.color = 'var(--blue-600)'}
                onMouseLeave={(e)=> e.currentTarget.style.color = 'var(--ink-2)'}>
                {l.label}
              </a>
            ))}
          </nav>

          <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            <IconBtn label="Buscar" onClick={()=> { setSearchOpen(true); if(onSearch) onSearch(); }}><Icon name="search" /></IconBtn>
            <IconBtn label="Conta" onClick={onLogin}><Icon name="user" /></IconBtn>
            <IconBtn label="Favoritos"><Icon name="heart" /></IconBtn>
            <IconBtn label="Sacola" onClick={()=> cart.setOpen(true)}>
              <span style={{ position: 'relative' }}>
                <Icon name="bag" />
                {cart.count > 0 && (
                  <span style={{
                    position: 'absolute', top: -6, right: -8,
                    background: 'var(--grad)', color: 'white',
                    fontSize: 10, fontWeight: 600,
                    minWidth: 18, height: 18, borderRadius: 10,
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    padding: '0 5px',
                  }}>{cart.count}</span>
                )}
              </span>
            </IconBtn>
            <IconBtn label="Menu" className="only-mobile" onClick={()=> setMobileOpen(true)}>
              <Icon name="menu" />
            </IconBtn>
          </div>
        </div>
      </header>

      {/* Cart flash */}
      {cart.flash && (
        <div style={{
          position: 'fixed', top: 96, right: 24, zIndex: 60,
          background: 'white', border: '1px solid var(--line)',
          borderRadius: 14, padding: '12px 16px',
          boxShadow: '0 16px 40px -12px rgba(8, 51, 68, 0.18)',
          display: 'flex', alignItems: 'center', gap: 10,
          animation: 'fadeUp .3s ease',
        }}>
          <span style={{
            width: 28, height: 28, borderRadius: '50%',
            background: 'var(--grad)', color: 'white',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          }}><Icon name="check" size={16} /></span>
          <div>
            <div style={{ fontSize: 13, fontWeight: 500 }}>Adicionado à sacola</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{cart.flash}</div>
          </div>
        </div>
      )}

      <SearchModal open={searchOpen} onClose={()=> setSearchOpen(false)} />
      <CartDrawer />
      <MobileDrawer open={mobileOpen} onClose={()=> setMobileOpen(false)} onLogin={onLogin} links={links} onCart={()=> cart.setOpen(true)}/>
    </>
  );
}

function MobileDrawer({ open, onClose, onLogin, links, onCart }) {
  return (
    <>
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, zIndex: 95,
        background: 'rgba(8,51,68,0.4)', backdropFilter: 'blur(4px)',
        opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none',
        transition: 'opacity .25s ease',
      }}/>
      <div style={{
        position: 'fixed', top: 0, right: 0, bottom: 0, zIndex: 96,
        width: 'min(320px, 88vw)',
        background: 'white',
        transform: open ? 'translateX(0)' : 'translateX(110%)',
        transition: 'transform .3s cubic-bezier(.2,.7,.2,1)',
        display: 'flex', flexDirection: 'column',
        boxShadow: '-20px 0 60px -20px rgba(8,51,68,0.3)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '20px 24px', borderBottom: '1px solid var(--line)' }}>
          <Logo size={20}/>
          <button onClick={onClose} aria-label="Fechar menu" style={{
            background: 'var(--blue-50)', border: 'none', cursor: 'pointer',
            width: 36, height: 36, borderRadius: 10, color: 'var(--ink)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name="close" size={18}/>
          </button>
        </div>

        <nav style={{ flex: 1, padding: '8px 16px', overflowY: 'auto' }}>
          {links.map(l => (
            <a key={l.label} href={l.href} onClick={onClose} style={{
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              padding: '14px 8px',
              borderBottom: '1px solid var(--line)',
              fontSize: 15, fontWeight: 500, color: 'var(--ink)',
              textDecoration: 'none',
            }}>
              {l.label}
              <span style={{ color: 'var(--ink-3)', display: 'inline-flex' }}>
                <Icon name="arrow" size={14}/>
              </span>
            </a>
          ))}
        </nav>

        <div style={{ padding: '16px 20px', display: 'flex', flexDirection: 'column', gap: 10, borderTop: '1px solid var(--line)' }}>
          <button onClick={()=> { onLogin(); onClose(); }} className="btn btn-ghost" style={{ width: '100%', height: 46 }}>
            <Icon name="user" size={16}/> Minha conta
          </button>
          <button onClick={()=> { onCart(); onClose(); }} className="btn btn-ghost" style={{ width: '100%', height: 46 }}>
            <Icon name="bag" size={16}/> Sacola
          </button>
          <a href="https://wa.me/5571999181376" target="_blank" rel="noreferrer" style={{
            height: 46, borderRadius: 999,
            background: 'linear-gradient(135deg, #25d366, #128c7e)',
            color: 'white', textDecoration: 'none', fontSize: 14, fontWeight: 500,
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          }}>
            <Icon name="whatsapp" size={18}/> Atendimento WhatsApp
          </a>
        </div>
      </div>
    </>
  );
}

function IconBtn({ children, label, onClick, className = '' }) {
  return (
    <button onClick={onClick} aria-label={label} className={className}
      style={{
        width: 40, height: 40, borderRadius: 12,
        background: 'transparent', border: 'none',
        color: 'var(--ink)',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        transition: 'background .15s ease, color .15s ease',
      }}
      onMouseEnter={(e)=> { e.currentTarget.style.background = 'var(--blue-50)'; e.currentTarget.style.color = 'var(--blue-700)'; }}
      onMouseLeave={(e)=> { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--ink)'; }}>
      {children}
    </button>
  );
}

function SearchModal({ open, onClose }) {
  const [query, setQuery] = useState('');
  const [allProducts, setAllProducts] = useState([]);
  const inputRef = React.useRef(null);

  useEffect(() => {
    if (!open) { setQuery(''); return; }
    setTimeout(() => inputRef.current && inputRef.current.focus(), 80);
    if (allProducts.length) return;
    fetch('/api/products?_=' + Date.now(), { cache: 'no-store' })
      .then(r => r.ok ? r.json() : null)
      .then(data => {
        if (data && Array.isArray(data.products)) setAllProducts(data.products);
      })
      .catch(() => {});
  }, [open]);

  const q = query.trim().toLowerCase();
  const results = q.length < 2 ? [] : allProducts.filter(p =>
    (p.name || '').toLowerCase().includes(q) ||
    (p.cat  || '').toLowerCase().includes(q)
  ).slice(0, 12);

  function onKey(e) { if (e.key === 'Escape') onClose(); }

  return (
    <>
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, zIndex: 120,
        background: 'rgba(8,51,68,0.45)', backdropFilter: 'blur(6px)',
        opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none',
        transition: 'opacity .2s ease',
      }}/>
      <div style={{
        position: 'fixed', top: 0, left: 0, right: 0, zIndex: 130,
        background: 'white',
        boxShadow: '0 20px 50px -10px rgba(8,51,68,0.22)',
        transform: open ? 'translateY(0)' : 'translateY(-110%)',
        transition: 'transform .3s cubic-bezier(.2,.7,.2,1)',
        maxHeight: '80vh', display: 'flex', flexDirection: 'column',
      }}>
        {/* Input row */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12,
          padding: '18px 28px', borderBottom: '1px solid var(--line)',
        }}>
          <Icon name="search" size={20} style={{ color: 'var(--ink-3)', flexShrink: 0 }}/>
          <input
            ref={inputRef}
            value={query}
            onChange={e => setQuery(e.target.value)}
            onKeyDown={onKey}
            placeholder="Buscar joias…"
            style={{
              flex: 1, border: 'none', outline: 'none',
              fontSize: 18, fontFamily: 'inherit', color: 'var(--ink)',
              background: 'transparent',
            }}
          />
          {query && (
            <button onClick={()=> setQuery('')} style={{
              border: 'none', background: 'var(--blue-50)', borderRadius: 8,
              width: 32, height: 32, cursor: 'pointer', color: 'var(--ink-3)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            }}><Icon name="close" size={14}/></button>
          )}
          <button onClick={onClose} style={{
            border: 'none', background: 'transparent', cursor: 'pointer',
            fontSize: 13, color: 'var(--ink-3)', padding: '4px 8px',
            fontFamily: 'var(--mono)', letterSpacing: '0.06em',
          }}>ESC</button>
        </div>

        {/* Results */}
        <div style={{ overflowY: 'auto', padding: '12px 28px 24px' }}>
          {q.length < 2 ? (
            <div style={{ padding: '32px 0', textAlign: 'center', color: 'var(--ink-3)', fontSize: 14 }}>
              Digite ao menos 2 letras para buscar
            </div>
          ) : results.length === 0 ? (
            <div style={{ padding: '32px 0', textAlign: 'center', color: 'var(--ink-3)', fontSize: 14 }}>
              Nenhum resultado para <strong style={{ color: 'var(--ink)' }}>"{query}"</strong>
            </div>
          ) : (
            <>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--mono)', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 14 }}>
                {results.length} resultado{results.length !== 1 ? 's' : ''}
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                {results.map(p => (
                  <a key={p.id || p.slug} href={`/produto?slug=${encodeURIComponent(p.slug || p.id)}`}
                    onClick={onClose}
                    style={{
                      display: 'grid', gridTemplateColumns: '56px 1fr auto',
                      gap: 14, alignItems: 'center',
                      padding: '10px 12px', borderRadius: 12,
                      textDecoration: 'none', color: 'inherit',
                      transition: 'background .12s ease',
                    }}
                    onMouseEnter={e => e.currentTarget.style.background = 'var(--blue-50)'}
                    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                  >
                    <div style={{ width: 56, height: 56, borderRadius: 10, overflow: 'hidden', background: '#f6f2ec', flexShrink: 0 }}>
                      {p.image
                        ? <img src={p.image} alt={p.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
                        : <JewelArt cat={p.cat} hue={p.hue} tone="soft" style={{ width: '100%', height: '100%' }}/>
                      }
                    </div>
                    <div>
                      <div style={{ fontSize: 14, fontWeight: 500 }}>{p.name}</div>
                      <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>{p.cat}</div>
                    </div>
                    <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--blue-800)', whiteSpace: 'nowrap' }}>
                      {p.price ? brl(p.price) : ''}
                    </div>
                  </a>
                ))}
              </div>
            </>
          )}
        </div>
      </div>
    </>
  );
}

function CartDrawer() {
  const cart = useCart();
  const [cep, setCep] = useState('');
  const [calc, setCalc] = useState('idle'); // idle | loading | done
  const [carriers, setCarriers] = useState([]);
  const [selected, setSelected] = useState(null);

  function maskCep(v) {
    const d = v.replace(/\D/g, '').slice(0, 8);
    return d.length > 5 ? d.slice(0,5) + '-' + d.slice(5) : d;
  }

  async function calcShipping() {
    if (cep.replace(/\D/g,'').length !== 8) return;
    setCalc('loading');
    setCarriers([]);
    setSelected(null);
    try {
      const r = await fetch('/api/shipping', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ cep }),
      });
      const data = await r.json().catch(() => ({}));
      if (!r.ok || !Array.isArray(data.carriers) || !data.carriers.length) {
        setCalc('error');
        return;
      }
      setCarriers(data.carriers);
      setSelected(data.carriers[0].id);
      setCalc('done');
    } catch {
      setCalc('error');
    }
  }
  const selectedCarrier = carriers.find(c => c.id === selected);
  const shippingCost = selectedCarrier ? selectedCarrier.price : 0;

  if (!cart) return null;
  return (
    <>
      {/* backdrop */}
      <div onClick={()=> cart.setOpen(false)} style={{
        position: 'fixed', inset: 0, zIndex: 80,
        background: 'rgba(8, 51, 68, 0.36)',
        backdropFilter: 'blur(4px)',
        opacity: cart.open ? 1 : 0,
        pointerEvents: cart.open ? 'auto' : 'none',
        transition: 'opacity .25s ease',
      }} />
      <aside style={{
        position: 'fixed', top: 0, right: 0, bottom: 0, zIndex: 90,
        width: 'min(460px, 100vw)',
        background: 'white',
        transform: cart.open ? 'translateX(0)' : 'translateX(110%)',
        transition: 'transform .35s cubic-bezier(.2,.7,.2,1)',
        display: 'flex', flexDirection: 'column',
        boxShadow: '-20px 0 60px -20px rgba(8,51,68,0.25)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '24px 28px', borderBottom: '1px solid var(--line)' }}>
          <h3 className="serif" style={{ margin: 0, fontSize: 26 }}>Sua sacola</h3>
          <IconBtn label="Fechar" onClick={()=> cart.setOpen(false)}><Icon name="close" /></IconBtn>
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: '20px 28px' }}>
          {cart.items.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '60px 12px', color: 'var(--ink-3)' }}>
              <div style={{ width: 64, height: 64, margin: '0 auto 16px', borderRadius: '50%', background: 'var(--grad-soft)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: 'var(--blue-600)' }}>
                <Icon name="bag" size={26} />
              </div>
              <div style={{ fontSize: 16, color: 'var(--ink)', fontWeight: 500, marginBottom: 6 }}>Sua sacola está vazia</div>
              <div style={{ fontSize: 13 }}>Descubra nossas peças artesanais</div>
              <button className="btn btn-primary" style={{ marginTop: 20 }} onClick={()=> cart.setOpen(false)}>
                Ver peças <Icon name="arrow" size={14}/>
              </button>
            </div>
          ) : (
            <>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                {cart.items.map(it => (
                  <div key={it.id} style={{ display: 'grid', gridTemplateColumns: '80px 1fr auto', gap: 14, alignItems: 'center' }}>
                    <div style={{ width: 80, height: 80, borderRadius: 12, overflow: 'hidden' }}>
                      <CartThumb image={it.ref.image || (it.ref.images && it.ref.images[0]?.url)} cat={it.ref.cat} hue={it.ref.hue} />
                    </div>
                    <div>
                      <div style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--mono)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>{it.ref.cat}</div>
                      <div className="serif" style={{ fontSize: 17, margin: '2px 0 6px' }}>{it.ref.name}</div>
                      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 4, border: '1px solid var(--line)', borderRadius: 999, padding: '2px' }}>
                        <button onClick={()=> cart.setQty(it.id, it.qty - 1)} style={qtyBtn}><Icon name="minus" size={12}/></button>
                        <span style={{ minWidth: 22, textAlign: 'center', fontSize: 13, fontWeight: 500 }}>{it.qty}</span>
                        <button onClick={()=> cart.setQty(it.id, it.qty + 1)} style={qtyBtn}><Icon name="plus" size={12}/></button>
                      </div>
                    </div>
                    <div style={{ textAlign: 'right' }}>
                      <div style={{ fontSize: 14, fontWeight: 600 }}>{brl(it.ref.price * it.qty)}</div>
                      <button onClick={()=> cart.remove(it.id)} style={{ background: 'none', border: 'none', fontSize: 11, color: 'var(--ink-3)', padding: 4, textDecoration: 'underline', marginTop: 6 }}>remover</button>
                    </div>
                  </div>
                ))}
              </div>

              {/* Shipping calculator */}
              <div style={{
                marginTop: 28, padding: 18,
                background: 'var(--blue-50)', borderRadius: 16,
                border: '1px solid var(--blue-100)',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
                  <Icon name="truck" size={16}/>
                  <strong style={{ fontSize: 13 }}>Calcular frete</strong>
                  <a href="https://buscacepinter.correios.com.br/" target="_blank" rel="noreferrer" style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--blue-700)' }}>
                    Não sei meu CEP
                  </a>
                </div>
                <div style={{ display: 'flex', gap: 8 }}>
                  <input
                    value={cep}
                    onChange={(e)=> setCep(maskCep(e.target.value))}
                    placeholder="00000-000"
                    onKeyDown={(e)=> { if (e.key === 'Enter') calcShipping(); }}
                    style={{
                      flex: 1, height: 42, padding: '0 14px',
                      border: '1px solid var(--line)', borderRadius: 10,
                      fontSize: 14, fontFamily: 'var(--mono)',
                      background: 'white', outline: 'none', letterSpacing: '0.06em',
                    }}/>
                  <button onClick={calcShipping}
                    disabled={cep.replace(/\D/g,'').length !== 8 || calc === 'loading'}
                    style={{
                      height: 42, padding: '0 18px', borderRadius: 10,
                      background: 'var(--grad)', color: 'white', border: 'none',
                      fontSize: 13, fontWeight: 500, cursor: 'pointer',
                      opacity: cep.replace(/\D/g,'').length !== 8 ? 0.45 : 1,
                    }}>
                    {calc === 'loading' ? '...' : 'Calcular'}
                  </button>
                </div>

                {calc === 'loading' && (
                  <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {[1,2,3].map(i=>(
                      <div key={i} style={{
                        height: 46, borderRadius: 10,
                        background: 'linear-gradient(90deg, #e0f2fe, #f0f9ff, #e0f2fe)',
                        backgroundSize: '200% 100%',
                        animation: 'shimmer 1.4s linear infinite',
                      }}/>
                    ))}
                  </div>
                )}

                {calc === 'error' && (
                  <div style={{ marginTop: 14, fontSize: 13, color: '#ef4444', textAlign: 'center', padding: '10px 0' }}>
                    Não foi possível calcular o frete. Tente novamente.
                  </div>
                )}

                {calc === 'done' && carriers.length > 0 && (
                  <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 8 }}>
                    <div style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--mono)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 2 }}>
                      Cotações para {cep}
                    </div>
                    {carriers.map((c,i)=>(
                      <label key={c.id} style={{
                        display: 'flex', alignItems: 'center', gap: 12,
                        padding: '12px 14px', borderRadius: 10,
                        background: 'white',
                        border: '1px solid ' + (selected === c.id ? 'var(--blue-500)' : 'var(--line)'),
                        cursor: 'pointer',
                        boxShadow: selected === c.id ? '0 0 0 3px rgba(6,182,212,0.15)' : 'none',
                        transition: 'all .15s ease',
                      }}>
                        <input type="radio" name="carrier"
                          checked={selected === c.id}
                          onChange={()=> setSelected(c.id)}
                          style={{ accentColor: 'var(--blue-600)', width: 16, height: 16 }}
                        />
                        <div style={{ flex: 1 }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, fontWeight: 500 }}>
                            {c.name}
                            {i === 0 && (
                              <span style={{ fontSize: 9, background: 'var(--grad)', color: 'white', padding: '2px 6px', borderRadius: 4, fontFamily: 'var(--mono)', letterSpacing: '0.08em' }}>
                                MAIS BARATO
                              </span>
                            )}
                          </div>
                          <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 1 }}>{c.days}</div>
                        </div>
                        <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--blue-800)' }}>{c.free ? 'Grátis' : brl(c.price)}</div>
                      </label>
                    ))}
                  </div>
                )}
              </div>
            </>
          )}
        </div>

        {cart.items.length > 0 && (
          <div style={{ borderTop: '1px solid var(--line)', padding: '20px 28px', background: 'var(--cream)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, color: 'var(--ink-2)', marginBottom: 6 }}>
              <span>Subtotal</span><span>{brl(cart.total)}</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, color: 'var(--ink-2)', marginBottom: 12 }}>
              <span>Frete {selectedCarrier ? `· ${selectedCarrier.name.split(' · ')[0]}` : ''}</span>
              <span>{selectedCarrier ? brl(shippingCost) : <em style={{ color: 'var(--ink-3)', fontStyle: 'normal' }}>calcule acima</em>}</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 18, fontWeight: 600, marginBottom: 16 }}>
              <span>Total</span><span>{brl(cart.total + shippingCost)}</span>
            </div>
            <button className="btn btn-primary" style={{ width: '100%', height: 54 }} onClick={()=> {
              // Persist cart + shipping to sessionStorage so the checkout page can read it
              try {
                sessionStorage.setItem('lua_cart', JSON.stringify(cart.items.map(it => ({
                  id: it.id,
                  name: it.ref.name,
                  cat: it.ref.cat,
                  price: it.ref.price,
                  qty: it.qty,
                  hue: it.ref.hue,
                  image: it.ref.image || (it.ref.images && it.ref.images[0]?.url) || null,
                  variant: it.ref.variant || it.ref.cat,
                }))));
                if (selectedCarrier){
                  sessionStorage.setItem('lua_shipping', JSON.stringify({
                    cep, name: selectedCarrier.name, price: selectedCarrier.price, days: selectedCarrier.days,
                  }));
                }
              } catch(e){}
              window.location.href = 'finalizar-compra.html';
            }}>
              Finalizar compra <Icon name="arrow" size={16}/>
            </button>
            <div style={{ textAlign: 'center', fontSize: 11, color: 'var(--ink-3)', marginTop: 10, fontFamily: 'var(--mono)' }}>
              PAGAMENTO 100% SEGURO · PIX · CARTÃO · BOLETO
            </div>
          </div>
        )}
      </aside>
    </>
  );
}

const qtyBtn = {
  width: 24, height: 24, borderRadius: '50%',
  background: 'white', border: 'none', cursor: 'pointer',
  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
  color: 'var(--ink-2)',
};

const RECAPTCHA_SITE_KEY = '6LflNvEsAAAAAFvURm1GTUbGd1QmYHL9Ez0u0uAM';

// Login modal
function LoginModal({ open, onClose, message }) {
  const auth = useAuth();
  const [mode, setMode] = useState('login');
  const [name, setName]         = useState('');
  const [email, setEmail]       = useState('');
  const [password, setPassword] = useState('');
  const [confirm, setConfirm]   = useState('');
  const [showPwd, setShowPwd]   = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const [busy, setBusy]         = useState(false);
  const [error, setError]       = useState(null);
  const recaptchaRef    = useRef(null);
  const recaptchaWidget = useRef(null);
  // stage: 'form' | 'check-email' | 'needs-verify'
  const [stage, setStage] = useState('form');
  const [verifyEmail, setVerifyEmail] = useState('');
  const [resendBusy, setResendBusy]   = useState(false);
  const [resendOK, setResendOK]       = useState(false);

  // Reset ao abrir
  useEffect(() => {
    if (open) {
      setError(null);
      setBusy(false);
      setStage('form');
      setResendOK(false);
      setConfirm('');
      setShowPwd(false);
      setShowConfirm(false);
      recaptchaWidget.current = null;
    }
  }, [open]);

  // Renderiza widget reCAPTCHA quando modo signup estiver visível
  useEffect(() => {
    if (!open || mode !== 'signup' || stage !== 'form') {
      recaptchaWidget.current = null;
      return;
    }
    let timer;
    function tryRender() {
      if (!recaptchaRef.current) return;
      if (recaptchaWidget.current !== null) return;
      if (!window.grecaptcha || !window.grecaptcha.render) {
        timer = setTimeout(tryRender, 150);
        return;
      }
      recaptchaRef.current.innerHTML = '';
      recaptchaWidget.current = window.grecaptcha.render(recaptchaRef.current, {
        sitekey: RECAPTCHA_SITE_KEY,
        theme: 'light',
      });
    }
    tryRender();
    return () => clearTimeout(timer);
  }, [open, mode, stage]);

  async function onSubmit(e){
    e.preventDefault();
    setError(null);
    if (mode === 'signup') {
      if (password !== confirm) return setError('As senhas não coincidem.');
      const captchaToken = window.grecaptcha && recaptchaWidget.current !== null
        ? window.grecaptcha.getResponse(recaptchaWidget.current)
        : '';
      if (!captchaToken) return setError('Confirme que você não é um robô.');
    }
    setBusy(true);
    try {
      if (mode === 'login') {
        await auth.login(email, password);
        setName(''); setEmail(''); setPassword('');
      } else {
        const captchaToken = window.grecaptcha && recaptchaWidget.current !== null
          ? window.grecaptcha.getResponse(recaptchaWidget.current)
          : '';
        const r = await auth.signup(name, email, password, captchaToken);
        setVerifyEmail(r.email || email);
        setStage('check-email');
      }
    } catch (err) {
      if (window.grecaptcha && recaptchaWidget.current !== null) {
        window.grecaptcha.reset(recaptchaWidget.current);
      }
      if (err.code === 'email_not_verified') {
        setVerifyEmail(err.email || email);
        setStage('needs-verify');
      } else {
        setError(err.message || 'Algo deu errado. Tente de novo.');
      }
    } finally {
      setBusy(false);
    }
  }

  async function onResend(){
    setResendBusy(true);
    setResendOK(false);
    try {
      await auth.resendVerification(verifyEmail);
      setResendOK(true);
    } catch(e) {
      setError(e.message || 'Não foi possível reenviar.');
    } finally {
      setResendBusy(false);
    }
  }

  return (
    <>
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, zIndex: 100,
        background: 'rgba(8,51,68,0.4)', backdropFilter: 'blur(6px)',
        opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none',
        transition: 'opacity .25s ease',
      }}/>
      <div style={{
        position: 'fixed', inset: 0, zIndex: 110,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 20,
        opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none',
        transition: 'opacity .25s ease',
      }}>
        <div style={{
          width: 'min(880px, 100%)',
          background: 'white', borderRadius: 24,
          overflow: 'hidden',
          display: 'grid', gridTemplateColumns: '1fr 1fr',
          maxHeight: 'calc(100vh - 40px)',
          transform: open ? 'scale(1)' : 'scale(0.96)',
          transition: 'transform .25s ease',
          boxShadow: '0 40px 80px -20px rgba(8,51,68,0.35)',
        }} className="login-grid">
          {/* visual side */}
          <div className="login-modal-visual" style={{
            background: 'var(--grad-deep)', color: 'white',
            padding: '48px 40px', position: 'relative', overflow: 'hidden',
            display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
            minHeight: 480,
          }}>
            <div style={{
              position: 'absolute', top: -80, right: -80,
              width: 320, height: 320, borderRadius: '50%',
              background: 'radial-gradient(circle at 30% 30%, rgba(255,255,255,0.32), transparent 60%)',
            }}/>
            <Logo light size={22}/>
            <div style={{ position: 'relative' }}>
              <div className="eyebrow" style={{ color: 'rgba(255,255,255,0.7)' }}>Sua conta</div>
              <h2 className="serif" style={{ fontSize: 38, lineHeight: 1.05, margin: '12px 0 16px', fontWeight: 400 }}>
                Bem-vinda de volta à Lua Azul.
              </h2>
              <p style={{ fontSize: 14, color: 'rgba(255,255,255,0.78)', lineHeight: 1.6, margin: 0 }}>
                Acompanhe seus pedidos, salve favoritos e tenha um endereço de entrega pronto pra próxima compra.
              </p>
            </div>
            <div style={{ display: 'flex', gap: 16, fontSize: 12, color: 'rgba(255,255,255,0.7)', fontFamily: 'var(--mono)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>
              <span>Feito à mão</span>
              <span>Salvador · BA</span>
            </div>
          </div>

          {/* form side */}
          <div style={{ padding: '40px 40px', position: 'relative', overflowY: 'auto' }}>
            <button onClick={onClose} aria-label="Fechar" style={{
              position: 'absolute', top: 16, right: 16,
              width: 36, height: 36, borderRadius: '50%',
              border: 'none', background: 'var(--blue-50)', cursor: 'pointer',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            }}><Icon name="close" size={16}/></button>

            {stage === 'check-email' ? (
              <CheckEmailStage email={verifyEmail} onResend={onResend} resendBusy={resendBusy} resendOK={resendOK} onSwitchToLogin={()=> { setStage('form'); setMode('login'); }}/>
            ) : stage === 'needs-verify' ? (
              <NeedsVerifyStage email={verifyEmail} onResend={onResend} resendBusy={resendBusy} resendOK={resendOK} onBack={()=> setStage('form')}/>
            ) : (
              <>
            <div style={{ display: 'flex', gap: 8, background: 'var(--blue-50)', padding: 4, borderRadius: 999, width: 'fit-content', marginBottom: 20 }}>
              <button onClick={()=> { setMode('login'); setError(null); setConfirm(''); setShowPwd(false); setShowConfirm(false); }} style={tabBtn(mode === 'login')}>Entrar</button>
              <button onClick={()=> { setMode('signup'); setError(null); recaptchaWidget.current = null; }} style={tabBtn(mode === 'signup')}>Cadastrar</button>
            </div>

            <h3 className="serif" style={{ fontSize: 30, margin: '0 0 6px', fontWeight: 500 }}>
              {mode === 'login' ? 'Olá novamente' : 'Crie sua conta'}
            </h3>
            <p style={{ fontSize: 13, color: 'var(--ink-3)', margin: '0 0 16px' }}>
              {mode === 'login' ? 'Entre pra ver pedidos e favoritos.' : 'Em 30 segundos, com email e senha.'}
            </p>

            {/* Mensagem contextual (ex: "Crie sua conta pra salvar essa peça nos favoritos") */}
            {message && (
              <div style={{
                background: 'linear-gradient(135deg, #ecfeff 0%, #f0fdfa 100%)',
                border: '1px solid var(--blue-200)',
                color: 'var(--blue-800)',
                padding: '10px 14px',
                borderRadius: 12,
                fontSize: 13,
                marginBottom: 16,
                display: 'flex', alignItems: 'center', gap: 10,
              }}>
                <Icon name="heart" size={16}/>
                <span>{message}</span>
              </div>
            )}

            {/* Google OAuth */}
            <button
              type="button"
              onClick={() => { window.location.href = '/api/auth/google'; }}
              style={{
                width: '100%', height: 46,
                border: '1px solid var(--line)', borderRadius: 12,
                background: 'white', cursor: 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
                fontSize: 14, fontFamily: 'inherit', fontWeight: 500,
                color: 'var(--ink-1)', marginBottom: 4,
                transition: 'background .15s, border-color .15s',
              }}
              onMouseEnter={(e) => { e.currentTarget.style.background = '#f8fafc'; e.currentTarget.style.borderColor = 'var(--blue-300)'; }}
              onMouseLeave={(e) => { e.currentTarget.style.background = 'white'; e.currentTarget.style.borderColor = 'var(--line)'; }}
            >
              <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true">
                <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
                <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
                <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z" fill="#FBBC05"/>
                <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
              </svg>
              Continuar com Google
            </button>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, margin: '4px 0 8px' }}>
              <hr style={{ flex: 1, border: 'none', borderTop: '1px solid var(--line)' }}/>
              <span style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>ou</span>
              <hr style={{ flex: 1, border: 'none', borderTop: '1px solid var(--line)' }}/>
            </div>

            {/* Erros do servidor */}
            {error && (
              <div style={{
                background: '#fef2f4',
                border: '1px solid #fbcfd6',
                color: '#a01a3c',
                padding: '10px 14px',
                borderRadius: 12,
                fontSize: 13,
                marginBottom: 12,
              }}>
                {error}
              </div>
            )}

            <form onSubmit={onSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {mode === 'signup' && (
                <Input label="Nome completo" placeholder="Maria Silva"
                  value={name} onChange={(e)=> setName(e.target.value)} required
                  autoComplete="name"/>
              )}
              <Input label="Email" type="email" placeholder="voce@email.com"
                value={email} onChange={(e)=> setEmail(e.target.value)} required
                autoComplete="email"/>
              <PasswordInput label="Senha" placeholder="••••••••"
                value={password} onChange={(e)=> setPassword(e.target.value)} required
                autoComplete={mode === 'login' ? 'current-password' : 'new-password'}
                minLength={mode === 'signup' ? 6 : undefined}
                show={showPwd} onToggle={()=> setShowPwd(v => !v)}/>
              {mode === 'signup' && (<>
                <PasswordInput label="Confirmar senha" placeholder="••••••••"
                  value={confirm} onChange={(e)=> setConfirm(e.target.value)} required
                  autoComplete="new-password" minLength={6}
                  show={showConfirm} onToggle={()=> setShowConfirm(v => !v)}/>
                <div ref={recaptchaRef} style={{ margin: '4px 0' }}></div>
              </>)}
              {mode === 'login' && (
                <div style={{ textAlign: 'right', fontSize: 12 }}>
                  <a href="#" style={{ color: 'var(--blue-600)' }}>Esqueci minha senha</a>
                </div>
              )}
              <button type="submit" disabled={busy} className="btn btn-primary" style={{
                height: 50, marginTop: 6,
                opacity: busy ? 0.7 : 1,
                cursor: busy ? 'wait' : 'pointer',
              }}>
                {busy
                  ? (mode === 'login' ? 'Entrando…' : 'Criando conta…')
                  : (mode === 'login' ? 'Entrar'    : 'Criar conta')}
              </button>
            </form>

            {/* Afiliadas link — só mostra se affiliates_enabled (default true) */}
            {(window.SITE_CONFIG?.affiliates_enabled !== false) && <a href="trabalhe-conosco.html" style={{
              display: 'flex', alignItems: 'center', gap: 12,
              marginTop: 22, padding: '14px 16px',
              background: 'linear-gradient(135deg, #ecfeff 0%, #f0fdfa 100%)',
              border: '1px solid var(--blue-100)',
              borderRadius: 14,
              transition: 'transform .15s ease, box-shadow .15s ease',
            }}
            onMouseEnter={(e)=> { e.currentTarget.style.transform = 'translateY(-1px)'; e.currentTarget.style.boxShadow = '0 12px 24px -12px rgba(8,51,68,0.18)'; }}
            onMouseLeave={(e)=> { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = 'none'; }}>
              <span style={{
                width: 36, height: 36, borderRadius: 10,
                background: 'var(--grad)', color: 'white',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                flexShrink: 0,
              }}>
                <Icon name="sparkle" size={16}/>
              </span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--blue-800)' }}>Quer ser afiliada Lua Azul?</div>
                <div style={{ fontSize: 12, color: 'var(--ink-2)', marginTop: 2 }}>10% de comissão · pagamento todo dia 1º</div>
              </div>
              <Icon name="arrow" size={16}/>
            </a>}
              </>
            )}
          </div>
        </div>
      </div>
    </>
  );
}

// ---------- stages "verifique seu email" ----------

function CheckEmailStage({ email, onResend, resendBusy, resendOK, onSwitchToLogin }) {
  return (
    <div style={{ paddingTop: 6 }}>
      <div style={{
        width: 64, height: 64, borderRadius: '50%',
        background: 'var(--grad)', color: 'white',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        marginBottom: 18,
      }}>
        <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 7l9 6 9-6"/></svg>
      </div>
      <h3 className="serif" style={{ fontSize: 26, margin: '0 0 8px', fontWeight: 500 }}>Confira seu e-mail</h3>
      <p style={{ fontSize: 14, color: 'var(--ink-2)', margin: '0 0 6px', lineHeight: 1.55 }}>
        Compre mais rápido e acompanhe seus pedidos em um só lugar! Você está a um passo de criar sua conta.
      </p>
      <p style={{ fontSize: 14, color: 'var(--ink-2)', margin: '0 0 22px', lineHeight: 1.55 }}>
        Enviamos um link para <strong style={{ color: 'var(--blue-800)' }}>{email}</strong> para validar seu e-mail.
      </p>
      <div style={{
        background: 'var(--cream)', borderRadius: 12, padding: '14px 16px',
        fontSize: 13, color: 'var(--ink-2)', marginBottom: 16,
      }}>
        Ainda não recebeu?{' '}
        <button onClick={onResend} disabled={resendBusy} style={{
          background: 'transparent', border: 'none',
          color: 'var(--blue-700)', cursor: resendBusy ? 'wait' : 'pointer',
          textDecoration: 'underline', font: 'inherit', padding: 0,
        }}>
          {resendBusy ? 'Enviando…' : 'Enviar o link novamente'}
        </button>
        {resendOK && <span style={{ marginLeft: 8, color: 'var(--blue-700)', fontWeight: 500 }}>✓ Enviado!</span>}
      </div>
      <button onClick={onSwitchToLogin} className="btn btn-ghost" style={{ width: '100%', height: 46 }}>
        Já confirmei · Entrar
      </button>
    </div>
  );
}

function NeedsVerifyStage({ email, onResend, resendBusy, resendOK, onBack }) {
  return (
    <div style={{ paddingTop: 6 }}>
      <div style={{
        width: 56, height: 56, borderRadius: '50%',
        background: '#fff7ed', color: '#c2410c',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        marginBottom: 18,
      }}>
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg>
      </div>
      <h3 className="serif" style={{ fontSize: 26, margin: '0 0 8px', fontWeight: 500 }}>Confirme seu e-mail antes de entrar</h3>
      <p style={{ fontSize: 14, color: 'var(--ink-2)', margin: '0 0 22px', lineHeight: 1.55 }}>
        Sua conta <strong style={{ color: 'var(--blue-800)' }}>{email}</strong> ainda não foi confirmada.
        Verifique sua caixa de entrada e clique no link que enviamos.
      </p>
      <div style={{ display: 'flex', gap: 10 }}>
        <button onClick={onBack} className="btn btn-ghost" style={{ flex: 1, height: 46 }}>
          Voltar
        </button>
        <button onClick={onResend} disabled={resendBusy} className="btn btn-primary" style={{ flex: 1, height: 46 }}>
          {resendBusy ? 'Enviando…' : 'Reenviar link'}
        </button>
      </div>
      {resendOK && (
        <div style={{ marginTop: 12, padding: '10px 14px', background: '#ecfdf5', color: '#065f46', borderRadius: 10, fontSize: 13 }}>
          ✓ Email reenviado. Confira sua caixa de entrada.
        </div>
      )}
    </div>
  );
}

function tabBtn(active) {
  return {
    border: 'none', cursor: 'pointer',
    padding: '8px 18px', fontSize: 13, fontWeight: 500,
    borderRadius: 999,
    background: active ? 'white' : 'transparent',
    color: active ? 'var(--blue-700)' : 'var(--ink-3)',
    boxShadow: active ? '0 4px 12px -4px rgba(8,51,68,0.18)' : 'none',
    transition: 'all .18s ease',
  };
}

function Input({ label, ...rest }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <span style={{ fontSize: 12, color: 'var(--ink-2)', fontWeight: 500 }}>{label}</span>
      <input {...rest} style={{
        height: 46, padding: '0 14px',
        border: '1px solid var(--line)', borderRadius: 12,
        fontSize: 14, fontFamily: 'inherit',
        background: 'white',
        outline: 'none',
        transition: 'border-color .15s, box-shadow .15s',
      }}
      onFocus={(e)=> { e.target.style.borderColor = 'var(--blue-500)'; e.target.style.boxShadow = '0 0 0 4px rgba(6,182,212,0.15)'; }}
      onBlur={(e)=> { e.target.style.borderColor = 'var(--line)'; e.target.style.boxShadow = 'none'; }}
      />
    </label>
  );
}

function PasswordInput({ label, show, onToggle, ...rest }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <span style={{ fontSize: 12, color: 'var(--ink-2)', fontWeight: 500 }}>{label}</span>
      <div style={{ position: 'relative' }}>
        <input {...rest} type={show ? 'text' : 'password'} style={{
          width: '100%', height: 46, padding: '0 44px 0 14px',
          border: '1px solid var(--line)', borderRadius: 12,
          fontSize: 14, fontFamily: 'inherit',
          background: 'white', outline: 'none',
          transition: 'border-color .15s, box-shadow .15s',
          boxSizing: 'border-box',
        }}
        onFocus={(e)=> { e.target.style.borderColor = 'var(--blue-500)'; e.target.style.boxShadow = '0 0 0 4px rgba(6,182,212,0.15)'; }}
        onBlur={(e)=> { e.target.style.borderColor = 'var(--line)'; e.target.style.boxShadow = 'none'; }}
        />
        <button type="button" onClick={onToggle} tabIndex={-1} style={{
          position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)',
          border: 'none', background: 'none', cursor: 'pointer',
          color: 'var(--ink-3)', padding: 4,
          display: 'inline-flex', alignItems: 'center',
        }}>
          <Icon name={show ? 'eye-off' : 'eye'} size={16}/>
        </button>
      </div>
    </label>
  );
}

// Floating WhatsApp button
function WhatsAppFab() {
  const [hover, setHover] = useState(false);
  return (
    <a href="https://wa.me/5571999181376" target="_blank" rel="noreferrer"
      className="whatsapp-fab"
      onMouseEnter={()=> setHover(true)} onMouseLeave={()=> setHover(false)}
      style={{
        position: 'fixed', bottom: 24, right: 24, zIndex: 70,
        background: 'linear-gradient(135deg, #25d366, #128c7e)',
        color: 'white', borderRadius: 999,
        height: 60, padding: hover ? '0 22px 0 18px' : '0', width: hover ? 'auto' : 60,
        display: 'inline-flex', alignItems: 'center', gap: 10,
        justifyContent: 'center',
        boxShadow: '0 14px 32px -8px rgba(18,140,126,0.55)',
        transition: 'all .25s cubic-bezier(.2,.7,.2,1)',
        overflow: 'hidden', whiteSpace: 'nowrap',
        fontSize: 14, fontWeight: 500,
      }}>
      <Icon name="whatsapp" size={26}/>
      {hover && <span className="wa-label">Atendimento</span>}
    </a>
  );
}

Object.assign(window, { Nav, LoginModal, WhatsAppFab });
